java auto_java-细粒度的Spring自动装配不起作用(@Autowi...

我正在尝试基本上使用spring文档中的示例http://docs.spring.io/spring/docs/3.2.0.RELEASE/spring-framework-reference/html/beans.html#beans-autowired-annotation-qualifiers来实现细粒度的@Autowired配置.

给定以下测试用例:

@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();

}

我期望的是以下内容:应该使用配置类中的第一个bean自动装配属性beanWithQualifierKeyX.配置上的注释和属性上的注释都具有key =“ x”设置,因此这应该是唯一的匹配项.据我所知,这几乎与Spring示例文档中的MovieQualifier注释相同.

但是,当我执行测试时,出现以下错误:

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都进行了注释),但没有考虑注释键的值-否则x将是完美的匹配.

我在配置过程中错过了什么吗?为什么没有匹配项?

我正在使用的Spring版本是3.2.0.RELEASE

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值