@Autowired
我正在尝试使用以下spring文档中的示例来实现细粒度配置:http: //docs.spring.io/spring/docs/3.2.0.RELEASE/spring-framework-reference/html/beans.html #beans-autowired-annotation-qualifiers。
给定以下测试用例:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=ExampleConfiguration.class)
public class ExampleTest {
@Autowired @ExampleQualifier(key="x")
private ExampleBean beanWithQualifierKeyX;
@Test
public void test() {
System.out.println(this.beanWithQualifierKeyX);
}
}
和以下配置:
@Configuration
public class ExampleConfiguration {
@Bean
@ExampleQualifier(key = "x")
public ExampleBean exampleBean1() {
return new ExampleBean();
}
@Bean
@ExampleQualifier(key = "y")
public ExampleBean exampleBean2() {
return new ExampleBean();
}
@Bean
public ExampleBean exampleBean3() {
return new ExampleBean();
}
}
使用自定义限定符注解:
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface ExampleQualifier {
String key();
}
我期望的是以下内容:beanWithQualifierKeyX
应该使用配置类中的第一个 bean 自动装配该属性。配置上的注释和属性上的注释都有key="x"
设置,所以这应该是唯一的匹配。据我所知,这MovieQualifier
与 Spring 示例文档中的注释几乎相同。
但是,当我执行测试时,出现以下错误:
org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private xxx.ExampleBean xxx.ExampleTest.beanWithQualifierKeyX;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [xxx.ExampleBean] is defined:
expected single matching bean but found 2: [exampleBean1, exampleBean2]
看起来 Spring 确实对注释执行了匹配(因为两者都exampleBean1
被exampleBean2
注释了),但没有考虑key
注释的值 - 否则x
将是一个完美的匹配。
我是否在配置过程中遗漏了什么或者为什么没有匹配?
我使用的 Spring 版本是 3.2.0.RELEASE