admin管理员组文章数量:1599529
浅谈 @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")
版权声明:本文标题:浅谈 @Condition注解以及配置开关是否注册bean 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1728324542a1154264.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论