Bean scope decides which type of bean instance should be returned to the caller from the Spring container. Scopes are defined using @Scope annotation.
There are six types of bean scopes in the latest version of the Spring framework:
- singleton
- prototype
- request
- session
- application
- WebSocket
The scopes request, session, application, and WebSocket are only available in a web-aware application.
1] Singleton Scope:
Singleton scope means that the container should create a single instance of a bean, and all the requests for that bean will return the same object. When there is no scope defined, the singleton scope is considered as default scope. When any modification is done to the object, it will reflect in all the references of that bean.
Syntax:
<!-- A bean definition with singleton scope --> <bean id = "..." class = "..." scope = "singleton"> </bean>
Example:
Step 1: First create an entity named as Person.
public class Person { private String name; // standard constructor, getters and setters }
Step 2: Define a bean with a singleton scope.
@Bean @Scope("singleton") public Person personSingleton() { return new Person(); }
Step 3: Create a Test.
private static final String NAME = "ABC"; @Test public void givenSingletonScope_whenSetName_thenEqualNames() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml"); Person personSingletonA = (Person) applicationContext.getBean("personSingleton"); Person personSingletonB = (Person) applicationContext.getBean("personSingleton"); personSingletonA.setName(NAME); Assert.assertEquals(NAME, personSingletonB.getName()); ((AbstractApplicationContext) applicationContext).close(); }
Step 4: Scope.xml file
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"> <bean id="personSingleton" class="org.spring.scopes.Person" scope="singleton"/> </beans>
2] Prototype Scope:
In prototype scope, a different instance is returned every time it is requested from the container.
Syntax:
<!-- A bean definition with prototype scope --> <bean id = "..." class = "..." scope = "prototype"> </bean>
Example:
Step 1: First create an entity named as Person.
public class Person { private String name; // standard constructor, getters and setters }
Step 2: Define a bean with prototype scope.
@Bean @Scope("prototype") public Person personPrototype() { return new Person(); }
Step 3: Create a Test File.
private static final String NAME = "ABC"; private static final String NAME_OTHER = "XYZ"; @Test public void givenPrototypeScope_whenSetNames_thenDifferentNames() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml"); Person personPrototypeA = (Person) applicationContext.getBean("personPrototype"); Person personPrototypeB = (Person) applicationContext.getBean("personPrototype"); personPrototypeA.setName(NAME); personPrototypeB.setName(NAME_OTHER); Assert.assertEquals(NAME, personPrototypeA.getName()); Assert.assertEquals(NAME_OTHER, personPrototypeB.getName()); ((AbstractApplicationContext) applicationContext).close(); }
Step 4: Scope.xml File
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"> <bean id="personSingleton" class="org.spring.scopes.Person" scope="prototype"/> </beans>
3] Request Scope:
In the request scope, the Spring container creates a new instance for each and every HTTP request. For example, if there are 20 requests then the container will create 20 new instances and the instances are destructed when the request is complete.
Syntax:
<!-- A bean definition with request scope --> <bean id = "..." class = "..." scope = "request"> </bean>
Example:
Step 1: Request Scope can be defined as:
@Bean @RequestScope public HelloMessageGenerator requestScopedBean() { return new HelloMessageGenerator(); }
Step 2: Define a Controller
@Controller public class ScopesController { @Resource(name = "requestScopedBean") HelloMessageGenerator requestScopedBean; @RequestMapping("/scopes/request") public String getRequestScopeMessage(final Model model) { model.addAttribute("previousMessage", requestScopedBean.getMessage()); requestScopedBean.setMessage("Good morning!"); model.addAttribute("currentMessage", requestScopedBean.getMessage()); return "scopesExample"; } }
Step 3: Scope.xml File
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"> <bean id="personSingleton" class="org.spring.scopes.Person" scope="request"/> </beans>
4] Session Scope:
In session scope, the Spring container creates a new instance for each and every HTTP session. For example, if there are 20 sessions then container will create 20 new instances and the instances are destructed when the session ends.
Syntax:
<!-- A bean definition with session scope --> <bean id = "..." class = "..." scope = "session"> </bean>
Example:
Step 1: Session Scope can be defined as:
@Bean @SessionScope public HelloMessageGenerator sessionScopedBean() { return new HelloMessageGenerator(); }
Step 2: Define a Controller
@Controller public class ScopesController { @Resource(name = "sessionScopedBean") HelloMessageGenerator sessionScopedBean; @RequestMapping("/scopes/session") public String getSessionScopeMessage(final Model model) { model.addAttribute("previousMessage", sessionScopedBean.getMessage()); sessionScopedBean.setMessage("Good afternoon!"); model.addAttribute("currentMessage", sessionScopedBean.getMessage()); return "scopesExample"; } }
Step 3: Scope.xml File
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"> <bean id="personSingleton" class="org.spring.scopes.Person" scope="session"/> </beans>
5] Application Scope:
In the application scope, the Spring container creates one instance per web application runtime. There can be multiple application scope instances for a single application.
Syntax:
<!-- A bean definition with application scope --> <bean id = "..." class = "..." scope = "application"> </bean>
Example:
Step 1: Application Scope can be defined as:
@Bean @ApplicationScope public HelloMessageGenerator applicationScopedBean() { return new HelloMessageGenerator(); }
Step 2: Define a Controller
@Controller public class ScopesController { @Resource(name = "applicationScopedBean") HelloMessageGenerator applicationScopedBean; @RequestMapping("/scopes/application") public String getApplicationScopeMessage(final Model model) { model.addAttribute("previousMessage", applicationScopedBean.getMessage()); applicationScopedBean.setMessage("Good afternoon!"); model.addAttribute("currentMessage", applicationScopedBean.getMessage()); return "scopesExample"; } }
Step 3: Scope.xml File
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"> <bean id="personSingleton" class="org.spring.scopes.Person" scope="application"/> </beans>
6] Websocket Scope:
Websocket scope enables a two-way communication between the client and the host.
Syntax:
<!-- A bean definition with WebSocket scope --> <bean id = "..." class = "..." scope = "websocket"> </bean>
WebSocket Scope can be defined as:
@Bean @Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS) public HelloMessageGenerator websocketScopedBean() { return new HelloMessageGenerator(); }
Scope.xml File for Websocket scope looks like:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"> <bean id="personSingleton" class="org.spring.scopes.Person" scope="websocket"/> </beans>