Spring中@Conditional注解的原理是什么,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
@Conditional是Spring4新提供的注解,它的作用是根据某个条件加载特定的bean。
我们需要创建实现类来实现Condition接口,这是Condition的源码
public interface Condition {
boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);
}
所以我们需要重写matches方法,该方法返回boolean类型。
首先我们准备根据不同的操作系统环境进行对容器加载不同的bean,先创建Person
public class Person {
}
创建实现类LinuxCondition和WindowCondiction,
LinuxCondition:
public class WindowCondiction implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return true;
}
}
WindowCondiction:
public class LinuxCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return true;
}
}
配置类:给相应的bean加上 @Conditional注解,里面的括号将返回boolean类型,返回true则加载bean
@Configuration
public class MainConfig {
@Profile("window")
@Conditional(WindowCondiction.class)
@Bean
public Person person01(){
return new Person("李思",30);
}
@Profile("linux")
@Conditional(LinuxCondition.class)
@Bean
public Person person02(){
return new Person("wangwu",35);
}
}
测试:现在是按照linux环境,@Profile注解先匹配linux的bean,再根据@Conditional 返回的类型判断是否加载bean,这里都设置返回true,所以应该打印
Person{name='wangwu', age=35}
public class CondictionTest {
@Test
public void test(){
//创建容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
//设置需要激活的环境
applicationContext.getEnvironment().setActiveProfiles("linux");
//设置主配置类
applicationContext.register(MainProfileConfig.class);
//启动刷新容器
applicationContext.refresh();
String[] beanNamesForType = applicationContext.getBeanNamesForType(DataSource.class);
for (String name : beanNamesForType){
System.out.println(name);
}
applicationContext.close();
}
}
如果把LinuxCondition的返回值该为false,会报找不到bean的异常
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.springbean.Person' available
关于Spring中@Conditional注解的原理是什么问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。