Sunday, 2 June 2013

Spring bean scopes

About Spring bean scope attributes




As we aware of that the beans configured in the spring beans XML configuration file are instantiated and managed by spring container. Spring also allows configuring each particular bean scope that satisfies the requirement. From spring version 2.0, it supports five built-in scopes Out of which three spring bean scopes are supported only in web ApplicationContext.


Bean scopes:-



singleton – This is the default scope used by the spring Ioc container. If we use this scope attribute then it returns a single bean instance per Spring IoC container. If no scope is defined in bean configuration file, then the default bean scope is set to singleton.

prototype – It means not singleton, returns a new bean instance each time when requested or referenced.

request – This scope is valid only when using a web aware spring ApplicationContext. If specified then this attribute will help to return a single bean instance per HTTP request.

session – This scope is also valid only when using a web aware spring ApplicationContext. If specified then this attribute will help to return a single bean instance per HTTP session. Then the bean scoped with a session is shared between all the session’s requests.

globalSession – This scope is also valid only when using a web aware spring ApplicationContext. If specified then this attribute will help to return a single bean instance per global HTTP session. This scope has importance only in context of portal-based web applications and it is mainly related to Portlet applications. Each portlet has its own session but if we want to store variables globally for all portlets in our applications then we can use globalSession scope attribute. According to portlet specification, the conception of a global session is that it is shared among all of the various portlets that make up a single portlet web application. Beans defined with the help of global session attribute scope are bound or scoped to the lifetime of the global portlet Session.

Note: - As we know that three spring bean scopes are supported only in web ApplicationContext So If we use these scopes with Spring IoC container such as the ClassPathXmlApplicationContext, then IllegalStateException  will be thrown at runtime complaining that No Scope registered for scope 'scope attribute'. In the following way we can use the scope attributes.

Example: - <bean id="kidsBean" class="com.spring.gaurav.constructorinjection.example.Kids" scope="prototype">
</bean>

Example of Bean Scope attribute:-

System Requirements:-
  •          Eclipse Editor or any other.
  •          JDK 1.5 or higher(I am using jdk 1.7.0_03)
  •          Spring jars.
Required Jars are:-
  • spring-core.jar
  • spring-2.5.jar
  • spring-beans.jar
  • spring-context.jar
  • commons-logging.jar
  • dom4j-1.4.jar
  • antlr.jar
  • log4j.jar

Steps for creating Eclipse java project for implementing spring bean scopes:-
  • Create a java project in eclipse.
  • Create a package in the src folder with the name as com.spring.gaurav.beanscope.test.singleton.example.
  • Create the below files in this package and place the corresponding code in those files.
  • Create an XML file and name it as beanscope-test-singleton-beans.xml and place this file in the classpath outside the srcfolder.
  • Execute the BeanScopeSingletonTestClient.java by selecting the option Run as Java Application.

 Singleton Scope attribute example:-

 Country.java


package com.spring.gaurav.beanscope.test.singleton.example;

public class Country {
            private String countryName;
            private String primeMinisterName;

            public String getCountryName() {
                        return countryName;
            }

            public void setCountryName(String countryName) {
                        this.countryName = countryName;
            }

            public String getPrimeMinisterName() {
                        return primeMinisterName;
            }

            public void setPrimeMinisterName(String primeMinisterName) {
                        this.primeMinisterName = primeMinisterName;
            }

}


beanscope-test-singleton-beans.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="countryBean" class="com.spring.gaurav.beanscope.test.singleton.example.Country" />

</beans>


BeanScopeSingletonTestClient.java

package com.spring.gaurav.beanscope.test.singleton.example;

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

public class BeanScopeSingletonTestClient {
            public static void main(String args[]) {
                        ApplicationContext context = new ClassPathXmlApplicationContext(
                                                "beanscope-test-singleton-beans.xml");
                        Country country1 = (Country) context.getBean("countryBean");
                        country1.setCountryName("MAURITIUS(REPUBLIC OF MAURITIUS)");
                        country1.setPrimeMinisterName("MR. NAVINCHANDRA RAMGOOLAM");
                        // Requesting first time to retrieve the bean class property value
                        System.out.println("COUNTRY NAME IS :- " + country1.getCountryName()
                                                + " \nCOUNTRY PRIME MINISTER IS :- "
                                                + country1.getPrimeMinisterName());
                       
                        System.out.println("****************************************************************");
                        System.out.println("REQUESTING SECOND TIME TO RETRIEVE THE BEAN CLASS PROPERTY VALUE");
                        Country country2 = (Country) context.getBean("countryBean");
                        // Requesting second time to retrieve the bean class property value
                        System.out.println("COUNTRY NAME IS :- " + country2.getCountryName()
                                                + " \nCOUNTRY PRIME MINISTER IS :- "
                                                + country2.getPrimeMinisterName());
                       
            }
}



/**
 * Note:- As I have not declared scope attribute in
 * "beanscope-test-singleton-beans.xml" XML configuration file, so the default
 * singleton scope attribute is taken. As I requested two time but I got the
 * same property values for the bean class. So we can conclude that we have
 * single bean instance by default.
 */

Result:-

log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
COUNTRY NAME IS :- MAURITIUS(REPUBLIC OF MAURITIUS)
COUNTRY PRIME MINISTER IS :- MR. NAVINCHANDRA RAMGOOLAM
****************************************************************
REQUESTING SECOND TIME TO RETRIEVE THE BEAN CLASS PROPERTY VALUE
COUNTRY NAME IS :- MAURITIUS(REPUBLIC OF MAURITIUS)
COUNTRY PRIME MINISTER IS :- MR. NAVINCHANDRA RAMGOOLAM

Prototype Scope attribute example:-


Steps for creating Eclipse java project for implementing constructor dependency injection:-
  • Create a java project in eclipse.
  • Create a package in the src folder with the name as com.spring.gaurav.beanscope.test.prototype.example.
  • Create the below files in this package and place the corresponding code in those files.
  • Create an XML file and name it as beanscope-test-prototype-beans.xml and place this file in the classpath outside the srcfolder.
  • Execute the BeanScopePrototypeTestClient.java by selecting the option Run as Java Application.
 
Note: - In this example also I am using the same country bean class which is available above.
beanscope-test-prototype-beans.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="countryBean" class="com.spring.gaurav.beanscope.test.prototype.example.Country" scope="prototype"/>

</beans>


BeanScopePrototypeTestClient.java

package com.spring.gaurav.beanscope.test.prototype.example;

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

public class BeanScopePrototypeTestClient {
            public static void main(String args[]) {
                        ApplicationContext context = new ClassPathXmlApplicationContext(
                                                "beanscope-test-prototype-beans.xml");
                        Country country1 = (Country) context.getBean("countryBean");
                        country1.setCountryName("KINGDOM OF BHUTAN");
                        country1.setPrimeMinisterName("MR. JIGME YOSER THINLEY");
                        // Requesting first time to retrieve the bean class property value
                        System.out.println("COUNTRY NAME IS :- " + country1.getCountryName()
                                                + " \nCOUNTRY PRIME MINISTER IS :- "
                                                + country1.getPrimeMinisterName());

                        System.out
                                                .println("****************************************************************");
                        System.out
                                                .println("REQUESTING SECOND TIME TO RETRIEVE THE BEAN CLASS PROPERTY VALUE");
                        Country country2 = (Country) context.getBean("countryBean");
                        // Requesting second time to retrieve the bean class property value
                        System.out.println("COUNTRY NAME IS :- " + country2.getCountryName()
                                                + " \nCOUNTRY PRIME MINISTER IS :- "
                                                + country2.getPrimeMinisterName());

            }
}



/**
 * Note:- As I have declared scope attribute as prototype in
 * "beanscope-test-prototype-beans.xml" XML configuration file, and I requested
 * two time and got different property values for the bean class. So we can
 * conclude that it returns a new bean instance each time when requested or
 * referenced.
 */

Result:-

log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
COUNTRY NAME IS :- KINGDOM OF BHUTAN
COUNTRY PRIME MINISTER IS :- MR. JIGME YOSER THINLEY
****************************************************************
REQUESTING SECOND TIME TO RETRIEVE THE BEAN CLASS PROPERTY VALUE
COUNTRY NAME IS :- null
COUNTRY PRIME MINISTER IS :- null


Back to Interview Questions

No comments:

Post a Comment