- Singleton – One instance per Application Context (default)
- Prototype – One instance every time getBean method is invoked on the ApplicationContext.
- request – One instance per HttpRequest (in web applications).
- session – One instance per HttpSession (in web applications).
How to add that ?
Add the below code at the top of a bean
@Scope(“prototype”)
@Component @Scope("prototype") public class PersonDAO{ //.. }
On executing below code from the main class:
ApplicationContext context=SpringApplication.run(SpringIn5StepsApplication.class, args); PersonDAO obj=context.getBean(PersonDAO.class); PersonDAO obj2=context.getBean(PersonDAO.class); System.out.println(">>>" + obj); System.out.println(">>>" + obj2);
Result: You will get different instance (hash code is different) of the same bean, since the scope is prototype.
>>>com.heapsteep.PersonDAO@1c56f7ca >>>com.heapsteep.PersonDAO@68a42556
what if the parent class had different scope than the nested class ?
The logic is:
If the parent class has broad scope in compare to the nested class then the scope of the created objects will remain as it is. But when it is the reverse, obviously the parent’s scope will be considered.
If the parent class is prototype and nested class is singleton: the parent object will be prototype and nested object will be singleton.
If the parent class is singleton and nested class is prototype: the parent object will be singleton and nested object will be singleton.
If you want to override the above and want that prototype should behave in a prototype way, you can declare the same nested class as proxy like below:
@Scope(value = “prototype”, proxyMode= ScopedProxyMode.TARGET_CLASS)
Below are a sample code where PersonaDAO is a parent class and MyJdbcConnection is a nested class. Just play around by running in your eclipse.
@Component @Scope("prototype") public class PersonDAO { @Autowired MyJdbcConnection myJdbcConnection; public MyJdbcConnection getMyJdbcConnection() { return myJdbcConnection; } public void setMyJdbcConnection(MyJdbcConnection myJdbcConnection) { this.myJdbcConnection = myJdbcConnection; } }
@Component public class MyJdbcConnection { public void myConnection() { System.out.println("inside myConnection()"); } }
@SpringBootApplication public class SpringIn5StepsApplication { public static void main(String[] args) { ApplicationContext context=SpringApplication.run(SpringIn5StepsApplication.class, args); PersonDAO obj=context.getBean(PersonDAO.class); PersonDAO obj2=context.getBean(PersonDAO.class); System.out.println(">>>>" + obj); System.out.println(">>>>" + obj2); System.out.println(">>>>" + obj.getMyJdbcConnection()); System.out.println(">>>>" + obj2.getMyJdbcConnection()); } }
Diff between Spring singleton and GOF singleton ?
This is a favourite question of interviewer, and below is the answer:
Spring singleton is single object inside an ApplicationContext.
GOF singleton is single object inside an JVM.