Performance: @Scope for bean scope
This affects application startup time and memory usage by controlling bean lifecycle and instantiation frequency.
@Component @Scope("prototype") public class MyService { // new instance created on each injection }
@Component public class MyService { // default singleton scope } // Injected everywhere, always created once and shared
| Pattern | Bean Instantiation | Memory Usage | Thread Safety | Verdict |
|---|---|---|---|---|
| Singleton scope for stateful beans | 1 instance at startup | High if stateful | Low, shared instance | [X] Bad |
| Prototype scope for stateful beans | New instance per injection | Moderate | High, isolated instances | [OK] Good |
| Request scope for web beans | New instance per HTTP request | Moderate | High, per request isolation | [OK] Good |
| Lazy singleton for heavy beans | Instance created on first use | Low at startup | High | [OK] Good |
@Scope("prototype") annotation do in a Spring Boot bean?prototype scope means Spring creates a new bean instance each time it is requested from the container.singleton which shares one instance, prototype always returns a fresh object.@Scope annotation in Spring Boot?@Scope("singleton").prototype creates new instances, session and request are web scopes, not singleton.@Component
@Scope("request")
public class UserRequestBean { }request scope means Spring creates a new bean instance for each HTTP request.@Component
@Scope("session")
public class ShoppingCart { }@Scope annotation and configuration should you use?session scope creates one bean instance per HTTP session, which fits the requirement.proxyMode = ScopedProxyMode.TARGET_CLASS allows safe injection into other beans by creating a proxy that resolves the correct session instance.Pass the test and this pattern moves unknown