@Service和@Autowired注释的Java/Spring问题

use*_*654 5 java spring annotations javabeans

[春季3.0.5] [jboss 5.1]

我有几个标记为的类@Service,它实现了相同的接口.

例如,

@Service(value="test1") 
public TestImpl1 implements Test {} 
@Service(value="test2") 
public TestImpl2 implements Test {} 
Run Code Online (Sandbox Code Playgroud)

接下来,我有以下结构

public SomeClass { 
@Autowired 
@Qualifier("test1") 
Test test1; 
@Autowired 
@Qualifier("test2") 
Test test2; 
Run Code Online (Sandbox Code Playgroud)

我得到一个例外(在部署时)

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) 
Run Code Online (Sandbox Code Playgroud)

有谁知道如何解决这个问题?

T.

Boz*_*zho 4

几个选项:

  • @Resource(name="test1")在注射点使用
  • 可以使用该javax.inject.Qualifer机制。简而言之 - 您定义一个注释 ( @Test) 并用 来注释该注释@Qualifier@Autowired @Test然后在注射点使用。
  • 在目标 bean 上显式设置限定符。文档说仅显示 xml 版本<qualifier />,但尝试添加@Qualifier("test1")服务定义

这是有关它的文档