版权声明:本文为博主原创文章,未经博主允许不得转载。					https://blog.csdn.net/xcy1193068639/article/details/81491071				</div>
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-f57960eb32.css">
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-f57960eb32.css">
<div class="htmledit_views" id="content_views">
<h2><a name="t0"></a>前言:</h2>

@Conditional是Spring4新提供的注解,它的作用是按照一定的条件进行判断,满足条件给容器注册bean。

@Conditional的定义:


  1. //此注解可以标注在类和方法上
  2. @Target({ElementType.TYPE, ElementType.METHOD})
  3. @Retention(RetentionPolicy.RUNTIME)
  4. @Documented
  5. public @interface Conditional {
  6. Class<? extends Condition>[] value();
  7. }

从代码中可以看到,需要传入一个Class数组,并且需要继承Condition接口:


  1. public interface Condition {
  2. boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);
  3. }

Condition是个接口,需要实现matches方法,返回true则注入bean,false则不注入。

示例:

首先,创建Person类:


  1. public class Person {
  2. private String name;
  3. private Integer age;
  4. public String getName() {
  5. return name;
  6. }
  7. public void setName(String name) {
  8. this.name = name;
  9. }
  10. public Integer getAge() {
  11. return age;
  12. }
  13. public void setAge(Integer age) {
  14. this.age = age;
  15. }
  16. public Person(String name, Integer age) {
  17. this.name = name;
  18. this.age = age;
  19. }
  20. @Override
  21. public String toString() {
  22. return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
  23. }
  24. }

创建BeanConfig类,用于配置两个Person实例并注入,一个是比尔盖茨,一个是林纳斯。


  1. @Configuration
  2. public class BeanConfig {
  3. @Bean(name = "bill")
  4. public Person person1(){
  5. return new Person("Bill Gates",62);
  6. }
  7. @Bean("linus")
  8. public Person person2(){
  9. return new Person("Linus",48);
  10. }
  11. }

接着写一个测试类进行验证这两个Bean是否注入成功。


  1. public class ConditionalTest {
  2. AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
  3. @Test
  4. public void test1(){
  5. Map<String, Person> map = applicationContext.getBeansOfType(Person.class);
  6. System.out.println(map);
  7. }
  8. }

运行,输出结果是这样的,两个Person实例被注入进容器。

这是一个简单的例子,现在问题来了,如果我想根据当前操作系统来注入Person实例,windows下注入bill,linux下注入linus,怎么实现呢?

这就需要我们用到@Conditional注解了,前言中提到,需要实现Condition接口,并重写方法来自定义match规则。

首先,创建一个WindowsCondition类:


  1. public class WindowsCondition implements Condition {
  2. /**
  3. * @param conditionContext:判断条件能使用的上下文环境
  4. * @param annotatedTypeMetadata:注解所在位置的注释信息
  5. * */
  6. @Override
  7. public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
  8. //获取ioc使用的beanFactory
  9. ConfigurableListableBeanFactory beanFactory = conditionContext.getBeanFactory();
  10. //获取类加载器
  11. ClassLoader classLoader = conditionContext.getClassLoader();
  12. //获取当前环境信息
  13. Environment environment = conditionContext.getEnvironment();
  14. //获取bean定义的注册类
  15. BeanDefinitionRegistry registry = conditionContext.getRegistry();
  16. //获得当前系统名
  17. String property = environment.getProperty("os.name");
  18. //包含Windows则说明是windows系统,返回true
  19. if (property.contains("Windows")){
  20. return true;
  21. }
  22. return false;
  23. }
  24. }

matches方法的两个参数的意思在注释中讲述了,值得一提的是,conditionContext提供了多种方法,方便获取各种信息,也是SpringBoot中 @ConditonalOnXX注解多样扩展的基础。

接着,创建LinuxCondition类:


  1. public class LinuxCondition implements Condition {
  2. @Override
  3. public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
  4. Environment environment = conditionContext.getEnvironment();
  5. String property = environment.getProperty("os.name");
  6. if (property.contains("Linux")){
  7. return true;
  8. }
  9. return false;
  10. }
  11. }

