java - Autowired 不会为相同类型的多个 bean 抛出异常

标签 java spring

我正在开发基本的@Autowired 程序,其中有 2 个类 AlphaBeta。这里 Alpha 使用 @Autowired 依赖于 Beta

在 spring 配置文件中,我为类 Beta 类型创建了 1 个以上的 bean,所以当它试图在 Alpha 类中注入(inject)依赖项时,我期待 Spring 出现异常,因为有 2 个 Beta bean而不是 1。但是在我的程序中,我没有收到任何异常,它运行得非常好。

这是我的代码:

Alpha.java

public class Alpha {
    @Autowired
    private Beta beta;

    public Alpha() {
        System.out.println("Inside Alpha constructor.");
    }

    @Override
    public String toString() {
        return "Alpha [beta=" + beta + "]";
    }

}

Beta.java

public class Beta {
    public Beta() {
        System.out.println("Inside Beta constructor.");
    }

    @Override
    public String toString() {
        return "This is Beta";
    }
}

spring-config.xml

<beans>

   <context:annotation-config/>

   <bean id="alpha" class="Alpha">
   </bean>

   <bean id="beta" class="Beta">
   </bean>

   <bean id="beta1" class="Beta">
   </bean>

   <bean id="beta2" class="Beta">
   </bean>

</beans>

主程序:

public static void main(String[] args) {
      ApplicationContext context = 
             new ClassPathXmlApplicationContext("beans.xml");

      Alpha alpha = (Alpha) context.getBean("alpha");

      System.out.println(alpha);
   }

这是输出:

Inside Alpha constructor.
Inside Beta constructor.
Inside Beta constructor.
Inside Beta constructor.
Alpha [beta=This is Beta]

最佳答案

它按名称 Autowiring 。您有三个 Beta1 类型的 bean,分别命名为 betabeta1beta2。您的字段名为 beta。 Spring 将使用它作为找到相应 bean 的提示。

如果你命名了你的字段

@Autowired
private Beta whatever;

Spring 将没有(有用的)提示,并且无法选择合适的 bean。

在Spring文档中不是很明显,需要从各个章节中去推断。

来自 chapter concerning @Autowired 中的注释

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.

对于 @Qualifier值(或者说缺少 @Qualifier)

For a fallback match, the bean name is considered a default qualifier value

然后从chapter on @Resource

If no name is specified [in the @Resource annotation] explicitly, the default name is derived from the field name or setter method. In case of a field, it takes the field name; in case of a setter method, it takes the bean property name.

关于java - Autowired 不会为相同类型的多个 bean 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31923421/

相关文章:

java - Spring : Always say forbidden - Status 403

java - 如何使用 Spring 表达式语言以编程方式自定义 bean 表达式的评估

java - Android ListView不显示数据库信息

java - JPA:通过接口(interface)查找而不是实现

java - 为什么我的 BST 不会写入文件?

java - 是否可以停用 Spring Integration 对现有消息 channel 的检查?

java - 通过用户对象从 Hashmap 获取值

java - log4j.xml中的参数值解释

spring - 在测试文件夹Spring中定义一个JPA Repository

mysql - 如何在 hibernate 中删除具有外键的行?