gpt4 book ai didi

java - 如何为 @Autowire 字段提供不同的 bean,条件是拥有对象(也是 @Autowired)上的注释?

转载 作者:行者123 更新时间:2023-12-02 11:47:53 25 4
gpt4 key购买 nike

我有一个配置类,它提供同一基本 bean 接口(interface)的两个实现。我希望根据所属类 Autowiring 的注释有条件地使用它们。

“拥有”类的用法:

public class MyController
{
@Autowired
private OwnerInterface baseOwner;

@Autowired
@MyAnnotation
private OwnerInterface specialOwner;
}

拥有类:

public class OwningClass implements OwnerInterface
{
//This is the one I want to supply a conditional bean for
@Autowired
private MyBeanInterface someBean;
}

这是配置类的伪代码:

@Configuration
public class ConfigClass
{
@Bean
//Should I use a different conditional?
//And if I make a static method to use here, how would I pass the owning class to it?
@ConditionalOnExpression(...elided...)
public MyBeanInterface getNormalBeanInterface()
{
return new MyBeanInterfaceImpl();
}

@Bean
@ConditionalOnExpression(...elided.../* MyAnnotation */)
public MyBeanInterface getSpecialBeanInterface()
{
return new MyBeanInterfaceForMyAnnotation();
}
}

对于条件,有没有办法将拥有的对象传递给它?我会使用静态方法,例如:

@ConditionalOnExpression(
"#{T(MyAnnotationVerifier).isAnnotatedBy(ownignObject))}"
)

有更好的解决方案吗?

我不想使用 AOP,因为这是在使用应用程序期间会增加每次调用的开销。如果我可以提供 bean,那么它将在启动时创建对象时发生。

我可以使用不同的 @Conditional 注释来执行此操作吗?

最佳答案

如果必须静态做出决定(例如您的@MyAnnotation),您也可以使用@Primary

@Bean
@Primary
public MyBeanInterface getNormalBeanInterface()
{
return new MyBeanInterfaceImpl();
}

@Bean
public MyBeanInterface getSpecialBeanInterface()
{
return new MyBeanInterfaceForMyAnnotation();
}

这样,您可以按类型自动连接,并且它将始终引用带有 @Primary 的 bean

<小时/>

替代方案:按名称使用自动连线

public class ConfigClass {
@Bean
public MyBeanInterface normalBean(){
return new MyBeanInterfaceImpl();
}

@Bean
public MyBeanInterface specialBean(){
return new MyBeanInterfaceForMyAnnotation();
}
}

public class MyController {
@Autowired
private OwnerInterface normalBean;

@Autowired
private OwnerInterface specialBean;
}

这里要注意:MyController 中的变量名称 (specialBean/normalBean) 与 中的 @Bean 方法完全匹配配置类

希望这对您有帮助。

关于java - 如何为 @Autowire 字段提供不同的 bean,条件是拥有对象(也是 @Autowired)上的注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48070531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com