gpt4 book ai didi

spring - Spring @Qualifier 注释的问题

转载 作者:行者123 更新时间:2023-12-02 02:09:06 25 4
gpt4 key购买 nike

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

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

然后,util.properties 文件会 Autowiring 到 @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 时也存在同样的问题。

什么配置不正确?谢谢

最佳答案

@Qualifier 注释语义不适合按名称注入(inject) Bean,也不适合注入(inject)集合。

As the documentation states:

If you intend to express annotation-driven injection by name, do not primarily use @Autowired, even if is technically capable of referring to a bean name through @Qualifier values. Instead, use the JSR-250 @Resource annotation, which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.

As a specific consequence of this semantic difference, beans that are themselves defined as a collection or map type cannot be injected through @Autowired, because type matching is not properly applicable to them. Use @Resource for such beans, referring to the specific collection or map bean by unique name.

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

关于spring - Spring @Qualifier 注释的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22335885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com