Sub topic 3
Bean Scopes, Lifecycle, and Wiring Errors
Assume you know Java constructors, interfaces, annotations, and basic Maven or Gradle use. This chapter focuses on how Spring controls bean lifetime and resolves common wiring problems.
Bean scopes
A bean scope defines how long a bean lives and when Spring creates it.
| Scope | Behavior | Typical use |
|---|---|---|
| `singleton` | One instance per `ApplicationContext` | Stateless services and caches |
| `prototype` | A new instance for each container request | Short-lived, stateful objects |
| `request` | One instance per HTTP request | Request-specific data |
| `session` | One instance per HTTP session | User-session state |
singleton is the default. A prototype bean is created when requested, but Spring does not normally call its destruction callback. Web scopes require a web-aware application context.
@Component
@Scope("prototype")
public class ReportBuilder {
}Do not store request or prototype state in a singleton. Injecting a shorter-lived bean directly into a singleton can also be surprising because the dependency may be created only once. Use a scoped proxy or ObjectProvider when the singleton must obtain a fresh instance.
Lifecycle callbacks
Spring creates a bean, injects its dependencies, and then calls initialization callbacks. @PostConstruct is useful for validation or warming a cache. @PreDestroy runs when the context closes, mainly for singleton beans.
@Component
public class PriceCache {
@PostConstruct
void warmUp() {
// Load initial data.
}
@PreDestroy
void flush() {
// Release resources.
}
}Configuration and profiles
Use @Value for a small number of properties. Use @ConfigurationProperties for related, typed settings.
@ConfigurationProperties(prefix = "mail")
public record MailProperties(String host, int port) {}Register it with @EnableConfigurationProperties. Add @Profile("prod") to register a bean only in a selected environment. @Conditional annotations provide more detailed conditions, such as enabling a bean only when a class or property exists.
Wiring errors and testing
A circular dependency occurs when A needs B while B needs A. Constructor injection exposes this error early. Break the cycle by extracting shared behavior or changing the object boundaries.
Missing beans usually mean a component was not scanned or a configuration class was not loaded. Multiple candidates require @Primary for a default or @Qualifier for an explicit choice.
Constructor injection also makes unit tests simple: instantiate the class with a fake dependency. Use a Spring test only when you need container configuration, scopes, or property binding.
Exercise
Why might a prototype bean injected into a singleton fail to provide a new object for every method call?
Show answer
The singleton usually receives one prototype instance during its own creation. Use ObjectProvider or a scoped proxy to request new instances.