浅谈 @Condition注解以及配置开关是否注册bean

6 篇文章 0 订阅

浅谈 @Condition注解以及配置开关是否注册bean

@Condition 中文翻译为条件,看到源码中注释了解到它是从4.0开始加的特性。

A condition is any state that can be determined programmatically before the bean definition is due to be registered (see {@link Condition} for details).

在注册bean定义之前是可以通过程序来控制状态的,详情Condition接口。

打开Condition注解

Conditions are checked immediately before the bean-definition is due to be registered and are free to veto registration based on any criteria that can be determined at that point.

在注册bean定义之前会检查条件,并且可以根据这个条件是否注册这个bean。

这个接口只有matches方法,看方法描述:确定是否匹配条件,spring当中比较熟悉的@Profile注解也是根据利用Condition接口实现了ProfileCondition类,进行根据启动环境加载bean对象。当然根据不同环境是否注册这个bean对象,在一大程度上满足了我们的业务,但是比如我们写了个公共项目,里面包含很多工具类,比如发送邮件、短信服务等等。其他服务在引用的时候可能近期用不到这些服务,我们需要一个配置开关更能灵活的控制bean的注册。

@ConditionalOnClass等一系类的注解可以帮助我们是否注册bean;有些特殊情况没有依赖特定的第三方类。注册也变得不灵活。
我们可以自己定义Condition条件注解,实现Condition接口,实现条件加载的具体逻辑。
首先自定义注解@RegisterBean

/**
 * @author liweigao
 * @date 2019/3/28 下午2:37
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Conditional(RegisterCondition.class) 
public @interface RegisterBean {

    /**
     * Environment key   Resolve ${...} placeholders in the given text
     * value true or false
     */
    String value();
}
 

RegisterCondition实现类

/**
 * @author liweigao
 * @date 2019/3/28 下午2:39
 */
public class RegisterCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(
                metadata.getAnnotationAttributes(RegisterBean.class.getName()));
        /**
         *  {@link org.springframework.core.env.PropertyResolver#resolvePlaceholders(String)}
         *  {@link org.springframework.core.env.AbstractPropertyResolver#resolvePlaceholders(String)}
         * */
        return Boolean.valueOf(context.getEnvironment().resolvePlaceholders(attributes.getString("value")));
    }
}

在我们公共类中使用RegisterBean注解 @RegisterBean("${common.email.service.enabled:false}")
默认是关闭的,如果需要开启的话在配置中配置相关的email 配置和common.mail.service.enabled= true 完成mail bean注册。

这样的写法极大的方便了封装公共包中的组件配置,避免其他项目引用增添不必要的配置,欢迎吐槽。
2019年09月18日更新
spring autoConfigure 包中已封装好你想要的注解@ConditionalOnProperty
示例

@ConditionalOnProperty(prefix = "common.email.service", name = "enabled", havingValue = "true")
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值