Thursday, December 31, 2015

Can we define a bean with Prototype scope inside a bean with singleton scope in a spring context?

Yes, You can define.

But you will have only one instance created for the inner bean also even though it has prototype scope because it's being called from a outer bean which is in a singleton scope (default spring bean scope).

See the below example to understand in detail.

Project Structure:






App.java

package com.rajesh.common.controller;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.rajesh.common.bean.HelloWorld;

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

HelloWorld obj = (HelloWorld) context.getBean("helloBean");
System.out.println("1st HelloWorld : " + obj);
System.out.println("1st HelloClass : "+obj.getHelloClass());
HelloWorld obj2 = (HelloWorld) context.getBean("helloBean");
System.out.println("2nd HelloWorld : " + obj2);
System.out.println("2nd HelloClass : "+obj2.getHelloClass());
obj.printHello();
}
}



HelloWorld.java

package com.rajesh.common.bean;

public class HelloWorld {
HelloClass helloClass;

public void printHello() {
helloClass.printHello();
}

public HelloClass getHelloClass() {
return helloClass;
}

public void setHelloClass(HelloClass helloClass) {
this.helloClass = helloClass;
}
}

HelloClass.java

package com.rajesh.common.bean;

public class HelloClass {

private String name;

public void setName(String name) {
this.name = name;
}

public void printHello() {
System.out.println("Spring 3 : Hello ! " + name);
}


}


applicationcontext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="HelloClass" class="com.rajesh.common.bean.HelloClass" scope="prototype">
<property name="name" value="rajesh" />
</bean>
<bean id="helloBean" class="com.rajesh.common.bean.HelloWorld" >
<property name="helloClass" ref="HelloClass" />
</bean>

</beans>



Here is output of this program.

1st HelloWorld : com.rajesh.common.bean.HelloWorld@4dd36dfe
1st HelloClass : com.rajesh.common.bean.HelloClass@73da669c
2nd HelloWorld : com.rajesh.common.bean.HelloWorld@4dd36dfe
2nd HelloClass : com.rajesh.common.bean.HelloClass@73da669c
Spring 3 : Hello ! rajesh


Analysis : If you observe the above output, you have the same instance returned in both the places for the HelloClass bean even though it's defined with prototype scope because the Helloworld bean is defined with default scope (singleton) and hence the result.









No comments:

Post a Comment