I need to understand how bean scopes affect dependency injection in Spring Boot. By default, everything seems to be a singleton, but how do prototype or request scopes behave when injected into a singleton bean during application development?
3 answers
By default, dependency injection in Spring Boot uses the Singleton scope, meaning only one instance is created per application context. If you inject a Prototype bean (which creates a new instance every time it is requested) into a Singleton bean, it will only be injected once during startup. Consequently, the Singleton bean will keep using that same prototype instance forever. To fix this behavior and get a fresh instance every time, you must use a scoped proxy or lookup methods.
Could you explain how a scoped proxy works under the hood to solve this issue? Does it negatively affect performance in heavy software development systems?
For web apps, you also get request and session scopes, which tie the lifecycle of your injected beans directly to individual HTTP requests.
Nicole's point is crucial for user-specific data tracking. Using request scope ensures zero data leakage between different user threads accessing the server simultaneously.
A scoped proxy inserts a smart proxy object instead of the real bean. When methods are called, the proxy fetches the correct short-lived bean from the context. The performance overhead is negligible for almost all enterprise web applications.