版权声明:本文为博主原创文章,未经博主允许不得转载。					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. robotframework - User key 操作

    一.用户关键字操作思路 a.创建model1资源 b.在model下创建用户关键字 - 循环 c.测试套件下创建test_case/case2 & 用户关键字 d.测试套件中导入Resourc ...

  2. springboot(一) 热部署

    代码地址:https://github.com/showkawa/springBoot_2017/tree/master/spb-demo 1.热部署的定义 所谓的热部署:比如项目的热部署,就是在应用 ...

  3. httpd 安装ssl证书

    1) 安装ssl模块 # yum install mod_ssl -y Ps:安装完成后,会在/etc/httpd/conf.d/下生成一个ssl.conf配置文件. 2) 先建一个目录用来放ssl证 ...

  4. php 编译时 报错 configure: error: libXpm.(a|so) not found.

    编译环境 centos7 php 5.4.26 $ yum install libXpm-devel 显示已安装 百度得知 ubuntu虚拟机安装lamp遇到的问题 configure: error: ...

  5. 推荐一波 瀑布流的RecylceView

    推荐博客:http://www.bubuko.com/infodetail-999014.html

  6. [W3School]JavaScript教程学习

    JavaScript 简介 JavaScript 是世界上最流行的编程语言.这门语言可用于 HTML 和 web,更可广泛用于服务器.PC.笔记本电脑.平板电脑和智能手机等设备. JavaScript ...

  7. Rabin_Karp(hash) HDOJ 1711 Number Sequence

    题目传送门 /* Rabin_Karp:虽说用KMP更好,但是RK算法好理解.简单说一下RK算法的原理:首先把模式串的哈希值算出来, 在文本串里不断更新模式串的长度的哈希值,若相等,则找到了,否则整个 ...

  8. Linux环境下卸载、安装及配置MySQL5.1

    Linux环境下卸载原有MySQL5.1数据库,并重新安装MySQL数据库的示例记录. 一.卸载MySQL 查看主机中是否安装了MySQL数据库: [root@RD-viPORTAL- ~]# rpm ...

  9. 【C++】Item34.区分接口继承和实现继承

    区分接口继承和实现继承 类包含的成员函数种类 1.静态函数 2.非静态函数 2.1 普通函数(非虚) non-virtual 2.2 虚函数 2.2.1 纯虚函数 pure-virtual 2.2.2 ...

  10. CF822C Hacker, pack your bags!

    思路: 对于一个区间[l, r],只需枚举所有满足r' < l并且二者duration之和为x的区间[l', r'],寻找其中二者cost之和最小的即可.于是可以开一个数组a[],a[i]表示所 ...