Searching...
Friday, 14 June 2013

Spring Bean scopes example

11:18

Spring Bean scopes

The Spring Framework supports following five scopes, three of which are available only if you use a web-aware ApplicationContext.

singleton
This scopes the bean definition to a single instance per Spring IoC container (default).

prototype
This scopes a single bean definition to have any number of object instances.

request
This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.

session
This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

global-session
This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext

Example

Spring configuration

Note: By default scope is singleton ,not mandatory to specify this scope

<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-2.5.xsd">

    <bean id="studentBean" class="com.vinod.test.Student" scope="singleton">
    </bean>
</beans>


Test class 

package com.vinod.test;

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

public class SpringCoreScopeTest {

    public static void main(String arg[]) {
        // Getting beans from XML based bean configuration
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-core.xml");
        // Student bean
        Student obj = (Student) context.getBean("studentBean");
        obj.setName("vinod");
        System.out.println(obj.getName());
       
       
        Student obj1 = (Student) context.getBean("studentBean");   
        //Let us check whether getting the same object or not.
        System.out.println(obj1.getName());

    }
}
 

Output

vinod
vinod

Here we can see the same object we are getting it from the context during the second call as it is singleton.

Let us change the bean scope to prototype and run the above program.

    <bean id="studentBean" class="com.vinod.test.Student" scope=“prototype">

Output

vinod
null

…Done!!!

 

 

0 comments: