【发布时间】:2016-01-14 19:51:02
【问题描述】:
鉴于此代码:
public interface Service {}
@Component
@Qualifier("NotWanted")
public class NotWantedService implements Service {}
@Component
@Qualifier("Wanted")
public class WantedService implements Service {}
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(NotWantedService.class);
ctx.register(WantedService.class);
ctx.refresh()
我现在该怎么做:
ctx.getBean(Service.class)
以某种方式只能获得带有@Qualifier("Wanted") 的那个而不是带有@Qualifier("NotWanted") 的那个?我特别询问是否可以使用getBean 来实现,而不是注入到一个类中,然后将其用作一种代理。
【问题讨论】:
-
为什么不按名称获取 bean,因为您使用的是名称常量,即
ctx.getBean("Wanted")? -
@aux 假设您有 50 个地方可以使用
ctx.getBean("service1"),现在您想将其更改为ctx.getBean("service2")。那是50个变化。更改限定符仅更改为 2 个 bean 定义(service1和service2)。还有其他情况——比如我想获得多个Service实例,它们是Wanted。它们不能都具有相同的 bean 名称。 -
好的,我明白了。那么如何引入你自己的“注册表”bean,它包含对你的 bean 的引用并用于通过不同的参数进行查找,比如 spring-data-rest 中的
Repositories?还是包装豆? -
@aux 请参阅问题中的最后一句话。我想知道我是否想取消间接性。换句话说,我有一个可行的解决方案,试图看看是否有更好的解决方案(阅读:更少的代码)。
标签: spring