Monday, May 18, 2015

Solve Spring NoUniqueBeanDefinitionException

I encountered the NoUniqueBeanDefinitionException where-in Spring was unable to which class to inject for an Autowired variable even though the it was properly qualified!

This happened because the Qualifier did not get post-processed and so multiple implementations of the Interface type of the variable being injected were now available in the classpath. So Spring found more that one instance and was unable to decide which instance to inject for the particular Autowired target.

The turn on the default AutowiredAnnotationBeanPostProcessor which processes the @Qualifier , you need to add the line to the beans section of your spring configuration. Since this was missing from the beans section of the configuration file, the Qualifier annotation was ignored in this code:

    @Autowired
    public void setDao(@Qualifier("myDaoImpl") MyDAO dao) {

And here is a snippet of the exception that was logged:

 java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Injection of autowired dependencies failed for class [class my.package.impl.name.MyBeanClassName]; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void my.package.impl.name.MyBeanClassName.setDao(my.package.intf.name.MyDAO); nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [my.package.intf.name.MyDAO] is defined: expected single matching bean but found 4: myDaoImpl,secondDaoImpl,thirdDaoImpl,fourthDaoImpl

This error was resolved after adding the below line to the beans section of spring configuration:

<context:annotation-config></context:annotation-config>

1 comment:

caris said...

Ace4sure is the website that deals in preparation material for the exam for many years. According to my exposure and research, this is the right platform where you can get exact PCNSA Exam Dumps.

LinkWithin

Related Posts Plugin for WordPress, Blogger...