我正在创建一个演示来理解我如何通过使用构造函数自动装配将原型bean注入到单例bean中。这是我的代码 我的第一个豆是
public class IndependentBean {
private String independentName;
public IndependentBean()
{
System.out.println("Independent called");
}
public String getIndependentName() {
return independentName;
}
public void setIndependentName(String independentName) {
this.independentName = independentName;
}
}
现在我正在创建一个独立的bean
package com.sample.beans;
public abstract class DependentBean {
private IndependentBean d1;
private IndependentBean d2;
public DependentBean()
{
System.out.println("Default Constructor for dependent");
}
public IndependentBean getD1() {
return d1;
}
public void setD1(IndependentBean d1) {
System.out.println("Setting d1");
this.d1 = d1;
}
public IndependentBean getD2() {
return d2;
}
public void setD2(IndependentBean d2) {
System.out.println("Setting d2");
this.d2 = d2;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DependentBean(IndependentBean d1) {
System.out.println("With 1");
this.d1 = d1;
}
public DependentBean(IndependentBean d1, IndependentBean d2) {
this.d1 = d1;
this.d2 = d2;
System.out.println("With 2");
}
public abstract IndependentBean getIndependent();
}
这是我的 context.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
<bean class="com.sample.beans.IndependentBean" id="firstIn" scope="prototype">
<property name="independentName" value="firstIndependent" />
</bean>
<bean class="com.sample.beans.DependentBean" id="autowireByConstructor"
autowire="constructor">
<lookup-method name="getIndependent" bean="firstIn" />
</bean>
</beans>
这是我的主要课程
package com.sample.beans;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainClass {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"classpath:context.xml");
ctx.getBean("autowireByConstructor");
ctx.close();
}
}
根据Spring规范,我知道当我使用构造函数进行自动装配时,将调用满足大多数依赖项的构造函数。 但是在这种情况下,独立bean的构造函数应该调用2次。但在我的情况下,构造函数被调用4次。我没有清楚地说明这一点。请帮我理解这个?
以下是代码的输出:
独立称为 独立称为 独立称为 独立称为 随着2
请帮助我理解这种行为。
答案 0 :(得分:0)
我在Spring Docs中找到了这个问题的答案。
虽然我们使用查找方法注入,但Spring使用cglib代理来满足要求。当Spring使用cglib代理时,目标bean的构造函数称为两次。 因此,在我的情况下,因为将创建Independent bean的两个代理,并且将被调用4次构造函数。