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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4968680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:51:10  来源:igfitidea点击:

Java/Spring Problem with @Service and @Autowired annotations

javaspringannotationsjavabeans

提问by user6778654

[spring 3.0.5] [jboss 5.1]

[春季 3.0.5] [jboss 5.1]

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

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

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.

T。

采纳答案by Bozho

A few options:

几个选项:

  • Use @Resource(name="test1")in the injection point
  • can use the javax.inject.Qualifermechanism. In short - you define an annotation (@Test) and annotate the annotation with @Qualifier. Then use @Autowired @Teston 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
  • 使用@Resource(name="test1")的注射点
  • 可以使用javax.inject.Qualifer机制。简而言之 - 您定义了一个注释 ( @Test) 并用@Qualifier. 然后@Autowired @Test在注射点使用。
  • 在目标 bean 上显式设置限定符。文档说只显示 xml 版本<qualifier />,但尝试添加@Qualifier("test1")服务定义

Here is the documentation about it

这是关于它的文档