@Conditional
官方文檔定義:“Indicates that a component is only eligible for registration when all specified conditions match”,意思是只有滿足一些列條件之后創(chuàng)建一個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來確定是不是要創(chuàng)建Bean實例泡躯,如下是官方的說明蜜另,大概是說boot是啟用@Conditional注解來確定是否要加載該實例
<blockquote>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. </blockquote>
- ConditionalOnBean: 當且僅當指定的bean classes and/or bean names在當前容器中,才創(chuàng)建標記上該注解的類的實例
- ConditionalOnBean: 當且僅當指定的bean classes and/or bean names不存在當前容器中,才創(chuàng)建標記上該注解的類的實例永品,有指定忽略ignored的參數存在,可以忽略Class闸婴、Type等
- ConditionalOnClass:當且僅當ClassPath存在指定的Class時飞醉,才創(chuàng)建標記上該注解的類的實例
- ConditionalOnMissingClass:當且僅當ClassPath不存在指定的Class時,創(chuàng)建標記上該注解的類的實例
- ConditionalOnProperty:當且僅當Application.properties存在指定的配置項時遭商,創(chuàng)建標記上了該注解的類的實例
- ConditionalOnJava:指定JDK的版本
- ConditionalOnExpression:表達式用${..}=false等來表示
- ConditionalOnJndi:JNDI存在該項時創(chuàng)建
- ConditionalOnResource:在classpath下存在指定的resource時創(chuàng)建
- 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環(huán)境下創(chuàng)建