
Bean scopes in Spring
In Spring user can control the scope of the objects created from a
particular bean definition. This can be achieved by the attribute "scope" in the <bean> tag. Following are the scopes available in the Spring.
- singleton:-Scopes the bean definition to a single instance per Spring container (default).
- prototype:-Allows a bean to be instantiated any number of times but bean is intialized once for a user.
- request:-Scopes a bean definition to an HTTP request. Only valid when used with a webcapable
Spring context (such as with Spring MVC). - session:-Scopes a bean definition to an HTTP session. Only valid when used with a webcapable
Spring context (such as with Spring MVC). - global-session:-Scopes a bean definition to a global HTTP session. Only valid when used in a
portlet context.
Example for various scopes is a follows:-
Note:-The prototype,request,session and global-session examples will be covered in the Web application part. The below example will cover the Singleton example.
<?xml version="1.0" encoding="UTF-8"?> <property name="prices"> <bean id="setterInjection" class="com.visualbuilder.beans.SetterInjectionBean" sscope="singleton" > |
ApplicationContextExample.java
package com.visualbuilder.factory; import org.springframework.context.ApplicationContext; import com.visualbuilder.beans.TestBean; public class ApplicationContextExample { |
Output:-
Jun 2, 2008 12:38:25 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@c4bcdc: display name [org.springframework.context.support.ClassPathXmlApplicationContext@c4bcdc]; startup date [Mon Jun 02 12:38:25 IST 2008]; root of context hierarchy
Jun 2, 2008 12:38:26 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/visualbuilder/xml/spring-beans.xml]
Jun 2, 2008 12:38:26 PM org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@c4bcdc]: org.springframework.beans.factory.support.DefaultListableBeanFactory@d6c16c
afterPropertiesSet method is called
Jun 2, 2008 12:38:26 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@d6c16c: defining beans [test,disposableBean,collectionExample,typeCollectionExample,constructorInjection,setterInjection,wrapperBean]; root of factory hierarchy
Bean is created
Bean has been called
Java Discussion
- - Difference between BMT an
- - Replace getParameterValue
- - Interviewing Next week -
- - Sudoku solver
- - Setting tab order in swin



