There are five types of spring bean scopes:
- singleton – Default –only one instance of the spring bean will be created for the spring container. This is the default spring bean scope. 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 from the spring container.
- 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 Bean Singleton and Prototype Scope
Spring bean singleton and prototype scopes can be used in standalone spring apps. Let’s see how we can easily configure these scopes using @Scope
annotation.
Let’s say we have a java bean class.
package com.journaldev.spring; public class MyBean { public MyBean() { System.out.println("MyBean instance created"); } }
Let’s define the spring configuration class where we will define the method to get MyBean instance from spring container.
package com.journaldev.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; @Configuration public class MyConfiguration { @Bean @Scope(value="singleton") public MyBean myBean() { return new MyBean(); } }
Note that singleton
is default scope, so we can remove @Scope(value="singleton")
from above bean definition.
Now let’s create a main method and test the singleton scope.
package com.journaldev.spring; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class MySpringApp { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(MyConfiguration.class); ctx.refresh(); MyBean mb1 = ctx.getBean(MyBean.class); System.out.println(mb1.hashCode()); MyBean mb2 = ctx.getBean(MyBean.class); System.out.println(mb2.hashCode()); ctx.close(); } }
When above program is executed, we will get output like below.
MyBean instance created 867988177 867988177
Notice that both MyBean instances have same hashcode and the constructor is called once once, it means that spring container is returning the same instance of MyBean always.
Now let’s change the scope to prototype
.
@Bean @Scope(value="prototype") public MyBean myBean() { return new MyBean(); }
This time we will get following output when main method is executed.
MyBean instance created 867988177 MyBean instance created 443934570
Reference :