Spring Framework
Spring Bean Lifecycle, Scopes and Advanced Configuration
Intermediate8 min readUpdated
Knowing when the container creates, initialises and destroys a bean explains most 'why is this null' and 'why is this run twice' problems. This guide walks the lifecycle phase by phase, compares singleton, prototype and web scopes and their proxies, and covers the configuration machinery — @Import, @Profile, @Value, @PropertySource, @Conditional, @Lazy — that Spring Boot builds its auto-configuration on.
What you will learn
- Trace a bean from definition to destruction and place each callback in the right phase
- Choose the correct scope and know when a scoped proxy is required
- Inject a prototype into a singleton without freezing a single instance
- Split configuration with @Import, @Profile and @PropertySource and read values with @Value and Environment
- Write a BeanPostProcessor and explain how Spring uses the same hook for proxies
Dependency injection tells you what a bean receives. The lifecycle tells you when, and the scope tells you how many. Most confusing Spring behaviour — an injected field that is null inside a constructor, an init method that runs twice, a request-scoped bean that fails at startup, a prototype that never changes — is a lifecycle or scope question in disguise. This guide targets Spring Framework 6.x and assumes you already know how to declare beans with Java configuration.
The lifecycle, phase by phase
A bean's life is split cleanly into container-level phases and instance-level phases.
Definition phase
When an ApplicationContext refreshes, it first collects bean definitions — metadata objects holding the class, scope, constructor arguments, property values, init and destroy method names and lazy flag. Nothing has been instantiated yet. BeanFactoryPostProcessor implementations run now and may add, remove or modify definitions. The property placeholder mechanism that resolves ${db.url} in configuration is one of these; Spring Boot's auto-configuration import selectors are another.
Instantiation and population
For each non-lazy singleton, in an order that respects dependencies, the container then:
- Instantiates the object by calling the chosen constructor, resolving each constructor argument first. If the constructor of
AneedsB,Bis fully created beforeA's constructor runs. - Populates setter and field injection points (
@Autowired,@Value,@Resource). - Calls Aware interfaces if implemented:
BeanNameAware.setBeanName,BeanFactoryAware,ApplicationContextAware,EnvironmentAware,ResourceLoaderAware. These hand the bean container internals; they are useful in framework code and a smell in business code.
Initialisation
- Every registered
BeanPostProcessorgetspostProcessBeforeInitialization(bean, name). The processor that handles@PostConstructlives here. @PostConstructmethods run, thenInitializingBean.afterPropertiesSet(), then the method named in@Bean(initMethod = "…").- Every
BeanPostProcessorgetspostProcessAfterInitialization(bean, name). This is where AOP auto-proxying happens: the processor may return a different object — a proxy — and it is that proxy, not your instance, that goes into the singleton registry and gets injected elsewhere.
The bean is now in use. SmartLifecycle beans additionally receive start() once the whole context is refreshed, which is the correct hook for "start consuming messages" logic that needs every other bean to be ready.
Destruction
When close() is called on the context (or the JVM shutdown hook registered by registerShutdownHook() fires), singletons are destroyed in reverse dependency order: @PreDestroy, then DisposableBean.destroy(), then the @Bean(destroyMethod) method. For @Bean methods, Spring infers a destroy method named close or shutdown automatically, so a HikariDataSource bean is closed without any configuration.
@Component
public class IndexWarmer implements SmartLifecycle {
private final SearchIndex index;
private volatile boolean running;
public IndexWarmer(SearchIndex index) { this.index = index; }
@PostConstruct
void checkConfig() { // injection is complete; safe to use `index`
index.validate();
}
@Override public void start() { index.warm(); running = true; } // whole context is ready
@Override public void stop() { running = false; }
@Override public boolean isRunning() { return running; }
@PreDestroy
void release() { index.close(); }
}
The one rule that resolves most lifecycle bugs: injected fields are not available in the constructor when you use field or setter injection. They are available in @PostConstruct. With constructor injection the question disappears, which is one more argument for it.
Scopes
A scope defines how many instances of a bean definition exist and how long each lives.
| Scope | Instances | Lifetime | Available in |
|---|---|---|---|
singleton (default) | One per container | Whole context | Everywhere |
prototype | One per injection or getBean | Until unreferenced; no destroy callback | Everywhere |
request | One per HTTP request | The request | Web contexts |
session | One per HTTP session | The session | Web contexts |
application | One per ServletContext | The web app | Web contexts |
websocket | One per WebSocket session | The session | WebSocket apps |
Singleton here means one per container, not one per JVM: two contexts hold two instances, and a class can be registered twice under different names. Because singletons are shared across threads, they must be stateless or thread-safe. Keeping per-request data in a singleton field is a classic and serious bug.
Prototype scope and the singleton trap
Declaring @Scope("prototype") makes the container create a new instance every time the bean is requested. The trap is that a singleton requests it exactly once — at its own creation — and then keeps that one instance forever. Three ways out:
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ReportBuilder { /* holds per-report mutable state */ }
@Service
public class ReportService {
private final ObjectProvider<ReportBuilder> builders;
public ReportService(ObjectProvider<ReportBuilder> builders) { this.builders = builders; }
public Report build(Query q) {
ReportBuilder builder = builders.getObject(); // new instance each call
return builder.with(q).build();
}
}
ObjectProvider is the cleanest. @Lookup on an abstract method makes Spring generate a subclass that returns a fresh bean from the method. A scoped proxy (below) works too but is designed for the web scopes.
Web scopes and scoped proxies
A request-scoped bean cannot be injected directly into a singleton: at startup there is no request, so there is nothing to inject, and the container fails with a message about no thread-bound request. The fix is to inject a proxy that resolves the real request-scoped object on every method call:
@Component
@RequestScope // shorthand for @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestAudit {
private final List<String> events = new ArrayList<>();
public void record(String e) { events.add(e); }
public List<String> events() { return events; }
}
@Service
public class CheckoutService {
private final RequestAudit audit; // actually a CGLIB proxy
public CheckoutService(RequestAudit audit) { this.audit = audit; }
public void checkout() { audit.record("checkout"); }
}
@RequestScope, @SessionScope and @ApplicationScope set the proxy mode for you. The proxy is a subclass of the target (TARGET_CLASS) or an interface implementation (INTERFACES); either way the class must be proxyable — not final, with an accessible constructor. Session-scoped beans should be Serializable if sessions can be persisted or replicated.
Configuration features that shape the context
Splitting and importing
Real applications spread configuration across classes by concern: DataConfig, WebConfig, SecurityConfig. Tie them together with @Import, which is explicit and works outside scanned packages:
@Configuration
@Import({DataConfig.class, MessagingConfig.class})
public class AppConfig { }
@Import also accepts an ImportSelector — a class that decides at runtime which configurations to import — which is the mechanism behind every @Enable… annotation and Spring Boot's auto-configuration.
@Configuration(proxyBeanMethods = false) switches off the CGLIB subclassing described in the DI guide. Inter-@Bean method calls then create new objects rather than returning the managed one, so you must pass dependencies as parameters. Spring Boot's own auto-configurations use this "lite" mode for faster startup and it is a reasonable default for your own code once you have adopted the parameter style.
Profiles
A profile is a named slice of configuration activated per environment. Any @Component, @Configuration or @Bean can carry @Profile:
@Configuration
public class DataConfig {
@Bean
@Profile("local")
DataSource embeddedDataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
}
@Bean
@Profile("!local") // expressions: !, &, |
DataSource pooledDataSource(Environment env) {
var ds = new HikariDataSource();
ds.setJdbcUrl(env.getRequiredProperty("db.url"));
return ds;
}
}
Activate profiles with the spring.profiles.active system property or environment variable, or programmatically with context.getEnvironment().setActiveProfiles("local") before refresh. When no profile is active, beans in the default profile are registered. Profiles are for environments; do not use them to toggle features — a property and @Conditional are the right tool for that.
Properties, Environment and @Value
The Environment abstraction unifies property sources — system properties, environment variables, property files, and anything you add — into one search order. @PropertySource adds a file:
@Configuration
@PropertySource("classpath:app.properties")
public class AppConfig {
@Bean
Mailer mailer(@Value("${mail.host}") String host,
@Value("${mail.port:587}") int port, // default after the colon
@Value("#{systemProperties['user.name']}") String user) { // SpEL
return new SmtpMailer(host, port, user);
}
}
@Value handles simple values with type conversion. For structured configuration — a group of related settings with validation — Spring Boot's @ConfigurationProperties is far better; in plain Framework code, inject Environment and read a prefix, or bind manually. Never hard-code secrets in property files that are committed; read them from the environment.
Conditions and laziness
@Conditional(SomeCondition.class) registers a bean only when the condition's matches method returns true. Writing conditions directly is rare in application code, but understanding them demystifies Boot's @ConditionalOnMissingBean — it is the same hook with a pre-written condition.
@Lazy defers a singleton's creation until first use. It is legitimate for a heavyweight bean that most requests never touch, and as a way to break a stubborn circular reference by injecting a lazy proxy. It is not a performance strategy: it moves the startup cost onto the first unlucky request and hides configuration errors until then.
@DependsOn("flywayMigration") forces creation order where there is no injection relationship — the canonical case is "run schema migration before the entity manager factory initialises".
Extending the container
A BeanPostProcessor sees every bean after instantiation and can wrap or modify it. Spring's own @Transactional, @Cacheable, @Async and AOP support are all post-processors that return a proxy from postProcessAfterInitialization. A small one of your own makes the mechanism concrete:
@Component
public class TimingPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (!bean.getClass().isAnnotationPresent(Timed.class)) {
return bean; // leave everything else untouched
}
var factory = new ProxyFactory(bean); // spring-aop
factory.addAdvice((MethodInterceptor) invocation -> {
long start = System.nanoTime();
try {
return invocation.proceed();
} finally {
System.out.printf("%s took %d µs%n", invocation.getMethod().getName(),
(System.nanoTime() - start) / 1_000);
}
});
return factory.getProxy();
}
}
Two consequences follow for anyone using proxies: the object injected into other beans is the proxy, so bean.getClass() reports a generated class, and calls a bean makes to its own methods bypass the proxy entirely. Both are covered in depth in the AOP guide.
A FactoryBean<T> is the other classic extension point: a bean whose job is to produce another bean of type T, used when construction is too complex for a @Bean method — LocalContainerEntityManagerFactoryBean and Spring Data's repository factories are examples. Asking the container for the bean name returns the product; prefixing the name with & returns the factory itself.
Common mistakes
Using an injected field in the constructor. With field injection the field is still null there. Move the logic to @PostConstruct or, better, switch to constructor injection.
Stateful singletons. A @Service with a private List<Order> current field is shared by every request thread. Keep state in method scope, in a request-scoped bean, or in an explicit, thread-safe structure.
Injecting a request-scoped bean without a proxy. Startup fails because no request exists. Use @RequestScope or set proxyMode.
Expecting destroy callbacks on prototypes. They never fire. Close resources yourself.
Registering a BeanPostProcessor that depends on ordinary beans. Post-processors are created before everything else, so the beans they pull in are instantiated early and miss other post-processors — Spring logs "is not eligible for getting processed by all BeanPostProcessors" when this happens. Keep post-processors dependency-free or use ObjectProvider inside them.
Placing @Profile on a method inside a lite configuration and forgetting the alternative. If every candidate for a type is profile-guarded and no profile matches, injection fails at startup. Always have an unconditional or !profile default, or make the dependency optional.
Key takeaways
- A bean passes through definition, instantiation, population, Aware callbacks, post-processor hooks, initialisation callbacks and finally destruction;
@PostConstructruns after injection, never before. postProcessAfterInitializationmay replace a bean with a proxy — that is how transactions, caching and AOP attach themselves.- Singleton is one instance per container shared across threads; prototype is one per request to the container with no destroy callback; web scopes need a scoped proxy to be injected into singletons.
- Inject
ObjectProvider<T>when a singleton needs a fresh prototype per call. @Importcomposes configuration,@Profileselects per environment,@PropertySourceand@Valueread settings,@Conditionalis the general switch that Spring Boot's auto-configuration is built on.@Lazyand@DependsOnare targeted fixes, not defaults; fail-fast startup is a feature.
Sources and further reading
Frequently asked questions
- Which runs first, @PostConstruct or afterPropertiesSet?
- @PostConstruct, then InitializingBean.afterPropertiesSet, then the @Bean(initMethod) or XML init-method. All three run after dependency injection is complete and before the bean is handed to other beans, so any of them can safely use injected fields. Use @PostConstruct unless you have a reason to couple the class to Spring interfaces.
- Why is my prototype bean always the same instance?
- Because it was injected once into a singleton, and singletons are created once. The container has no chance to create a new prototype on each call. Inject ObjectProvider<T> and call getObject() when you need a fresh instance, or declare the prototype with a scoped proxy so that each method call goes through a proxy that resolves a new target.
- Does Spring call @PreDestroy on prototype beans?
- No. The container creates a prototype, injects it, runs its initialisation callbacks and then forgets about it; it never tracks the instance, so it cannot destroy it. If a prototype holds resources, the client that obtained it is responsible for releasing them, or you register it with a custom bean post-processor that tracks instances.
- What is the difference between @Profile and @Conditional?
- @Profile is a specific, built-in condition: the bean is registered only when one of the named profiles is active in the Environment. @Conditional is the general mechanism — you supply a Condition class that inspects anything (a property, a class on the classpath, an existing bean) and Spring Boot's @ConditionalOnMissingBean, @ConditionalOnProperty and friends are all built on it.