NOTE
Bean Scopes
1. Scope categories 2. Why prototype exists 3. References
This is a historical learning note and may contain outdated or incomplete understanding.
1. Scope Categories
- singleton: every time the Bean is obtained from the container, it is the same instance.
- prototype: every time the Bean is obtained from the container, a new one is created.
- request: the same Bean is used within an HTTP request.
- session: the same Bean is used within an HTTP session.
2. Why Is There prototype?
- Modifying properties on a singleton can cause thread-safety problems.
For example:
@Autowired
HttpServletRequest request;
The injected HttpServletRequest here does not have a thread-safety problem because it is prototype-scoped.
2.1. How to Use prototype
- MainController
@RestController
public class MainController
{
@Autowired
MainServices services;
}
- MainServices
@Service
@Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS)// ScopedProxyMode.TARGET_CLASS is required here.
public class MainServices
{
//...
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub