3

@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 确实对注释执行了匹配(因为两者都exampleBean1exampleBean2注释了),但没有考虑key注释的值 - 否则x将是一个完美的匹配。

我是否在配置过程中遗漏了什么或者为什么没有匹配?

我使用的 Spring 版本是 3.2.0.RELEASE

4

1 回答 1

4

Spring 3.2.0 中存在/曾经存在错误使用 @Qualifier 和 @Qualifier 元注释自动装配在 Spring 3.2 中失败 (在 3.2.1 中修复)

它的描述听起来完全像你的问题。

所以更新到 3.2.1

于 2014-01-14T15:54:17.200 回答