Beans, lifecycle, and scopes
The container creates a bean, injects dependencies, applies processors, calls initialization callbacks, exposes it for use, and invokes destruction callbacks when the context closes.
Lifecycle tools
- Constructor: establish valid required state.
@PostConstruct: initialize after dependencies exist.@PreDestroy: release managed resources.BeanPostProcessor: change or wrap many beans as infrastructure.SmartLifecycle: coordinate start/stop for active components.
Keep constructors fast and avoid remote calls during startup when possible. Startup should fail clearly for invalid configuration but not depend on a temporary network response unless absolutely required.
Scopes
| Scope | Meaning |
|---|---|
| Singleton | One bean instance per application context; default |
| Prototype | New instance each time requested |
| Request | One instance per HTTP request |
| Session | One instance per HTTP session |
| Application | One per servlet application |
A singleton may serve many threads. Mutable fields can create races. Prefer stateless singleton services and keep request data in method variables.
Proxies
Spring may wrap a bean with a proxy to add transactions, security,
caching, or AOP behavior. Calls entering through the proxy receive that
behavior. Self-invocation—one method calling another on
this—can bypass proxy advice.
Feynman check
A proxy is a receptionist standing before the real worker. If the worker calls their own second task internally, the call never passes the receptionist.