Spring Bean Scopes – Examples


There are 5 spring bean scopes as below:

1. Singleton: 

If scope is set to singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object.

If we not set any scope to bean then spring container will set to the default scope and default scope of the bean is always singleton. use ‘singleton’ to set the bean scope to Singleton.

2. Prototype

If scope is set to prototype, the Spring IoC container creates new bean instance of the object every time a request for that specific bean is made.

Use ‘prototype’ word during spring configuration to set the bean scope to Proto Type.

As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans.

3. Request:

This scopes a bean definition to an HTTP Request and its only valid in the context of a web-aware Spring ApplicationContext.

Use the ‘request’ keyword to set the bean scope to HttpRequest during spring bean configuration.

4. Session:

This scopes a bean definition to an HTTP Session and its only valid in the context of a web-aware Spring ApplicationContext.

Use the ‘session’ keyword to set the bean scope to Http Session during spring bean configuration.

5. Global Session

This scopes a bean definition to a Global HTTP Session and its only valid in the context of a web-aware Spring ApplicationContext.

Use the ‘global-session’ keyword to set the bean scope to Global Http Session during spring bean configuration.

Configuration of these scopes can be done as below:

Define the above mentioned scopes in beans.xml file along with bean declaration.

<!– A bean definition with singleton scope –>
<bean id=”…” class=”…” scope=”singleton”>
<!– collaborators and configuration for this bean go here –>
</bean>

Can also be mention the bean scope using annotation:

@Configuration
public class BeanJavaConfiguration {
@Bean
@Scope(“prototype”)
public Appleapp() {
return new Apple();
}
}

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.