SpringBoot 常用条件注解
注解 | 条件断类 | 备注 |
---|---|---|
@ConditionalOnClass | OnClassCondition | 如果Classpath 存在匹配到class,就创建 |
@ConditionalOnMissingClass | OnClassCondition | 如果Classpath 不存在匹配到class,就创建 |
@ConditionalOnBean | OnBeanCondition | 如果Spring容器中 存在匹配到Bean,就创建 |
@ConditionalOnMissingBean | OnBeanCondition | 如果Spring容器 存在匹配到Bean,就创建 |
@ConditionalOnProperty | OnPropertyCondition | 如果Spring容器 存在匹配到属性,就创建 |
@ConditionalOnResource | OnResourceCondition | 如果ClassPath下存在匹配到resource,就创建 |
@ConditionalOnWebApplication | OnWebApplicationCondition | 如果应用类型不满足type(ANY、SERVLET、REACTIVE),就创建 |
@ConditionalOnNotWebApplication | OnWebApplicationCondition | 如果应用类型不满足type(ANY、SERVLET、REACTIVE),就创建 |
@ConditionalOnExpression | OnExpressionCondition | 基于SpringEL表达式进行判断,如果true就创建 |
自定义条件注解
1.编写条件Class
继承Condition
或者Condition
子类SpringBootCondition
public class TestOnCondition extends SpringBootCondition {
private String defaultValue = "test";
@Override
//关键点:实现业务逻辑判断
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
Map<String, Object> map = metadata.getAnnotationAttributes(TestConditional.class.getName());
String value = String.valueOf(map.get("value"));
if (defaultValue.equals(value)) {
return ConditionOutcome.match(ConditionMessage.forCondition(TestConditional.class)
.because("match"));
} else {
return ConditionOutcome.noMatch(ConditionMessage.forCondition(TestConditional.class)
.because("not match"));
}
}
}
2.编写自定义注解
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(TestOnCondition.class)
public @interface TestConditional {
String value() default "";
}
3.实体类
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
测试:
@SpringBootApplication
public class Demo01Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Demo01Application.class, args);
Object test = context.getBean("greeting");
System.out.println(test);
}
@Bean
@TestConditional("test")
public Greeting greeting(){
return new Greeting(1,"test");
}
}
结果
把@TestConditional(“test”)改成@TestConditional(“test1”)
结果: