本文主要是介绍Spring-boot中Conditional介绍,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原文地址:http://www.jianshu.com/p/0740c07f6c1d
@Conditional
官方文档定义:“Indicates that a component is only eligible for registration when all specified conditions match”,意思是只有满足一些列条件之后创建一个bean。 @Conditional定义
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface Conditional {Class<? extends Condition>[] value(); }@Conditional注解主要用在以下位置:
- 类级别可以放在注标识有@Component(包含@Configuration)的类上
- 作为一个meta-annotation,组成自定义注解
- 方法级别可以放在标识由@Bean的方法上
spring-boot的@Conditional系列
spring-boot利用Conditional来确定是不是要创建Bean实例,如下是官方的说明,大概是说boot是启用@Conditional注解来确定是否要加载该实例
No. Boot is enabled in Spring Framework 4.0 by the @Conditional annotation infrastructure. Your perception of loaded is accurate otherwise - JRebel is much more comprehensive, works with multiple IDEs, etc.
- ConditionalOnBean: 当且仅当指定的bean classes and/or bean names在当前容器中,才创建标记上该注解的类的实例
- ConditionalOnMissingBean: 当且仅当指定的bean classes and/or bean names不存在当前容器中,才创建标记上该注解的类的实例,有指定忽略ignored的参数存在,可以忽略Class、Type等
- ConditionalOnClass:当且仅当ClassPath存在指定的Class时,才创建标记上该注解的类的实例
- ConditionalOnMissingClass:当且仅当ClassPath不存在指定的Class时,创建标记上该注解的类的实例
- ConditionalOnProperty:当且仅当Application.properties存在指定的配置项时,创建标记上了该注解的类的实例
- ConditionalOnJava:指定JDK的版本
- ConditionalOnExpression:表达式用${..}=false等来表示
- ConditionalOnJndi:JNDI存在该项时创建
- ConditionalOnResource:在classpath下存在指定的resource时创建
- ConditionalOnSingleCandidate:Conditional that only matches when the specified bean class is already contained in the BeanFactory and a single candidate can be determined.The condition will also match if multiple matching bean instances are already contained in the BeanFactory but a primary candidate has been defined; essentially, the condition match if auto-wiring a bean with the defined type will succeed.
- ConditionalOnWebApplication:在web环境下创建
这篇关于Spring-boot中Conditional介绍的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!