一、@Conditional是什么?
-
@Conditional是Spring4新提供的注解,它的作用是按照一定的条件进行判断,满足条件给容器注册bean。
-
该注解为条件装配注解,大量运用于SpringBoot底层,有如下这些类是衍生出来的。
二、相关衍生类
// @ConditionalOnClass 检查类在加载器中是否存在对应的类,如果有则被注解修饰的类就有资格被 Spring 容器所注册,否则会被跳过。
//@ConditionalOnBean 仅仅在当前上下文中存在某个对象时,才会实例化一个 Bean
//@ConditionalOnClass 某个 CLASS 位于类路径上,才会实例化一个 Bean
//@ConditionalOnExpression 当表达式为 true 的时候,才会实例化一个 Bean
//@ConditionalOnMissingBean 仅仅在当前上下文中不存在某个对象时,才会实例化一个 Bean
//@ConditionalOnMissingClass 某个 CLASS 类路径上不存在的时候,才会实例化一个 Bean
三、 源码示例
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
/**
* All {@link Condition} classes that must {@linkplain Condition#matches match}
* in order for the component to be registered.
*/
Class<? extends Condition>[] value();
}
@FunctionalInterface
public interface Condition {
/**
* Determine if the condition matches.
* @param context the condition context
* @param metadata the metadata of the {@link org.springframework.core.type.AnnotationMetadata class}
* or {@link org.springframework.core.type.MethodMetadata method} being checked
* @return {@code true} if the condition matches and the component can be registered,
* or {@code false} to veto the annotated component's registration
*/
boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
}
四、使用
@Configuration
@ConditionalOnClass(WhiteListProperties.class)
@EnableConfigurationProperties(WhiteListProperties.class)
public class WhiteListAutoConfigure {
@Bean("whiteListConfig")
@ConditionalOnMissingBean
public String whiteListConfig(WhiteListProperties pro) {
return pro.getUsers();
}
@Bean
@ConditionalOnMissingBean
public DoJoinPoint point(){
return new DoJoinPoint();
}
}
参考文章:
https://mp.weixin.qq.com/s/jHzLWpogiDgFZqivaYNDIw
https://zhuanlan.zhihu.com/p/141613945
http://www.itsoku.com/article/278