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容器相关的注解,先后有:@ ...
随机推荐
- Tomcat PermGen space的解决方案
Tomcat报告 Caused by: java.lang.OutOfMemoryError: PermGen space异常 内存溢出PermGen space的全称是Permanent Gener ...
- linux下svn(subversion)服务端添加工程及配置权限
linux下svn(subversion)服务端添加工程及配置权限 转载请注明源地址:http://www.cnblogs.com/funnyzpc/p/9010507.html 此篇我只是将所做过的 ...
- 2、原生js实现轮播图特效
很多很多网站经常会用到一个特效,那就是轮播图,对于日新月异的前端技术来说其实就是一个框架一个接口的事,但轮播的原理是什么?用最原始的javascript来写又是怎样的呢?本人是一枚菜鸟,这篇文章就当做 ...
- vue国际化高逼格多语言
## 1.NPM 项目安装 ``` cnpm i vue-i18n ``` ## 2.使用方法 ``` /* 国际化使用规则 */ import Vue from 'vue' import VueI1 ...
- Spring 的IOC和AOP总结
Spring 的IOC和AOP IOC 1.IOC 许多应用都是通过彼此间的相互合作来实现业务逻辑的,如类A要调用类B的方法,以前我们都是在类A中,通过自身new一个类B,然后在调用类B的方法,现在我 ...
- java 字符常量池
一.题目: 问题:String str = new String(“hello”),“hello”在内存中是怎么分配的? 答案是:堆,字符串常量区. Java中的字符串常量池和JVM运行时数据区 ...
- php-msf 源码解读【转】
php-msf: https://github.com/pinguo/php-msf 百度脑图 - php-msf 源码解读: http://naotu.baidu.com/file/cc7b5a49 ...
- Eclipse中导入项目后js报错解决方法
http://blog.csdn.net/chenchunlin526/article/details/54666882 原因是因为开启了js的校验功能 不影响项目 如需去除错误标志按链接文档操作即可 ...
- 2. Java面向对象之泛型-构造方法中使用
package generic; class Construtgeneric<T> { private T value; public Construtgeneric(T value) { ...
- 两种方法轻松搞定-- Eclipse 安装FindBugs插件
1安装:首先到官方网站下载最新版本FindBugs http://findbugs.sourceforge.net/downloads.html 将 edu.umd.c ...