简体   繁体   中英

Java / Spring: “Tagging” beans in XML to get specific bean by class and tag

I have big XML config made from several files.

I need to get bean implementing specific interface. But there are several implementations so I have to choose. I want to tag bean with special "tag" to get it easily:

<bean class="myInterfaceImpl1" tag="beanForMe" />
<bean class="myInterfaceImpl2" />
<bean class="myInterfaceImpl3" />

T get(Class<T> clazz) {
    return factory.getBean(clazz, "beanForMe"); //Returns first one 
}

Does there is something like that in spring?

I found 2 workaround. First is to use special tag id:

first

<bean class="myInterfaceImpl1" id="MyInterface-beanForMe" />

But when I rename class in My IDE everything would fail unless I write IDE plugin to support my idea.

Second is to add all "tagged" beans to specific list, get it by id and then iterate through it to find appropriate bean.

But tags would be the best here. What do you think?

Spring has a notion of qualifiers for exactly that purpose:

<bean class="myInterfaceImpl1">
    <qualifier value = "beanForMe" />
</bean> 

Unfortunately, they are intended to be used only for autowiring, but you can access them manually, though it would be quite ugly:

ConfigurableListableBeanFactory cbf = ((ConfigurableListableBeanFactory) factory);
BeanDefinition bd = cbf.getBeanDefinition(name);
AutowireCandidateQualifier q = ((AbstractBeanDefinition) bd).getQualifier(Qualifier.class.getName());
String value = (String) q.getAttribute(AutowireCandidateQualifier.VALUE_KEY);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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