Spring注解之@Conditional

【1】@Conditional介绍

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

​ @Conditional源码:

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

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

public interface Condition {
boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);
}

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

【2】@Conditional示例

​ 首先,创建Person类:

public class Person {

    private String name;
private Integer age; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} public Person(String name, Integer age) {
this.name = name;
this.age = age;
} @Override
public String toString() {
return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
}
}

​ 创建MyConfig类,用于配置两个Person实例并注入,一个是Bill Gates,一个是linus。

@Configuration
public class MyConfig { @Bean(name = "bill")
public Person person1(){
return new Person("Bill Gates",62);
} @Bean("linus")
public Person person2(){
return new Person("Linus",48);
}
}

​ 写一个测试类,测试是否注入成功

public class ConditionalTest {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class); @Test
public void test1(){
Map<String, Person> map = applicationContext.getBeansOfType(Person.class);
System.out.println(map);
}
}
/**测试结果
{bill=Person{name='Bill Gates',age=62},linus=Person{name='Linus',age='48'}}
*/

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

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

​ 首先,创建一个WindowsCondition类:

public class WindowsCondition implements Condition {

    /**
* @param conditionContext:判断条件能使用的上下文环境
* @param annotatedTypeMetadata:注解所在位置的注释信息
* */
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
//获取ioc使用的beanFactory
ConfigurableListableBeanFactory beanFactory = conditionContext.getBeanFactory();
//获取类加载器
ClassLoader classLoader = conditionContext.getClassLoader();
//获取当前环境信息
Environment environment = conditionContext.getEnvironment();
//获取bean定义的注册类
BeanDefinitionRegistry registry = conditionContext.getRegistry(); //获得当前系统名
String property = environment.getProperty("os.name");
//包含Windows则说明是windows系统,返回true
if (property.contains("Windows")){
return true;
}
return false;
}
}

​ 接着,创建LinuxCondition类:

public class LinuxCondition implements Condition {

    @Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { Environment environment = conditionContext.getEnvironment(); String property = environment.getProperty("os.name");
if (property.contains("Linux")){
return true;
}
return false;
}
}

​ 修改MyConfig:

@Configuration
public class MyConfig { //只有一个类时,大括号可以省略
//如果WindowsCondition的实现方法返回true,则注入这个bean
@Conditional({WindowsCondition.class})
@Bean(name = "bill")
public Person person1(){
return new Person("Bill Gates",62);
} //如果LinuxCondition的实现方法返回true,则注入这个bean
@Conditional({LinuxCondition.class})
@Bean("linus")
public Person person2(){
return new Person("Linus",48);
}
}

标注在方法上:

​ 修改测试程序,开始测试:

public class ConditionalTest {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class); @Test
public void test1(){
String osName = applicationContext.getEnvironment().getProperty("os.name");
System.out.println("当前系统为:" + osName);
Map<String, Person> map = applicationContext.getBeansOfType(Person.class);
System.out.println(map);
}
}
/**测试结果
当前系统为:Windows 10
{bill=Person{name='Bill Gates',age=62}}
*/

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

标注在类上:

@Configuration
@Conditional({WindowsCondition.class})
public class MyConfig { //只有一个类时,大括号可以省略
//如果WindowsCondition的实现方法返回true,则注入这个bean
@Bean(name = "bill")
public Person person1(){
return new Person("Bill Gates",62);
} //如果LinuxCondition的实现方法返回true,则注入这个bean
@Bean("linus")
public Person person2(){
return new Person("Linus",48);
}
}

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

二、Spring注解之@Conditional的更多相关文章

  1. Spring 注解驱动(二)Servlet 3.0 注解驱动在 Spring MVC 中的应用

    Spring 注解驱动(二)Servlet 3.0 注解驱动在 Spring MVC 中的应用 Spring 系列目录(https://www.cnblogs.com/binarylei/p/1019 ...

  2. Spring 注解(二)注解工具类 AnnotationUtils 和 AnnotatedElementUtils

    Spring 注解(二)注解工具类 AnnotationUtils 和 AnnotatedElementUtils Spring 系列目录(https://www.cnblogs.com/binary ...

  3. Spring Boot 二十个注解

    Spring Boot 二十个注解 占据无力拥有的东西是一种悲哀. Cold on the outside passionate on the insede. 背景:Spring Boot 注解的强大 ...

  4. 【Spring注解驱动开发】二狗子让我给他讲讲@EnableAspectJAutoProxy注解

    写在前面 最近,二狗子入职了新公司,新入职的那几天确实有点飘.不过慢慢的,他发现他身边的人各个身怀绝技啊,有Spring源码的贡献者,有Dubbo源码的贡献者,有MyBatis源码的贡献者,还有研究A ...

  5. Spring 注解(二)注解工具类

    本文转载自Spring 注解(二)注解工具类 导语 首先回顾一下 AnnotationUtils 和 AnnotatedElementUtils 这两个注解工具类的用法: @Test @GetMapp ...

  6. Spring 注解驱动(一)基本使用规则

    Spring 注解驱动(一)基本使用规则 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) 一.基本使用 @Configur ...

  7. spring注解扫描组件注册

    最近对单点系统进行微服务拆分,被各个springboot的组件注册搞得云里雾里的.(有的是通过springboot的自动配置进IOC容器的,有的是自己添加构造方法添加进IOC容器.)决定抽时间将spr ...

  8. Spring注解(生命周期)

    对于上面的知识图解,需要一点一点的研究. 首先核心容器: 控制反转 和 依赖注入 创建工程: maven仓库搜索 spring context  : 引入后 <!-- https://mvnre ...

  9. 006-Spring Boot自动配置-Condition、Conditional、Spring提供的Conditional自动配置

    一.接口Condition.Conditional(原理) 主要提供一下方法 boolean matches(ConditionContext context, AnnotatedTypeMetada ...

随机推荐

  1. 明解C语言 入门篇 第八章答案

    练习8-1 #include<stdio.h> #define diff(x,y)(x-y) int main() { int x; int y; printf("x=" ...

  2. bootstrap 输入框后面有个按钮

    效果如下:  实现代码:

  3. .NET 使用OLEDB导入Excel数据

    /** * *在本章节中主要讲解的是如何使用OLEDB将Excel中的数据导入到数据库中 * */using System; using System.Data; using System.Data. ...

  4. ASP.NET Core基于K8S的微服务电商案例实践--学习笔记

    摘要 一个完整的电商项目微服务的实践过程,从选型.业务设计.架构设计到开发过程管理.以及上线运维的完整过程总结与剖析. 讲师介绍 产品需求介绍 纯线上商城 线上线下一体化 跨行业 跨商业模式 从0开始 ...

  5. Javase之多线程(2)

    多线程(2) 线程的生命周期 新建:创建线程对象 就绪:有执行资格,没有执行权 运行:有资格运行,有执行权 ​ 阻塞:由一些操作让线程处于改状态.没有执行资格,没有执行权,而通过另一些操作激活它,激活 ...

  6. 专访腾讯方亮:WeTest品牌全面升级,“好的产品一定深谙人性”

    工欲善其事,必先利其器.在当下竞争激烈的市场环境中,精品,已经成为所有游戏厂商安身立命之本.但如何提升品质,使产品成为精品,行业内却长期缺乏公开.透明,以及具备实际参考.实操价值的标准. 制定一项标准 ...

  7. 【XML】XML基本结构以及XML-Schema约束

    XML 简介 1998年2月,W3C正式批准了可扩展标记语言的标准定义,可扩展标记语言可以对文档和数据进行结构化处理,从而能够在部门.客户和供应商之间进行交换,实现动态内容生成,企业集成和应用开发.可 ...

  8. 关于MySQL的一些骚操作——提升正确性,抠点性能

    概要 回顾以前写的项目,发现在规范的时候,还是可以做点骚操作的. 假使以后还有新的项目用到了MySQL,那么肯定是要实践一番的. 为了准备,创建测试数据表(建表语句中默认使用utf8mb4以及utf8 ...

  9. [20190517]rman tape compressed.txt

    [20190517]rman tape compressed.txt --//前一段测试rman选择压缩备份时,如果备份单个数据文件小于64M-3*8K时,先建立大小64M文件,最后会回收到自己的备份 ...

  10. ssh-copy-id 实现ssh无密码登录 openssh putty

    ssh-keygen 生成公私钥对 $ssh-keygen ssh-copy-id将本机的公钥复制到远程机器 ssh-copy-id -i .ssh/id_rsa.pub(公钥路径) 用户名字@192 ...