二、Spring注解之@Conditional
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的更多相关文章
- Spring 注解驱动(二)Servlet 3.0 注解驱动在 Spring MVC 中的应用
Spring 注解驱动(二)Servlet 3.0 注解驱动在 Spring MVC 中的应用 Spring 系列目录(https://www.cnblogs.com/binarylei/p/1019 ...
- Spring 注解(二)注解工具类 AnnotationUtils 和 AnnotatedElementUtils
Spring 注解(二)注解工具类 AnnotationUtils 和 AnnotatedElementUtils Spring 系列目录(https://www.cnblogs.com/binary ...
- Spring Boot 二十个注解
Spring Boot 二十个注解 占据无力拥有的东西是一种悲哀. Cold on the outside passionate on the insede. 背景:Spring Boot 注解的强大 ...
- 【Spring注解驱动开发】二狗子让我给他讲讲@EnableAspectJAutoProxy注解
写在前面 最近,二狗子入职了新公司,新入职的那几天确实有点飘.不过慢慢的,他发现他身边的人各个身怀绝技啊,有Spring源码的贡献者,有Dubbo源码的贡献者,有MyBatis源码的贡献者,还有研究A ...
- Spring 注解(二)注解工具类
本文转载自Spring 注解(二)注解工具类 导语 首先回顾一下 AnnotationUtils 和 AnnotatedElementUtils 这两个注解工具类的用法: @Test @GetMapp ...
- Spring 注解驱动(一)基本使用规则
Spring 注解驱动(一)基本使用规则 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) 一.基本使用 @Configur ...
- spring注解扫描组件注册
最近对单点系统进行微服务拆分,被各个springboot的组件注册搞得云里雾里的.(有的是通过springboot的自动配置进IOC容器的,有的是自己添加构造方法添加进IOC容器.)决定抽时间将spr ...
- Spring注解(生命周期)
对于上面的知识图解,需要一点一点的研究. 首先核心容器: 控制反转 和 依赖注入 创建工程: maven仓库搜索 spring context : 引入后 <!-- https://mvnre ...
- 006-Spring Boot自动配置-Condition、Conditional、Spring提供的Conditional自动配置
一.接口Condition.Conditional(原理) 主要提供一下方法 boolean matches(ConditionContext context, AnnotatedTypeMetada ...
随机推荐
- 资源推荐:PPT快闪资源合集附配套字体下载
样例ppt下载 搜索公众号“拒收”或扫码关注公众号 回复关键字“快闪ppt”获取全部福利 本公众号只出精品,拒收劣质 或者点击菜单链接获取获取全部资源
- 配置sshd的免密码登录
在客户端上生成密钥: ssh-keygen -t rsa 然后上传到服务器上即可: ssh-copy-id username@remote-server -p22
- 红黑树之 原理和算法详细介绍(阿里面试-treemap使用了红黑树) 红黑树的时间复杂度是O(lgn) 高度<=2log(n+1)1、X节点左旋-将X右边的子节点变成 父节点 2、X节点右旋-将X左边的子节点变成父节点
红黑树插入删除 具体参考:红黑树原理以及插入.删除算法 附图例说明 (阿里的高德一直追着问) 或者插入的情况参考:红黑树原理以及插入.删除算法 附图例说明 红黑树与AVL树 红黑树 的时间复杂度 ...
- KiRaiseException函数逆向
KiRaiseException函数是记录异常的最后一步,在这之后紧接着就调用KiDispatchException分发异常. 我们在逆向前,先看一下书中的介绍: 1. 概念认知: KiRaiseEx ...
- Java日期时间API系列5-----Jdk7及以前的日期时间类TimeUnit在并发编程中的应用
TimeUnit是一个时间单位枚举类,主要用于并发编程,时间单元表示给定粒度单元的时间持续时间,并提供实用程序方法来跨单元转换,以及在这些单元中执行计时和延迟操作. 1.时间单位换算 (1)支持的单位 ...
- Typescript基础(2)——函数
前言 今天继续typescript的学习,开始函数的学习. 函数 函数的定义 和JavaScript一样,TypeScript函数可以创建有名字的函数和匿名函数. 你可以随意选择适合应用程序的方式,不 ...
- Wireshark分析实战:某达速递登录帐号密码提取
- 准备工作 首先,备好Wireshark,打开,在外网网卡上抓包. 其次,用浏览器访问http://www.yundaex.com/cn/index.php,并在手机上下载安装其APP,找到登录页面 ...
- Git:SSH、SSH与HTTP区别、git常用命令
SSH1.首先需要检查你电脑是否已经有 SSH key cd ~/.sshls12.ssh表示ssh文件是个隐藏文件查看是否存在 id_rsa.pub 或 id_dsa.pub 文件,如果文件已经存在 ...
- mac上安装npm
检查brew -v是否安装了homebrew这个macOS 缺失的软件包的管理器.如果安装,跳转到第3步,否则跳转到第二步: 安装homebrew.安装跳转到官网指导.等待安装好之后,输入brew - ...
- python字符减运算
在C语言等高级语言中,字符之间的减运算都是支持的,但是python不然,在python中直接进行字符减运算是不被允许的. >>> print('c'-'a') Traceback ( ...