0
0
Spring Bootframework~8 mins

@Scope for bean scope in Spring Boot - Performance & Optimization

Choose your learning style9 modes available
Performance: @Scope for bean scope
MEDIUM IMPACT
This affects application startup time and memory usage by controlling bean lifecycle and instantiation frequency.
Managing bean lifecycle to optimize resource usage
Spring Boot
@Component
@Scope("prototype")
public class MyService {
  // new instance created on each injection
}
Prototype scope creates fresh instances only when needed, reducing shared state and memory pressure.
📈 Performance GainReduces memory footprint and avoids stale state, improving runtime stability.
Managing bean lifecycle to optimize resource usage
Spring Boot
@Component
public class MyService {
  // default singleton scope
}

// Injected everywhere, always created once and shared
Using singleton scope for beans that hold state or are expensive to create can cause memory bloat or stale data.
📉 Performance CostIncreases memory usage and can cause thread-safety issues, impacting responsiveness.
Performance Comparison
PatternBean InstantiationMemory UsageThread SafetyVerdict
Singleton scope for stateful beans1 instance at startupHigh if statefulLow, shared instance[X] Bad
Prototype scope for stateful beansNew instance per injectionModerateHigh, isolated instances[OK] Good
Request scope for web beansNew instance per HTTP requestModerateHigh, per request isolation[OK] Good
Lazy singleton for heavy beansInstance created on first useLow at startupHigh[OK] Good
Rendering Pipeline
Bean scopes influence when and how many bean instances are created and managed by Spring's container, affecting memory and CPU usage during app lifecycle.
Application Startup
Runtime Memory Management
Request Handling
⚠️ BottleneckExcessive singleton beans with heavy initialization or improper scope causing memory bloat and thread contention.
Optimization Tips
1Use prototype or request scope for beans with user-specific or stateful data.
2Apply @Lazy to heavy singleton beans to improve startup time.
3Avoid singleton scope for beans that require thread safety or hold request data.
Performance Quiz - 3 Questions
Test your performance knowledge
Which @Scope is best to avoid shared state issues in beans handling user-specific data?
Aapplication
Bsingleton
Cprototype
Dsession
DevTools: Spring Boot Actuator and JVM Monitoring Tools
How to check: Use Actuator endpoints to monitor bean creation counts and JVM tools (like VisualVM) to observe memory usage and thread activity during app runtime.
What to look for: Look for excessive singleton bean memory retention and thread contention patterns indicating scope misuse.