I will explain this step by step :
Scopes of a Spring Bean :
Scope |
Description |
Singleton |
Single instance of a bean is created per container (by default). |
Prototype |
New instance is created each time bean is requested. |
Request |
New instance of a bean is created per each HTTP request. |
Session |
New instance of a bean per each HTTP session. |
Application |
Single instance of a bean is created per each ServletContext. |
WebSocket |
Single instance of a bean per each WebSocket. |
Example with a sample code :
I have created five beans to demonstrate all the scope's use - cases :
SingletonBean :
@Component
public class SingletonBean {
}
PrototypeBean :
@Component
@Scope("prototype")
public class PrototypeBean {
}
RequestBean :
@Component
@RequestScope
public class RequestBean {
}
SessionBean :
@Component
@SessionScope
public class SessionBean {
}
ApplicationBean :
@Component
@ApplicationScope
public class ApplicationBean {
}
Now, I have created one controller to show all the behaviors of the scopes :
@RestController
@Scope("prototype")
public class Resource {
@Autowired
private SingletonBean singletonBean;
@Autowired
private PrototypeBean protoTypeBean;
@Autowired
private RequestBean requestBean;
@Autowired
private SessionBean sessionBean;
@Autowired
private ApplicationBean applicationBean;
@GetMapping("/testbeans")
public String index() {
return "<pre>" + singletonBean + "\n" + protoTypeBean + "\n" + requestBean + "\n" + sessionBean + "\n"
+ applicationBean + "\n" + "</pre>";
}
}
When you hit the endpoint - http://localhost:8080/dweller/testbeans
, you will get this output :
To check whether new instance of bean with request scope is created or not after, just refresh/send a new request.
Note: In addition to this, a new instance of a bean with prototype scope has also been created, the hashcode/address of the new instance is being shown in the above screenshot.
To check whether or not a new instance of a bean with session scope is created, just open an incognito window, and hit the same url. You will see now that a new instance is created for a bean with session scope.
To create a new instance of a singleton and application scope bean, you have to redeploy the application to see the changes.
I think this explanation is enough to get started with any project as I have explained the basics with a running code. I would recommend to start with a demo project (bank or ticket project that you have mentioned) by implementing all the scopes.
I'm adding a link to a real time internet banking system sequence diagram to implement the flow. Just understand the use-cases and try to see where you can add scopes.