说明
首先我们看下 Conditional注解
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
Class<? extends Condition>[] value();
}
可以看出,需要使用Conditional
注解必须实现Condition
接口。
@FunctionalInterface
public interface Condition {
boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
}
Demo
@Data
public class Test{
private String id="@Bean";
}
@Data
public class Test2{
private String id="@Conditional";
}
public class TestCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// 条件判断
return false;
}
}
/**
注册bean
*/
@Configuration
public class TestConfiguration {
@Bean
@Conditional(TestCondition.class)
public Test test() {
return new Test();
}
@Bean
@Conditional(TestCondition.class)
public Test2 test2() {
return new Test2();
}
}
网友评论