Issue
I want to design such feature with SpringBoot. Say there are 2 projects 'projectA' and 'projectB', which B is a java library and A is depends on B. there is a Filter 'FilterA' defined on B ,
now I would like add a custom annotation @EnableCustomBean. Only if I put the @EnableCustomBean(class=FilterA.class), the FilterA will be work on projectA, I've search some about spring @Conditional , but still no idea
Solution
Option 1:
You don't need any custom annotations - just use @ConditionalOnProperty:
@Bean
@ConditionalOnProperty(prefix = "foo", name = "bar")
public YourFilterClass yourFilterClass() {
...
}
This bean will only be created if you define the foo.bar property
Option 2:
To satisfy your requirement of using custom Annotation you can:
define your own annotation
define custom condition:
class MyCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return AnnotationUtils.getAnnotation(MainApplication.getClass(),YourCustomAnnotation.class) != null; } }
Use you custom condition with
@Conditional
over@Bean
definition:@Bean @Conditional(MyCondition.class) public YourFilterClass yourFilterClass() { ... }
Answered By - J Asgarov
Answer Checked By - Katrina (JavaFixing Volunteer)