Spring中的@conditional注解
今天主要从以下几方面来介绍一下@Conditional注解
@Conditional注解是什么
@Conditional注解怎么使用
1,@Conditional注解是什么
@Conditional注解是可以根据一些自定义的条件动态的选择是否加载该bean到springIOC容器中去,如果看过springBoot源码的同学会发现,springBoot中大量使用了该注解
2,@Conditional注解怎么使用
查看@Conditional源码你会发现它既可以作用在方法上,同时也可以作用在类上,源码如下:
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
/**
* All {@link Condition}s that must {@linkplain Condition#matches match}
* in order for the component to be registered.
*/
Class<? extends Condition>[] value();
}
设置给@conditional的类需要实现Condition接口
我们看一下Condition的源码:
public interface Condition {
boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);
}
ConditionContext源码:
public interface ConditionContext {
BeanDefinitionRegistry getRegistry();
ConfigurableListableBeanFactory getBeanFactory();
Environment getEnvironment();
ResourceLoader getResourceLoader();
ClassLoader getClassLoader();
}
AnnotatedTypeMetadata源码: 此类能够让我们检查带有@Bean注解的方法上还有其他什么注解
public interface AnnotatedTypeMetadata {
boolean isAnnotated(String var1);
Map<String, Object> getAnnotationAttributes(String var1);
Map<String, Object> getAnnotationAttributes(String var1, boolean var2);
MultiValueMap<String, Object> getAllAnnotationAttributes(String var1);
MultiValueMap<String, Object> getAllAnnotationAttributes(String var1, boolean var2);
}
a,@Conditional作用在方法上
定义一个Condition如下:
/**
* 定义一个bean的Condition
*
* @author zhangqh
* @date 2018年5月1日
*/
public class MyCondition implements Condition {
public boolean matches(ConditionContext context,AnnotatedTypeMetadata metadata) {
Environment env = context.getEnvironment();
String system = env.getProperty("os.name");
System.out.println("系统环境为 ==="+system);
// 系统环境在Windows才加载该bean到容器中
if(system.contains("Windows")){
return true;
}
return false;
}
}
定义一个bean加上@Conditional注解如下:
@Conditional({MyCondition.class})
@Bean(value="user1")
public User getUser1(){
System.out.println("创建user1实例");
return new User("李四",26);
}
测试如下:
AnnotationConfigApplicationContext applicationContext2 = new AnnotationConfigApplicationContext(MainConfig.class);
String[] beanNames = applicationContext2.getBeanDefinitionNames();
for(int i=0;i<beanNames.length;i++){
System.out.println("bean名称为==="+beanNames[i]);
}
运行结果:
bean名称为===mainConfig
bean名称为===user0
bean名称为===user1
我这边电脑系统是window所以user1实例是有创建出来的,如果把MyCondition中的判断改成if(system.contains("linux"))那么user1是不会加载到spring容器中的
b,@Conditional作用在类上
修改注解配置如下:
/**
* 定义一个注解配置文件 必须要加上@Configuration注解
*
* @author zhangqh
* @date 2018年4月30日
*/
@Conditional({MyCondition.class})
@Configuration
public class MainConfig {
/**
* 定义一个bean对象
* @return
*/
@Scope
@Lazy
@Bean(value="user0")
public User getUser(){
System.out.println("创建user实例");
return new User("张三",26);
}
//@Conditional({MyCondition.class})
@Bean(value="user1")
public User getUser1(){
System.out.println("创建user1实例");
return new User("李四",26);
}
}
运行测试:
bean名称为===mainConfig
bean名称为===user0
bean名称为===user1
MainConfig中的bean都成功打印出来了,因为我MyCondition条件返回的是true,同样如果我修改成if(system.contains("linux"))那么MainConfig的bean就都不会实例化了
c, @profile注解分析
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({ProfileCondition.class})
public @interface Profile {
String[] value();
}
注意:@Profile本身也使用了@Condition注解,并且引用ProfileCondition作为Condition的实现。
以下为ProfileCondition的实现
class ProfileCondition implements Condition {
ProfileCondition() {
}
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
if (context.getEnvironment() != null) {
MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
if (attrs != null) {
Iterator var4 = ((List)attrs.get("value")).iterator();
Object value;
do {
if (!var4.hasNext()) {
return false;
}
value = var4.next();
} while(!context.getEnvironment().acceptsProfiles((String[])((String[])value)));
return true;
}
}
return true;
}
}
Spring中的@conditional注解的更多相关文章
- 四、Spring中使用@Conditional按照条件注册Bean
以前其实是写过@Condtional注解的笔记的,这里附上链接: Spring中的@conditional注解 但已经忘记的差不多了,所以今天再重新学习下,可以互补着学习 @Contional:按照一 ...
- 第5章—构建Spring Web应用程序—关于spring中的validate注解后台校验的解析
关于spring中的validate注解后台校验的解析 在后台开发过程中,对参数的校验成为开发环境不可缺少的一个环节.比如参数不能为null,email那么必须符合email的格式,如果手动进行if判 ...
- Spring 中aop切面注解实现
spring中aop的注解实现方式简单实例 上篇中我们讲到spring的xml实现,这里我们讲讲使用注解如何实现aop呢.前面已经讲过aop的简单理解了,这里就不在赘述了. 注解方式实现aop我们 ...
- Spring中的常用注解
Spring中的常用注解 1.@Controller 标识一个该类是Spring MVC controller处理器,用来创建处理http请求的对象.
- JavaEE开发之Spring中的条件注解组合注解与元注解
上篇博客我们详细的聊了<JavaEE开发之Spring中的多线程编程以及任务定时器详解>,本篇博客我们就来聊聊条件注解@Conditional以及组合条件.条件注解说简单点就是根据特定的条 ...
- JavaEE开发之Spring中的条件注解、组合注解与元注解
上篇博客我们详细的聊了<JavaEE开发之Spring中的多线程编程以及任务定时器详解>,本篇博客我们就来聊聊条件注解@Conditional以及组合条件.条件注解说简单点就是根据特定的条 ...
- Spring中常用的注解,你知道几个呢?
今天给大家分享下Spring中一般常用的注解都有哪些.可能很多人做了很长是了但有些还是不知道一些注解,不过没有关系,你接着往下看. Spring部分 1.声明bean的注解 @Component 组件 ...
- Spring中的Autowired注解和Resource注解的区别
1.所属jar包不同,Autowired是Spring中的Resource是JSR-250规范定义的注解
- 深入理解spring中的各种注解
Spring中的注解大概可以分为两大类: 1)spring的bean容器相关的注解,或者说bean工厂相关的注解: 2)springmvc相关的注解. spring的bean容器相关的注解,先后有:@ ...
随机推荐
- HTTP协议简单记录
http协议的格式 1. 首行 2. 头 3. 空行 4. 体 http请求头 #Referer 请求来自哪里,如果是在http://www.baidu.com上点击链接发出的请求,那么Referer ...
- Redis未授权访问
最近在做校招题目的时候发现有问到未授权访问,特此搭建了诸多未授权访问的环境并且一一复现并做简单总结.再次记录下来 环境介绍 0x00环境搭建 我这里用到的是Microsoft(R) Windows(R ...
- java线程interrupt、interrupted 、isInterrupted区别
前言 在分析interrupt之前,应该先了解java里线程有5种状态,其中有一个阻塞状态,interrupt和阻塞有关. interrupt() 方法 作用于要中断的那个线程. interrupt( ...
- Spring-cloud (八) Hystrix 请求缓存的使用
前言: 最近忙着微服务项目的开发,脱更了半个月多,今天项目的初版已经完成,所以打算继续我们的微服务学习,由于Hystrix这一块东西好多,只好多拆分几篇文章写,对于一般对性能要求不是很高的项目中,可以 ...
- Spring Cloud @HystrixCommand和@CacheResult注解使用,参数配置
使用Spring Cloud时绕不开Hystrix,他帮助微服务实现断路器功能.该框架的目标在于通过控制那些访问远程系统.服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力.Hystrix具备 ...
- springMVC框架在js中使用window.location.href请求url时IE不兼容问题解决
是使用springMVC框架时,有时候需要在js中使用window.location.href来请求url,比如下面的路径: window.location.href = 'forecast/down ...
- 你不知道的JavaScript--Item5 全局变量
1.尽量少用全局对象 全局变量的问题在于,你的JavaScript应用程序和web页面上的所有代码都共享了这些全局变量,他们住在同一个全局命名空间,所以当程序的两个不同部分定义同名但不同作用的全局变量 ...
- 安装scrapy出错Failed building wheel for Twisted
用64位windows10的CMD命令安装pip install scrapy出错: Running setup.py bdist_wheel for Twisted ... error Failed ...
- TestNG 相对路径与绝对路径getResourceAsStream
以下内容引自: http://blog.csdn.net/zmx729618/article/details/51144588 (注: 此url并非原出处,该文章也是转自他人.但博主未注明出处) Ja ...
- reader-write.go
{ return n, err } r.bucket.Wait(int64(n)) return n, err } type writer struct { ...