接着就是使用这两个类了,因为此注解可以标注在方法上和类上,所以分开测试:

标注在方法上:

修改BeanConfig:


  1. @Configuration
  2. public class BeanConfig {
  3. //只有一个类时,大括号可以省略
  4. //如果WindowsCondition的实现方法返回true,则注入这个bean
  5. @Conditional({WindowsCondition.class})
  6. @Bean(name = "bill")
  7. public Person person1(){
  8. return new Person("Bill Gates",62);
  9. }
  10. //如果LinuxCondition的实现方法返回true,则注入这个bean
  11. @Conditional({LinuxCondition.class})
  12. @Bean("linus")
  13. public Person person2(){
  14. return new Person("Linus",48);
  15. }
  16. }

修改测试方法,使其可以打印当前系统名:


  1. @Test
  2. public void test1(){
  3. String osName = applicationContext.getEnvironment().getProperty("os.name");
  4. System.out.println("当前系统为:" + osName);
  5. Map<String, Person> map = applicationContext.getBeansOfType(Person.class);
  6. System.out.println(map);
  7. }

运行结果如下:

我是运行在windows上的所以只注入了bill,嗯,没毛病。

接着实验linux下的情况,不能运行在linux下,但可以修改运行时参数:

修改后启动测试方法:

一个方法只能注入一个bean实例,所以@Conditional标注在方法上只能控制一个bean实例是否注入。

标注在类上:

一个类中可以注入很多实例,@Conditional标注在类上就决定了一批bean是否注入。

我们试一下,将BeanConfig改写,这时,如果WindowsCondition返回true,则两个Person实例将被注入(注意:上一个测试将os.name改为linux,这是我将把这个参数去掉):


  1. @Conditional({WindowsCondition.class})
  2. @Configuration
  3. public class BeanConfig {
  4. @Bean(name = "bill")
  5. public Person person1(){
  6. return new Person("Bill Gates",62);
  7. }
  8. @Bean("linus")
  9. public Person person2(){
  10. return new Person("Linus",48);
  11. }
  12. }

结果两个实例都被注入:

如果将类上的WindowsCondition.class改为LinuxCondition.class,结果应该可以猜到:

结果就是空的,类中所有bean都没有注入。

多个条件类:

前言中说,@Conditional注解传入的是一个Class数组,存在多种条件类的情况。

这种情况貌似判断难度加深了,测试一波,新增新的条件类,实现的matches返回false(这种写死返回false的方法纯属测试用,没有实际意义O(∩_∩)O)


  1. public class ObstinateCondition implements Condition {
  2. @Override
  3. public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
  4. return false;
  5. }
  6. }

BeanConfig修改一下:


  1. @Conditional({WindowsCondition.class,ObstinateCondition.class})
  2. @Configuration
  3. public class BeanConfig {
  4. @Bean(name = "bill")
  5. public Person person1(){
  6. return new Person("Bill Gates",62);
  7. }
  8. @Bean("linus")
  9. public Person person2(){
  10. return new Person("Linus",48);
  11. }
  12. }

结果:

现在如果将ObstinateCondition的matches方法返回值改成true,两个bean就被注入进容器:

结论得:

第一个条件类实现的方法返回true,第二个返回false,则结果false,不注入进容器。

第一个条件类实现的方法返回true,第二个返回true,则结果true,注入进容器中。

原文地址:https://blog.csdn.net/xcy1193068639/article/details/81491071

