简体   繁体   中英

Spring Configuration xml file with two beans of the same type NoUniqueBeanDefinitionException

I am trying to set up a test applicationContext file for running integration tests on a project that I am working on. I have two classes that have fields that are marked as @Resource. One class I can change and one I cannot as it is imported from a different project that I don't have any permissions to change. I cannot get my configuration file to set these @Resouces fields without giving me an org.springframework.beans.factory.NoUniqueBeanDefinitionException.

Simple example: appconfig.xml file

...Typical spring setup...
<bean id="baseUrl" class="java.lang.String">
<constructor-arg value="myURL"/>
</bean>
<bean id="supportedLang" class = "java.lang.String">
<constructor-arg value="en"/>
</bean>

Class that uses baseURL, (I have control to change, simplified Version)

@Service("myService")
public class MyService implements AnotherService{
@Resource
private String baseUrl;
public String getBaseUrl(){return baseUrl;}
public void setBaseURL(String baseURL){this.baseUrl = baseUrl;}

}

Class that uses supportedLang (I don't have access to change this class simplified version)

@Service
public class LangSupportImpl implements InitializaingBean, LangSupport{
@Resource(name= "supportedLang")
private String twoLetterSupportedLang;
public getTwoLetterSupportedLang(){return this.twoLetterSupportedLang;}
}

If I don't set up the beans in the application config file I get a no bean defined error instead.

Any help would be greatly appreciated.

Try to use @Resource(name = "baseUrl") in your MyService class. This will tell Spring which exact bean to take and will resolve ambiguity.

Another option is to change XML configuration and add primary="true" to declaration of baseUrl bean

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