Java 如何使用注释';s值初始化bean

Java 如何使用注释';s值初始化bean,java,spring,spring-annotations,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

我有下面的注解

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


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

不要为此使用注释值

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

您要做的是使用
@Conditional
的组合,它允许您在给定特定环境变量的情况下定义要执行的操作,或者使用Spring Boot中的注释来简单地提供基于特定属性中特定值的连接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
语句。添加以确保不会意外地同时连接到这两个bean将有助于您解决问题。

您可以在希望注入bean的位置共享代码吗?最重要的是,这两种bean的类型不同
BeanA
BeanB
,您是否计划将它们移动到单个界面?不清楚您到底想要做什么注释的值是A/B在哪里?在您的示例中,没有使用
MyAnnotation
注释任何内容。此外,Spring已经有了条件定义的
@Conditional
。@iam.Carrot我已经在末尾添加了这个用例。@DinethSenevirathne因为
BeanA
BeanB
是两种不同的
数据类型
你能分享一下你到底想做什么吗?您已经分享了
如何
,但我们想知道
为什么
。你想要达到的目标是什么?请举例说明条件是什么,当条件为
true
时会发生什么,如果条件为
false
时会发生什么。您将如何使用这两种不同的
数据类型
?是否有一个您声明没有提到的通用
接口
?您好。谢谢你的建议。但在我的例子中,basicImpl和advancedImpl的内部逻辑是不同的。即使两者都有相同的输入参数,每个实现也使用不同的值。你能提到使用注释值初始化bean的方法吗?我不理解@DinethSenevirathne这个问题。只要这两个bean都实现了
CommonBean
,并且利用了
CommonBean
的公共接口,那么实现细节是什么就无关紧要了。听起来这个问题也有点相切……嗨,我试着用上面的实现作为另一个项目(主项目)的库。这意味着我进行上述实现(我采用了您的方法-ConditionalOnProperty,而上述实现没有Application.java),然后构建jar文件,然后导入到主项目中,添加属性并注入BeanA或BeanB。但是当我尝试在主项目中注入时,它说“找不到BeanA的bean”。@DinethSenevirathne:启动调试日志并调查那里发生了什么。很有可能将其用作库的代码没有属性集,因此无法确定要连接的bean。已解决!谢谢我使用提供的答案使它工作。