我有以下注释。
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Import(MyBeanInitializer.class)
public @interface MyAnnotation {
String clientType() default "" ;
}
我有一个如下所示的Bean初始化程序组件
@Configuration
public class MyBeanInitializer {
@Bean() // trigger this when annoattion's value == "A"
public CommonBean firstBean() {
return new BeanA;
}
@Bean() // trigger this when annoattion's value == "B"
public CommonBean firstBean() {
return new BeanB;
}
}
我的BeanA和BeanB的Commoin接口
public interface CommonBean {
void doSomething();
}
我的两个实现是
@Component()
public class BeanA implements CommonBean {
@Overrid
public void doSomething (){
// implementation here
}
}
@Component()
public class BeanB implements CommonBean {
@Overrid
public void doSomething (){
// implementation here
}
}
我需要将上面用作另一个Spring Boot项目的库。在该项目中,我用Application.java
注释了@MyAnnotation(clientType="web")
,然后使用构造函数Injection将 BeanA 或 BeanB 注入到该项目中的类。>
通过查看通过注释传递的值来初始化bean的机制是什么?
答案 0 :(得分:2)
请勿为此使用注释值。
注释值在编译时进行了硬编码,无法动态更改。另外,面对@Conditional
时,它看上去和感觉难以置信尴尬,@ConditionalOnProperty
已经存在并且与获得 dynamic 属性的能力有关。
您想要做的是使用@Conditional
的组合,它允许您在给定特定环境变量的情况下定义要执行的操作,或者使用在 Spring中找到的@ConditionalOnMissingBean
注释引导,以简单地提供根据特定属性中存在特定值来连接Bean的功能。
这就是它的外观。假设您具有名为common.basicImpl
和common.advancedImpl
的属性。
@Component
@ConditionalOnProperty(prefix = "common", value = "basicImpl")
public class BeanA implements CommonBean {
@Override
public void doSomething (){
// implementation here
}
}
@Component
@ConditionalOnProperty(prefix = "common", value = "advancedImpl")
public class BeanB implements CommonBean {
@Override
public void doSomething (){
// implementation here
}
}
请注意,仅此一项并不能解决同时存在两个 属性的情况,并且您不能执行多个@ConditionalOnProperty
语句。添加{{3}}以确保您不会意外地同时将它们两个都连接起来,将会对您有所帮助。