gpt4 book ai didi

java - 请解释一下在 Spring 中通过构造函数 Autowiring 的这种(歧义)行为

转载 作者:搜寻专家 更新时间:2023-11-01 03:39:38 26 4
gpt4 key购买 nike

我先提供一小段代码,然后我会要求解释。

public class A {
private String msg;
private B b;

public A () {
System.out.println("No argument constructor is called");
}

public A (B b) {
System.out.println("Parameterized constructor is called");
this.b = b;
}

// getters and setters
}

==============================================

<bean id="a" class="A" p:msg="hello" autowire="constructor"/>

<bean id="b" class="B"/>

==============================================

输出:

Parameterized constructor is called

这是正常的行为,可以理解

==============================================

现在,我正在添加 B 类的新 bean 定义,如下所示。

<bean id="a" class="A" p:msg="hello" autowire="constructor"/>

<bean id="b" class="B"/>

<bean id="c" class="B"/>

因此,据我所知,由于通过构造函数的 Autowiring 在内部使用“byType”,因此它会给出一个关于违反 bean 唯一性的异常,例如,如果我使用 autowire="byType",就会出现这种情况。

但奇怪的是,输出如下。

输出:

No argument constructor is called

========================================

但是请注意,如果类A中没有指定默认构造函数,那么就会出现预期的异常。那么,这是 Spring IoC 容器的默认行为吗?如果是,请详细解释一下。

提前谢谢你。

这个问题也可以在 LinkedIn ( Spring autowiring through constructor ambiguity ) 中找到

最佳答案

If a class has multiple constructors, any of which can be satisfied by autowiring, then Spring will throw an exception as it cannot decide which bean to auto-wire.

http://www.studytrails.com/frameworks/spring/spring-auto-wire-constructor.jsp

所以这意味着如果你有多个构造函数,spring 需要选择一个。而 spring 非常聪明,可以选择它可以连线的那个。所以你只有 B bean 它使用带有 B 参数的构造函数。如果你有两个 B bean,它不能使用这个构造函数,因为 B 不是唯一的,所以它会回退到默认构造函数。如果你删除这个构造函数,你会得到异常。

关于java - 请解释一下在 Spring 中通过构造函数 Autowiring 的这种(歧义)行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17667581/

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