繁体   English   中英

如何使用注解的值来初始化 bean

[英]How use an annotation's value to initialize a bean

我有以下注释。

@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 的我的 Common 接口

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 引导项目的库。 在该项目中,我使用@MyAnnotation(clientType="web")注释Application.java ,然后使用构造函数注入将BeanABeanB注入该项目内的 class。

通过查看通过注释传递的值来初始化 bean 的机制是什么?

不要为此使用注释值。

注释值在编译时是硬编码的,不能动态更改。 另外,面对@Conditional ,它看起来和感觉都非常尴尬,它已经存在并与获取动态属性的能力相关联。

您想要做的是使用@Conditional的组合,它允许您在给定特定环境变量的情况下定义要执行的操作,或者使用Spring Boot中的@ConditionalOnProperty注释来简单地提供基于 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语句。 添加@ConditionalOnMissingBean以确保您不会意外地将它们同时连接起来会对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM