gpt4 book ai didi

Spring 3 构造函数 Autowiring - 为什么这段代码有效?

转载 作者:行者123 更新时间:2023-12-04 19:06:00 24 4
gpt4 key购买 nike

Spring 版是3.2

在 Spring in Action,第三版,在 3.1.1 下。它说明了四种 Autowiring ,即

Autowiring by constructor shares the same limitations as byType. Spring won’t attempt to guess which bean to autowire when it finds multiple beans that match a constructor’s arguments. Furthermore, if a class has multiple constructors, any of which can be satisfied by autowiring, Spring won’t attempt to guess which constructor to use.



最后一句话让我感到困惑。我有以下bean定义:
<bean id="independentBean" class="autowiring.IndependentBean" scope="prototype" />
<bean id="weirdBean" class="autowiring.WeirdBean" scope="prototype" />

<bean id="dependentBeanAutowiredByName" class="autowiring.DependentBean" autowire="byName" />
<bean id="dependentBeanAutowiredByType" class="autowiring.DependentBean" autowire="byType" />
<bean id="dependentBeanAutowiredByConstructor" class="autowiring.DependentBean" autowire="constructor" />

IndependentBean 和 WeirdBean 是空类。

DependendBean 定义如下:
package autowiring;

public class DependentBean {
private IndependentBean independentBean;
private IndependentBean anotherBean;
private WeirdBean weirdBean;

public DependentBean() {

}

public DependentBean(IndependentBean independentBean) {
super();
this.independentBean = independentBean;
}

public DependentBean(IndependentBean independentBean, IndependentBean anotherBean) {
super();
this.independentBean = independentBean;
this.anotherBean = anotherBean;
}

public DependentBean(IndependentBean independentBean, IndependentBean anotherBean, WeirdBean weirdBean) {
super();
this.independentBean = independentBean;
this.anotherBean = anotherBean;
this.weirdBean = weirdBean;
}

// getters and setters for each field...

}

现在让我们回顾一下粗体的声明:

Furthermore, if a class has multiple constructors, any of which can be satisfied by autowiring, Spring won’t attempt to guess which constructor to use.



据此,我本来预计,当尝试实例化dependentBeanAutowiredByConstructor 时,Spring 会抛出异常,而不是
知道使用三个构造函数中的哪一个。但是代码运行得很好。

那么,这是怎么回事?为什么这段代码有效?错误情况是什么
上述声明中提到的?

最佳答案

我认为这可能是作者最了解的 :-),但我将分享我如何看待它以及我如何理解它。

他说“Spring 不会尝试猜测”,这意味着 Spring 不会只使用 Math.random()并随机获取三个构造函数之一,只是因为都匹配。这意味着 Spring 遵循一个规则,它是预先确定的和确定性的(在同一测试的多次尝试中,将有相同的输出)。

AutowiredAnnotationBeanPostProcessorJavadoc :

If multiple non-required constructors carry the annotation, they will be considered as candidates for autowiring. The constructor with the greatest number of dependencies that can be satisfied by matching beans in the Spring container will be chosen.



因此,如果所有三个构造函数都匹配(在您的测试中发生),则匹配参数最多的一个获胜。

关于Spring 3 构造函数 Autowiring - 为什么这段代码有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24330421/

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