samedi 28 mars 2015

Autowiring by constructor in Spring creating more objects

I am creating a demo to understand that how can i inject a prototype bean into a singleton bean by using constructor autowiring. Here is my code My First bean is



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;
}
}


Now I am creating an independent 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");
}
}


Here is my context.xml:



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU" xmlns:context="http://ift.tt/GArMu7"
xmlns:aop="http://ift.tt/OpNdV1"
xsi:schemaLocation="http://ift.tt/GArMu6 http://ift.tt/1jdM0fG
http://ift.tt/GArMu7 http://ift.tt/1tY3uA9
http://ift.tt/OpNdV1 http://ift.tt/1oTOpwm">
<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">
</bean>
</beans>


Here is my main class



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();
}

}


According toSpring spec I know that when i am working with autowiring with constructor the constructor with satisfying most dependencies will be called. However in this case the constructor of independent bean should be call 2 times.but in my case the constructor is called 4 times. I am not getting this clearly.Please help me to understand this ?


Here is the output of the code:



Independent called

Independent called

Independent called

Independent called

With 2



Please help me to understand this behaviour.


Aucun commentaire:

Enregistrer un commentaire