@Autowired发现模糊的依赖关系,仍然有效.怎么样?

Nit*_*tal 1 java spring annotations spring-annotations

为什么Spring不会抛出NoSuchBeanDefinitionException存在模糊依赖关系的地方,并且有多个bean候选者使用@Autowired注释进行自动装配?

我有这个简单的beans.xml,它有两个相同的bean,具有不同的id category,category1并且出于某种原因,Spring选择categorybean进行自动装配.我的印象是@Autowired注释byType在内部使用自动装配,因为这里有多个匹配,Spring会抛出NoSuchBeanDefinitionException异常.

我在3.2.13.RELEASE这里使用spring版本.

beans.xml中

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans 
     .....   ">

        <context:annotation-config />

        <bean id="product" class="com.study.spring.Product">
            <property name="id" value="101"/>
            <property name="name" value="Apple iPhone"/>
            <property name="active" value="true"/>
        </bean>

        <bean id="category1" class="com.study.spring.Category">
            <property name="id" value="202"/>
            <property name="name" value="Phone"/>
            <property name="active" value="true"/>
        </bean>

        <bean id="category" class="com.study.spring.Category">
            <property name="id" value="201"/>
            <property name="name" value="Communications"/>
            <property name="active" value="true"/>
        </bean>

    </beans>
Run Code Online (Sandbox Code Playgroud)

Product.java

package com.study.spring;

import org.springframework.beans.factory.annotation.Autowired;

public class Product {
    private int id;
    private String name;
    private boolean active;
    @Autowired
    private Category category;

    //getters and setters here
}
Run Code Online (Sandbox Code Playgroud)

ret*_*eto 5

Category使用带有id 的对象,category因为它匹配字段的名称.旧的春季文档解释如下:

"对于后备匹配,bean名称被视为默认限定符值."

当前文档解释了这一点更清晰.您有一个"byName"自动装配情况:

按属性名称自动装配.Spring查找与需要自动装配的属性同名的bean.例如,如果bean定义按名称设置为autowire,并且它包含master属性(即,它具有setMaster(..)方法),则Spring会查找名为master的bean定义,并使用它来设置属性.

  • 是的,我明白.我将`category`重命名为`category1`,导致异常`NoSuchBeanDefinitionException`.因此,在模糊的情况下,Spring有一个回退机制,它解决了bean歧义`byName`自动装配功能,否则`byType`是默认的. (2认同)