Wednesday, 4 May 2011

Spring Beans


Spring Bean, any object in the Spring framework that we initialize through Spring container is called Spring Bean. Any normal Java POJO class can be a Spring Bean if it’s configured to be initialized via container by providing configuration metadata information.


Spring Bean Scopes

There are five scopes defined for Spring Beans.

singleton – Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope, make sure bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues.

prototype – A new instance will be created every time the bean is requested.

request
– This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.

session – A new bean will be created for each HTTP session by the container.

global-session – This is used to create global session beans for Portlet applications.
Spring Framework is extendable and we can create our own scopes too, however most of the times we are good with the scopes provided by the framework.

Spring Bean Configuration

Spring Framework provide three ways to configure beans to be used in the application.

Annotation Based Configuration – By using @Service or @Component annotations. Scope details can be provided with @Scope annotation.
XML Based Configuration – By creating Spring Configuration XML file to configure the beans. If you are using Spring MVC framework, the xml based configuration can be loaded automatically by writing some boiler plate code in web.xml file.
Java Based Configuration – Starting from Spring 3.0, we can configure Spring beans using java programs. Some important annotations used for java based configuration are @Configuration, @ComponentScan and @Bean.


You may like the following posts:

No comments:

Post a Comment