前言
@Conditional是Spring4新提供的注解,它的作用是按照一定的条件进行判断,满足条件给容器注册bean。
接口
Conditional.java
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
Class<? extends Condition>[] value();
}
Condition.java
public interface Condition {
boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata);
}
将@Conditional加到创建Bean的类或方法上,指定Conditoin类的具体实现类,
就可以由具体的判断逻辑进行是否要创建Bean了。
默认实现
在org.springframework.boot:spring-boot-autoconfigure:[version] jar文件中的org.springframework.boot.autoconfigure.condition
包中有如下常用的实现:
Condtion类 | Conditional注解 | 说明 |
---|---|---|
OnBeanCondition | @ConditionalOnBean | Matches when beans meeting all the specified equirements are already contained in the BeanFactory |
OnBeanCondition | @ConditionalOnSingleCandidate | Matches when a bean of the specified class is already contained in the BeanFactory and a single candidate can be determined |
OnBeanCondition | @ConditionalOnMissingBean | Matches when no beans meeting the specified requirements are already contained in the BeanFactory |
OnClassCondition | @ConditionalOnClass | Matches when the specified classes are on the classpath |
OnClassCondition | @ConditionalOnMissingClass | Matches when the specified classes are not on the classpath |
OnCloudPlatformCondition | @ConditionalOnCloudPlatform | Matches when the specified cloud platform is active |
OnExpressionCondition | @ConditionalOnExpression | Configuration annotation for a conditional element that depends on the value of a SpEL expression |
OnJavaCondition | @OnJavaCondition | Matches based on the JVM version the application is running on |
OnJndiCondition | @ConditionalOnJndi | Matches based on the availability of a JNDI InitialContext and the ability to lookup specific locations |
OnPropertyCondition | @ConditionalOnProperty | Checks if the specified properties have a specific value |
OnResourceCondition | @ConditionalOnResource | Matches when the specified resources are on the classpath |
OnWebApplicationCondition | @ConditionalOnWebApplication | Matches when the application is a web application |
OnWebApplicationCondition | @ConditionalOnNotWebApplication | Matches when the application is not a web application |