@Conditional的简单使用

先看下源码。首先继承了Condition接口。

 Condition接口源码

@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);

}

注释最后两行百度翻译下,作用说的很清楚了。

 matches方法返回true,就注入bean,否则,不注入。

简单的使用场景。

如果有个需要注入的组件,只在local环境执行,不在local-2执行。

1.先写一个是否注入的逻辑处理类

public class CheckEnvironmentCondition implements Condition {
    /**
     * Determine if the condition matches.
     *
     * @param context  the condition context
     * @param metadata the metadata of the {@link AnnotationMetadata class}
     *                 or {@link 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
     */
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment environment = context.getEnvironment();
        System.out.println("environment:"+environment);
        String active = environment.getProperty("spring.profiles.active");
        System.out.println("a:"+active);
        if("local".equals(active)){
            return true;
        }else {
            return false;
        }
    }
}

在组件上加入注解@Conditional(CheckEnvironmentCondition.class)

@Configuration
@Slf4j
@EnableScheduling
@Conditional(CheckEnvironmentCondition.class)
public class ConditionalConfigTest {

    @Scheduled(cron = "*/5 * * * * ?")
    private void updateJob(){
        System.out.println("ConditionalConfigTest:"+ LocalDateTime.now());
    }
}

local环境,成功执行

 local-2环境,就不执行了,注入失败。

 


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值