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

时间:2015-03-04 20:51:35

标签: java spring annotations spring-annotations

为什么Spring没有抛出NoSuchBeanDefinitionException哪里存在模糊的依赖关系,并且使用@Autowired注释找到了多个用于自动装配的bean候选者?

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

我在这里使用的是弹簧版3.2.13.RELEASE

的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>

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
}

1 个答案:

答案 0 :(得分:5)

Category对象的标识为category,因为它与字段名称匹配。旧spring documentation解释为:

  

&#34;对于后备匹配,bean名称被视为默认限定符值。&#34;

current documentation更清楚地解释了这一点。你有一个&#34; byName&#34;这里的自动装配情况:

  

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

相关问题