SpringBoot之Condition系列

一、@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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值