Sub topic 5
Initialization callbacks
This chapter covers the three ways to run your own code after Spring has built a bean and injected its dependencies. It assumes you can write @Component and @Bean classes and run a Spring or Spring Boot application. It also assumes you know the container phases from the previous chapter.
Why initialization callbacks exist
A constructor runs before Spring has set fields or setter-injected properties. With constructor injection, the dependencies are available, but the bean is still only partly built. Some work needs a fully wired bean: opening a connection, loading a cache, or validating configuration.
Initialization callbacks run once per instance, after dependency injection and before the bean is handed to any other bean. If a callback throws, Spring wraps the exception in a BeanCreationException and the context fails to start. A broken bean therefore stops the application at startup instead of failing later.
The three mechanisms
Spring offers three ways to register an init callback.
| Mechanism | Declared on | Couples code to Spring? | Typical use |
|---|---|---|---|
| `@PostConstruct` | Method in the bean class | No, it is a Jakarta standard | Default choice for your own classes |
| `InitializingBean.afterPropertiesSet()` | Bean class implements an interface | Yes | Framework-style code |
| `initMethod` on `@Bean` (or `init-method` in XML) | Configuration, not the class | No | Third-party classes you cannot edit |
@PostConstruct
Put @PostConstruct on a method of your bean. The method must take no arguments. It can have any visibility, and Spring ignores any return value. In Spring 6 and Spring Boot 3 the annotation lives in jakarta.annotation. Older versions use javax.annotation.
@PostConstruct is not processed by the core container itself. A built-in BeanPostProcessor, CommonAnnotationBeanPostProcessor, finds the annotated method and calls it. It is registered automatically by AnnotationConfigApplicationContext and by Spring Boot.
InitializingBean
InitializingBean declares one method, afterPropertiesSet() throws Exception. The name describes when it runs: after all properties have been set. The interface ties your class to Spring, so most projects prefer @PostConstruct for their own code.
initMethod
@Bean(initMethod = "open") names a no-argument method on the returned object. Spring calls it by reflection. The class needs no annotations and no Spring imports, which is why this suits library classes.
Seeing the order
This program registers one bean with all three mechanisms at once.
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class InitConfig {
@Bean(initMethod = "customInit")
Warmup warmup() {
return new Warmup();
}
}
class Warmup implements InitializingBean {
Warmup() {
System.out.println("constructor");
}
@PostConstruct
void postConstruct() {
System.out.println("@PostConstruct");
}
@Override
public void afterPropertiesSet() {
System.out.println("afterPropertiesSet");
}
void customInit() {
System.out.println("customInit");
}
}
public class InitDemo {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(InitConfig.class)) {
System.out.println("context ready");
}
}
}The output is:
constructor
@PostConstruct
afterPropertiesSet
customInit
context readyThe order is fixed: @PostConstruct, then afterPropertiesSet, then the custom init method. "context ready" prints last because singleton beans are created eagerly while the context starts.
Where init callbacks sit in the lifecycle
A BeanPostProcessor wraps the whole group of init callbacks. Its postProcessBeforeInitialization hook runs before them, and postProcessAfterInitialization runs after them. Because @PostConstruct is itself implemented as a BeanPostProcessor, it runs inside the "before initialization" step.
This placement matters for the next section. The postProcessAfterInitialization step is where Spring usually swaps a bean for a proxy.
What is and is not ready inside a callback
Inside an init callback you can rely on these things:
- Constructor arguments,
@Autowiredfields and setters are all populated. @Valueproperties are resolved.- Aware callbacks such as
BeanNameAwarehave already run.
You cannot rely on the following:
- Proxy behavior. The callback runs on the raw object, before
postProcessAfterInitializationwraps it. If an init method calls a method marked@Transactional,@Asyncor@Cacheableonthis, the advice does not apply. No proxy exists yet. - Other beans being fully initialized. Spring creates a dependency fully before injecting it, so ordinary dependencies are ready. In a circular reference, however, one side can receive a partly initialized bean.
- A running application. Web servers may not be listening, and other singletons may not exist yet.
Exceptions and failure behavior
afterPropertiesSet declares throws Exception. @PostConstruct and custom init methods may also throw. Any exception aborts creation of that bean. Spring then destroys the singletons it has already created and throws from the context constructor or refresh().
This is useful for fail-fast validation:
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
class ApiClient {
@Value("${api.url:}")
private String url;
@PostConstruct
void validate() {
if (url.isBlank()) {
throw new IllegalStateException("api.url must be set");
}
}
}If api.url is missing, the application stops at startup with a BeanCreationException whose cause names the missing property. That is usually better than a NullPointerException on the first request.
Scope and laziness effects
Init callbacks run every time Spring creates an instance:
- Singleton beans run them once, normally during context startup.
@Lazysingletons run them on first use, so a bad configuration surfaces late.- Prototype beans run them on every request for a new instance. The later chapters on scopes build on this.
Choosing between them
For your own classes, use @PostConstruct. It is standard, readable, and needs no interface. Use initMethod when you cannot or should not edit the class, such as a library pool or client. Use InitializingBean only when you are writing framework-level code that must work without annotation processing.
Keep init callbacks short. They run on the startup thread, and a slow callback delays the whole application. Slow warm-up work belongs after startup, in an event listener or a lifecycle bean.
Common errors
- Annotation not firing. With the
javax.annotationimport on Spring 6, nothing happens and no error appears. Usejakarta.annotation.PostConstruct. - Annotation not firing outside Spring management. An object created with
new, not registered as a bean, never gets callbacks. - Method has parameters. A
@PostConstructmethod with arguments causes anIllegalStateExceptionat startup. - Misspelled
initMethod. Spring reports that it could not find the method, and the context fails to start. - Relying on proxies. See the warning above.
Exercise
A bean has a constructor, a @PostConstruct method, an afterPropertiesSet method and an initMethod named setup. A BeanPostProcessor logs "before" and "after" for this bean. In what order do the six events appear, and why can't a @Transactional method called from @PostConstruct on this bean start a transaction?
Show answer
The order is constructor, "before", @PostConstruct, afterPropertiesSet, setup, "after". @PostConstruct runs inside the "before initialization" phase, because CommonAnnotationBeanPostProcessor invokes it. The transactional proxy is applied in the "after initialization" phase, so during @PostConstruct the bean is still the raw object and the transaction advice is not applied.