Spring @Qualifier does not work when bean is in another jar file

I have a number of Spring beans, some of which are in a jar with a shared library. It seems I can not work @Qualifier .

I have default-autowire set to "byType", this uses Spring 3.1.0.M2 and works as a standalone executable. If I remove "TestTwoBean" from the shared library, the project will execute as expected.

MYPROJ-shared lib.jar:

 @Service public class TestOneBean implements ITestBean { } @Service public class TestTwoBean implements ITestBean { } 

myproj.jar:

 @Service public class TestConsumerBean { @Autowired @Qualifier("testOneBean") private ITestBean bean; } 

I get a "unique bean exception named" at runtime:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name "testConsumerBean" defined in file [-]: Invalid dependency expressed through bean property 'bean' :: No unique bean of type [com.myco.ITestBean] : expected single match bean, but found 2: [testOneBean, testTwoBean]; nested exception org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.myco.TestBean]: expected single bean match, but found 2: [testOneBean, testTwoBean] in org.springframework.beans.factory.sute. .autowireByType (AbstractAutowireCapableBeanFactory.java:1167) ...

Does @Qualifier in this situation? Is a workaround known?

0
source share
1 answer

Are you sure you want to use autwire like AND annotation injection? Autowire by type means that spring will try to inject detected setters and constructor parameters using type search, even if they are not annotated for injection.

At the same time, you are trying to enter fields by name. Your annotated @Service classes produce beans with names that default to the class name, "testOneBean" and "testTwoBean" respectively. @Qualifier uses bean names as valid matches. The recommended method of introducing "by name", but using @Resource(name="testOneBean") . I can only guess that spring is trying to inject by type because of the autwire mode set by type (which I doubt you really need).

I would recommend reverting to the default autwire mode and using @Resource to post by name.

+2
source

Source: https://habr.com/ru/post/918648/


All Articles