Spring @Qualifier注释问题

时间:2014-03-11 20:25:55

标签: spring

在以下示例中,@Qualifier注释无效。 我在Spring XML配置中声明了一个属性文件,如下所示:

<context:property-placeholder />
<util:properties id="xx" location="classpath:file.properties" />

然后将util.properties文件自动装入@Component带注释的类中:

@Autowired
private Properties props;

抛出以下异常:

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: 
No qualifying bean of type [java.util.Properties] is defined: expected single matching 
bean but found 2: xx,systemProperties

所以有两个属性文件,其中一个是 xx 。但是当我添加@Qualifier注释时......

@Autowired
@Qualifier("xx")
private Properties props;

...抛出此异常:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type [java.util.Properties] found for dependency: 
expected at least 1 bean which qualifies as autowire candidate for this dependency. 
Dependency annotations 
{@org.springframework.beans.factory.annotation.Autowired(required=true)  
@org.springframework.beans.factory.annotation.Qualifier(value=xx)}

没有@Qualifier,Spring发现了两个java.util.Properties实例,其中一个是 xx 。但是对于@Qualifier,它没有看到 xx 文件。使用@Resource时会出现同样的问题。

什么配置不正确? 感谢

1 个答案:

答案 0 :(得分:3)

@Qualifier注释语义不适合按名称注入bean或注入集合。

As the documentation states:

  

如果您打算按名称表达注释驱动的注入,请不要   主要使用@Autowired,即使技术上能够引用   通过@Qualifier值获取bean名称。相反,使用JSR-250   @Resource注释,在语义上定义为标识a   特定目标组件的唯一名称,具有声明的类型   与匹配过程无关。

     

作为这种语义差异的一个特定结果,是   自己定义为集合或地图类型不能注入   通过@Autowired ,因为类型匹配不适用   给他们。对于这样的bean使用@Resource,参考具体的   按唯一名称收集或映射bean。

在这种情况下,您应该使用@Resource(name = "xx")作为the Properties you are trying to inject are Maps

相关问题