版权声明:本文为博主原创文章,未经博主允许不得转载。					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. 清北考前刷题day1下午好

    水题(water) Time Limit:1000ms   Memory Limit:128MB 题目描述 LYK出了道水题. 这个水题是这样的:有两副牌,每副牌都有n张. 对于第一副牌的每张牌长和宽 ...

  2. nginx+thinkPhp配置虚拟主机和伪静态规则重写

    /usr/local/nginx/conf/nginx.conf 进行配置 server    {        listen 80 default_server;        #listen [: ...

  3. [C和指针] 6-指针

    6.1 内存和地址 我们可以把计算机的内存看作是一条长街上的一排房屋,每座房子都可以容纳数据,并通过一个房号来标识. 这个比喻颇为有用,但也存在局限性.计算机的内存由以亿万计的位(bit)组成,每个位 ...

  4. G - And Then There Was One (约瑟夫环变形)

    Description Let’s play a stone removing game. Initially, n stones are arranged on a circle and numbe ...

  5. 为WebSphere Application Server v8.5安装并配置JDK7

    IBM WebSphere Application Server v8.5可以同时支持不同版本的JDK共存,并且可以通过命令设置概要文件所使用的JDK版本.WAS8.5默认安装JDK6,如果要使用JD ...

  6. python之路 之一pyspark

    pip包下载安装pyspark pip install pyspark  这里可能会遇到安装超时的情况   加参数  --timeout=100 pip   -default   -timeout=1 ...

  7. MySql数据查询中 left join 条件位置区别

    /*A 和 B 两张表都只有一个 ID 字段 比如A表的数据为 ID 1,2,3,4,5,6 B表的数据为 ID 1,2,3 判断 JOIN 查询时候条件在 ON 和 WHERE 时的区别 ON 和 ...

  8. poj1787 Charlie's Change

    思路: 完全背包,记录路径. 实现: #include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; ] ...

  9. python __slots__ 详解(上篇)

    转自:http://blog.csdn.net/sxingming/article/details/52892640 python中的new-style class要求继承Python中的一个内建类型 ...

  10. webSql的简单小例子

    初始化websql数据库的参数信息 var config = { name: 'my_plan', version: '', desc: 'manage my plans', size: 20 * 1 ...