Spring @Conditional注解 详细讲解及示例的更多相关文章

  1. Spring Conditional注解使用小结

    今天我们来总结下Conditional注解的使用. Conditional注解 增加配置类Config package condition; import org.springframework.co ...

  2. Spring @Conditional注解的使用

    Spring Boot的强大之处在于使用了Spring 4框架的新特性:@Conditional注释,此注释使得只有在特定条件满足时才启用一些配置. 下面来介绍如何使用Condition 首先写一个类 ...

  3. Spring和SpringMvc详细讲解

    转载自:https://www.cnblogs.com/doudouxiaoye/p/5693399.html 1. 为什么使用Spring ? 1). 方便解耦,简化开发 通过Spring提供的Io ...

  4. Spring常用注解(讲解的通俗易懂,很透彻)

    使用注解来构造IoC容器 用注解来向Spring容器注册Bean.需要在applicationContext.xml中注册<context:component-scan base-package ...

  5. RabbitMQ与java、Spring结合实例详细讲解(转)

    林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文介绍了rabbitMq,提供了如何在Ubuntu下安装RabbitMQ 服务的方法. ...

  6. RabbitMQ与java、Spring结合实例详细讲解

    林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文介绍了rabbitMq,提供了如何在Ubuntu下安装RabbitMQ 服务的方法. ...

  7. Javascript正则表达式详细讲解和示例,通俗易懂

    正则表达式可以: •测试字符串的某个模式.例如,可以对一个输入字符串进行测试,看在该字符串是否存在一个电话号码模式或一个信用卡号码模式.这称为数据有效性验证 •替换文本.可以在文档中使用一个正则表达式 ...

  8. 一文了解@Conditional注解说明和使用

    ​ @Conditional:Spring4.0 介绍了一个新的注解@Conditional,它的逻辑语义可以作为"If-then-else-"来对bean的注册起作用. @Con ...

  9. Spring @Conditional简单使用 以及 使用时注意事项一点

    @Conditional注解在类的方法中 @Conditional注解失效的一种原因 @Conditional注解在类上 手写的低配版@ConditionalOnClass Spring  @Cond ...

随机推荐

  1. 牛客网NOIP赛前集训营 提高组(第七场)

    中国式家长 2 链接:https://www.nowcoder.com/acm/contest/179/A来源:牛客网 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 262144K, ...

  2. [Swift通天遁地]一、超级工具-(15)使用SCLAlertView制作强大的Alert警告窗口和Input编辑窗口

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...

  3. robotframework - Edit编辑器

    1.测试项目&套件 提供的Edit编辑器 2.在 Edit 标签页中主要分:加载外部文件.定义内部变量.定义元数据等三个部分. (1):加载外部文件Add Library:加载测试库,主要是[ ...

  4. 【题解】TES-Intelligence Test

    [题解]\(TES-Intelligence\) \(Test\) 逼自己每天一道模拟题 传送:\(TES-Intelligence\) \(Test\) \([POI2010]\) \([P3500 ...

  5. phpAnalysis调试接口

    phpAnalysis是一款轻量级非侵入式PHP应用性能分析器,适用于开发.测试及生产环境部署使用,方便开发及测试工程师诊断性能问题: 通过tideways收集PHP程序单步运行过程中所有的函数调用时 ...

  6. java 配置信息类 Properties 的简单使用

    Properties :(配置信息类) 是一个表示持久性的集合 ,继承 Hashtable ,存值是以键-值得方式  主要用于生产配置文件和读取配置文件信息. 简单的实例: import java.i ...

  7. ios基础笔试题-集锦二

    前言 下文转载自:http://www.henishuo.com/objc-interview-two/ 1.即时聊天App不会采用的网络传输方式 A. UDP B. TCP C. HTTP D. F ...

  8. Android Error:Unable to find method 'com.android.build.gradle.api.BaseVariant.getOutputs()Ljava/util/List;'.

    问题:Error:Unable to find method 'com.android.build.gradle.api.BaseVariant.getOutputs()Ljava/util/List ...

  9. angular 琐碎

    1.controller 只要在一个地方引用就可以了,路由的时候不用指定controller了,在HTML中指定就可以了,否则会初始化两次 2.angular 模块间的服务无层级关系,相互可见.本质是 ...

  10. Xcode 6 Beta 高速官方下载地址

    推荐迅雷下载: http://adcdownload.apple.com//wwdc_2014/xcode_6_beta_ie8g3n/xcode_6_beta.dmg