Spring Bean Scopes

JavaSpringSpring Mvc

Java Problem Overview


Can someone explain what the scopes are in Spring beans I've always just used 'prototype' but are there other parameters I can put in place of that?

Example of what I'm talking about

<bean id="customerInfoController" class="com.action.Controller" scope="prototype">
	<property name="accountDao" ref="accountDao"/>
	<property name="utilityDao" ref="utilityDao"/>
	<property name="account_usageDao" ref="account_usageDao"/>	
</bean>

Java Solutions


Solution 1 - Java

From the spring specs, there are five types of bean scopes supported :

> 1. singleton(default)* > > Scopes a single bean definition to a single object instance per Spring > IoC container. > > 2. prototype > > Scopes a single bean definition to any number of object instances. > > 3. request > > Scopes a single bean definition to the lifecycle of a single HTTP > request; that is each and every HTTP request will have its own > instance of a bean created off the back of a single bean definition. > Only valid in the context of a web-aware Spring ApplicationContext. > > 4. session > > Scopes a single bean definition to the lifecycle of a HTTP Session. > Only valid in the context of a web-aware Spring ApplicationContext. > > 5. global session > > Scopes a single bean definition to the lifecycle of a global HTTP > Session. Typically only valid when used in a portlet context. Only > valid in the context of a web-aware Spring ApplicationContext.

*default means when no scope is explicitly provided in the <bean /> tag. read more about them here: http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch04s04.html

Solution 2 - Java

In Spring, bean scope is used to decide which type of bean instance should be returned from Spring container back to the caller.

5 types of bean scopes are supported :

  1. Singleton : It returns a single bean instance per Spring IoC container.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 no bean scope is specified in bean configuration file, default to singleton. enter image description here

  2. Prototype : It returns a new bean instance each time when requested. It does not store any cache version like singleton. enter image description here

  3. Request : It returns a single bean instance per HTTP request.

    enter image description here

  4. Session : It returns a single bean instance per HTTP session (User level session).

  5. GlobalSession : It returns a single bean instance per global HTTP session. It is only valid in the context of a web-aware Spring ApplicationContext (Application level session).

In most cases, you may only deal with the Spring’s core scope – singleton and prototype, and the default scope is singleton.

Solution 3 - Java

Just want to update, that in Spring 5, as mentioned in Spring docs, Spring supports 6 scopes, four of which are available only if you use a web-aware ApplicationContext.

> singleton (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

> prototype Scopes a single bean definition to any number of object instances.

> request Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

> session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

>application Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.

>websocket Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

Solution 4 - Java

The Spring documentation describes the following standard scopes:

> singleton: (Default) Scopes a single bean definition to a single object instance per Spring IoC container. > > prototype: Scopes a single bean definition to any number of object instances. > > request: Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext. > > session: Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext. > > global session: Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

Additional custom scopes can also be created and configured using a CustomScopeConfigurer. An example would be the flow scope added by Spring Webflow.

By the way, you argues that you always used prototype what I find strange. The standard scope is singleton and in the application I develop, I rarely need the prototype scope. You should maybe take a look at this.

Solution 5 - Java

Detailed explanation for each scope can be found here in Spring bean scopes. Below is the summary

Singleton - (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

prototype - Scopes a single bean definition to any number of object instances.

request - Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session - Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

global session - Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

Solution 6 - Java

According to the documentation of Spring-Cloud-Config there is one extra scope next to the existing five. It is @RefreshScope.

This is the short description of RefreshScope:

> When there is a configuration change, a Spring @Bean that is marked as > @RefreshScope gets special treatment. This feature addresses the > problem of stateful beans that only get their configuration injected > when they are initialized. For instance, if a DataSource has open > connections when the database URL is changed via the Environment, you > probably want the holders of those connections to be able to complete > what they are doing. Then, the next time something borrows a > connection from the pool, it gets one with the new URL. > > Sometimes, it might even be mandatory to apply the @RefreshScope > annotation on some beans which can be only initialized once. If a bean > is "immutable", you will have to either annotate the bean with > @RefreshScope or specify the classname under the property key > spring.cloud.refresh.extra-refreshable. > > Refresh scope beans are lazy proxies that initialize when they are > used (that is, when a method is called), and the scope acts as a cache > of initialized values. To force a bean to re-initialize on the next > method call, you must invalidate its cache entry. > > The RefreshScope is a bean in the context and has a public > refreshAll() method to refresh all beans in the scope by clearing the > target cache. The /refresh endpoint exposes this functionality (over > HTTP or JMX). To refresh an individual bean by name, there is also a > refresh(String) method.

Solution 7 - Java

A short example what is the difference between @Scope("singleton") (default) and @Scope("prototype"):

DAO class:

package com.example.demo;

public class Manager {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Configuration:

@Configuration
public class AppConfiguration {
    @Bean
    @Scope("singleton")
    public Manager getManager(){
        return new Manager();
    }
}

and MainApp:

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.scan("com.example.demo");
		context.refresh();

		Manager firstManager = context.getBean(Manager.class);
		firstManager.setName("Karol");

		Manager secondManager = context.getBean(Manager.class);
		System.out.println(secondManager.getName());
	}

}

In this example the result is: Karol even if we set this name only for firstManager object. It's because Spring IoC container created one instance of object. However when we change scope to @Scope("prototype") in Configuration class then result is: null because Spring IoC container creates a new bean instance of the object when request for that bean is made.

Solution 8 - Java

About prototype bean(s) : > The client code must clean up prototype-scoped objects and release > expensive resources that the prototype bean(s) are holding. To get the > Spring container to release resources held by prototype-scoped beans, > try using a custom bean post-processor, which holds a reference to > beans that need to be cleaned up.

ref : https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-prototype

Solution 9 - Java

Also websocket scope is added:

Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

As the per the content of the documentation, there is also thread scope, that is not registered by default.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiongcalex5View Question on Stackoverflow
Solution 1 - JavaJuned AhsanView Answer on Stackoverflow
Solution 2 - JavaDivyesh KanzariyaView Answer on Stackoverflow
Solution 3 - JavaheyxhView Answer on Stackoverflow
Solution 4 - JavaLaurentGView Answer on Stackoverflow
Solution 5 - JavaVikas VView Answer on Stackoverflow
Solution 6 - JavazappeeView Answer on Stackoverflow
Solution 7 - JavaMichu93View Answer on Stackoverflow
Solution 8 - JavaemonView Answer on Stackoverflow
Solution 9 - Javagai-jinView Answer on Stackoverflow