如何使用注释的值初始化bean

时间:2020-05-15 17:01:50

标签: java spring spring-annotations

我有以下注释。

@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的机制是什么?

1 个答案:

答案 0 :(得分:2)

请勿为此使用注释值。

注释值在编译时进行了硬编码,无法动态更改。另外,面对@Conditional时,它看上去和感觉难以置信尴尬,@ConditionalOnProperty已经存在并且与获得 dynamic 属性的能力有关。

您想要做的是使用@Conditional的组合,它允许您在给定特定环境变量的情况下定义要执行的操作,或者使用在 Spring中找到的@ConditionalOnMissingBean注释引导,以简单地提供根据特定属性中存在特定值来连接Bean的功能。

这就是它的外观。假设您具有名为common.basicImplcommon.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}}以确保您不会意外地同时将它们两个都连接起来,将会对您有所帮助。

相关问题