Spring - @Conditional全解
【摘要】
文章目录
作用扩展注解CodeBean1 Bean2自定义比较规则配置类测试类
如何校验自动配置类是否生效
作用
必须是@Conditional指定的条件成立,才给容器中添加...
作用
必须是@Conditional指定的条件成立,才给容器中添加组件,配置配里面的所有内容才生效
扩展注解
| @Conditional扩展注解 | 作用(判断是否满足当前指定条件) |
|---|---|
| @ConditionalOnJava | 系统的java版本是否符合要求 |
| @ConditionalOnBean | 容器中存在指定Bean; |
| @ConditionalOnMissingBean | 容器中不存在指定Bean; |
| @ConditionalOnExpression | 满足SpEL表达式指定 |
| @ConditionalOnClass | 系统中有指定的类 |
| @ConditionalOnMissingClass | 系统中没有指定的类 |
| @ConditionalOnSingleCandidate | 容器中只有一个指定的Bean,或者这个Bean是首选Bean |
| @ConditionalOnProperty | 系统中指定的属性是否有指定的值 |
| @ConditionalOnResource | 类路径下是否存在指定资源文件 |
| @ConditionalOnWebApplication | 当前是web环境 |
| @ConditionalOnNotWebApplication | 当前不是web环境 |
| @ConditionalOnJndi | JNDI存在指定项 |
Code

Bean1 Bean2
public class Bean1 {
public Bean1() {
System.out.println("我是Bean1的构造方法");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
public class Bean2 {
public Bean2() {
System.out.println("我是Bean2的构造方法");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
自定义比较规则
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class ArtisanCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//判断容器中是否有bean1的组件
if(context.getBeanFactory().containsBean("bean1")) {
return true;
}
return false;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
配置类
import com.tuling.testconditional.compent.Bean1;
import com.tuling.testconditional.compent.Bean2;
import com.tuling.testconditional.condition.ArtisanCondition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
public class MainConfig {
@Bean
public Bean1 bean1() {
return new Bean1();
}
// 如果满足ArtisanCondition中定义的规则,就实例化Bean2
@Bean
@Conditional(value = ArtisanCondition.class)
public Bean2 bean2() {
return new Bean2();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
测试类
import com.tuling.testconditional.config.MainConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class);
for(String beanName:ctx.getBeanDefinitionNames()) {
System.out.println("beanName:"+beanName);
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16

为了测试效果

重新测试

如何校验自动配置类是否生效
配置文件中增加
启用 debug=true属性;来让控制台打印自动配置报告

文章来源: artisan.blog.csdn.net,作者:小小工匠,版权归原作者所有,如需转载,请联系作者。
原文链接:artisan.blog.csdn.net/article/details/115413988
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)