通过限定符从ApplicationContext获取bean [英] Get bean from ApplicationContext by qualifier

查看:121
本文介绍了通过限定符从ApplicationContext获取bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

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而不是注入类,然后将该类用作代理.

in a way that will only get the one with @Qualifier("Wanted") and not the one with @Qualifier("NotWanted")? I'm specifically asking if it's possible to do it using getBean, not injecting to a class, then using that one as a kind of proxy.

推荐答案

您可以使用

BeanFactoryAnnotationUtils.qualifiedBeanOfType(ctx.getBeanFactory(), Service.class, "Wanted")

使用ctx.getBeanFactory()而不是ctx本身很重要,因为'qualifiedBeanOfType'方法只能解析ConfigurableListenableBeanFactory的限定词.

It's important to use ctx.getBeanFactory(), not ctx itself, because the 'qualifiedBeanOfType' method can resolve qualifiers only for ConfigurableListenableBeanFactory.

这篇关于通过限定符从ApplicationContext获取bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