开发者

Java/Spring Problem with @Service and @Autowired annotations

开发者 https://www.devze.com 2023-02-10 10:19 出处:网络
[spr开发者_高级运维ing 3.0.5] [jboss 5.1] I have several classes labeled as @Service, which implements thet same interface.

[spr开发者_高级运维ing 3.0.5] [jboss 5.1]

I have several classes labeled as @Service, which implements thet same interface.

For example,

@Service(value="test1") 
public TestImpl1 implements Test {} 
@Service(value="test2") 
public TestImpl2 implements Test {} 

Next, I have the following structure

public SomeClass { 
@Autowired 
@Qualifier("test1") 
Test test1; 
@Autowired 
@Qualifier("test2") 
Test test2; 

I am getting an exception (at deployment)

10:36:58,277 ERROR [[/test-web]] Servlet /test-web threw load() 
exception 
org.springframework.beans.factory.NoSuchBeanDefinitionException: No 
unique bean of type [pl.tests] is defined: expected single matching 
bean but found 2: [test1, test2] 
        at 
org.springframework.beans.factory.support.DefaultListableBeanFactory.doReso lveDependency(DefaultListableBeanFactory.java: 
796) 
        at 
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolv eDependency(DefaultListableBeanFactory.java: 
703) 
        at 
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostPro cessor 
$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java: 
474) 

Anyone know how to solve this?

T.


A few options:

  • Use @Resource(name="test1") in the injection point
  • can use the javax.inject.Qualifer mechanism. In short - you define an annotation (@Test) and annotate the annotation with @Qualifier. Then use @Autowired @Test on the injection point.
  • explicitly set qualifiers on the target bean. The docs say show only the xml version <qualifier />, but try adding @Qualifier("test1") on the service definition

Here is the documentation about it

0

精彩评论

暂无评论...
验证码 换一张
取 消