Sub topic 9
The Full Callback Order
This chapter assumes you know basic Spring dependency injection (@Component, @Autowired, @Configuration, @Bean) and have seen the individual callbacks in earlier chapters: @PostConstruct, InitializingBean, @PreDestroy, DisposableBean, the Aware interfaces, and BeanPostProcessor. Here you put them in one sequence, run it, and learn the mistakes that come from getting the order wrong.
Why the order matters
Each callback sees the bean in a different state. A constructor runs before any dependency is injected by field or setter. @PostConstruct runs after injection. A BeanPostProcessor can replace the bean with a proxy after initialization. If you put work in the wrong hook, you get a NullPointerException, a missing proxy, or a resource that closes before something still needs it.
The startup sequence
For a singleton bean, the container runs these steps in order:
- Instantiate the bean by calling its constructor (or a factory method). Constructor arguments are resolved first.
- Populate properties: field and setter injection.
- Call the Aware callbacks:
BeanNameAware.setBeanName, thenBeanClassLoaderAware, thenBeanFactoryAware. For beans in anApplicationContext,ApplicationContextAwareand the other context-level Aware interfaces are called by a built-inBeanPostProcessor, so they run in the next step. - Call
postProcessBeforeInitializationon everyBeanPostProcessor.@PostConstructis itself handled by one of these post processors, so it runs here. - Call
InitializingBean.afterPropertiesSet. - Call the custom init method named by
@Bean(initMethod = "..."). - Call
postProcessAfterInitializationon everyBeanPostProcessor. AOP proxies are usually created in this step.
The bean is now ready and is handed to whoever asked for it.
The shutdown sequence
When the context closes, the container destroys singleton beans. For each one it runs:
@PreDestroymethods.DisposableBean.destroy.- The custom method named by
@Bean(destroyMethod = "...").
Destruction runs in the reverse order of dependency. If A depends on B, then B was created first and A is destroyed first. This lets A still use B in its own destroy callback.
Watching it run
Use the DemoBean and LoggingPostProcessor classes from the code examples, together with Main and AppConfig. Add BeanNameAware to DemoBean to see the Aware step as well:
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
@Component
public class DemoBean implements BeanNameAware, InitializingBean, DisposableBean {
public DemoBean() {
System.out.println("constructor");
}
@Override
public void setBeanName(String name) {
System.out.println("setBeanName: " + name);
}
@PostConstruct
void postConstruct() {
System.out.println("@PostConstruct");
}
@Override
public void afterPropertiesSet() {
System.out.println("afterPropertiesSet");
}
@PreDestroy
void preDestroy() {
System.out.println("@PreDestroy");
}
@Override
public void destroy() {
System.out.println("DisposableBean.destroy");
}
}Running Main with the post processor prints:
constructor
setBeanName: demoBean
before initialization: demoBean
@PostConstruct
afterPropertiesSet
after initialization: demoBean
context running
@PreDestroy
DisposableBean.destroyThe before initialization line from LoggingPostProcessor appears before @PostConstruct. This is the visible proof that @PostConstruct is part of the before-initialization step, so a custom post processor can run before or after it depending on its own ordering (see below).
Post processors and ordering
Several BeanPostProcessor instances can be registered. By default they run in registration order, but the container sorts them like this:
- Those implementing
PriorityOrderedrun first. - Those implementing
Ordered(or annotated with@Order) run next. - All others run last, in registration order.
Spring's own processor for @PostConstruct is CommonAnnotationBeanPostProcessor, and the one for @Autowired is AutowiredAnnotationBeanPostProcessor. Both are PriorityOrdered-level infrastructure, so a plain custom post processor runs after them. That means in your postProcessBeforeInitialization, the @PostConstruct method of the bean has usually not yet been called if your processor is ordered earlier, and has been called if it comes later. Do not rely on this. If you need to act after the bean has fully initialized, use postProcessAfterInitialization.
Another consequence is that the post processor itself is created before ordinary beans. Beans it depends on are also created early, and they are not processed by post processors that have not been registered yet. Spring logs an info message such as "Bean 'x' is not eligible for getting processed by all BeanPostProcessors". Declare BeanPostProcessor factory methods as static in @Configuration classes to avoid pulling in the configuration class too early.
Lifecycle callbacks and proxies
Step 7 is where AOP wraps the bean. Because of this, the object that @PostConstruct runs on is the raw target, not the proxy. Calling a transactional or cached method of your own bean from @PostConstruct therefore runs without the advice, because the call goes to the raw object and not through the proxy. Likewise, the proxy does not exist yet when afterPropertiesSet runs.
If initialization needs the full proxied behavior, wait for a later event such as ContextRefreshedEvent or ApplicationReadyEvent in Spring Boot, or use a SmartLifecycle bean.
What differs by scope
The sequence above is for singletons. Other scopes change it in the following ways.
| Scope | Init callbacks | Destroy callbacks |
|---|---|---|
| singleton | Run once, at startup (unless lazy) | Run when the context closes |
| prototype | Run on every creation | Never called by the container |
| request, session | Run when the scoped instance is created | Run when the scope ends, only if the scope supports it |
For prototype beans the container hands over the instance after the init phase and forgets it. If a prototype holds a resource, the code that obtained it must release the resource itself.
Common errors
- Using an injected field in the constructor. Field and setter injection happen after the constructor, so the field is
null. Move the code to@PostConstruct, or use constructor injection. - Expecting
@PostConstructto run on a plainnewobject. The annotation works only for beans created by the container. - Throwing from init. An exception in any init callback fails the bean, and the context fails to start. Exceptions in destroy callbacks are logged, and shutdown continues with the other beans.
- Using
@PreDestroyon a prototype. It is never called. Implement your own release method. - Forgetting to close the context. In a plain Java program, destroy callbacks run only if you call
close()or use try-with-resources, asMaindoes. Spring Boot registers a shutdown hook for you. - Putting lifecycle annotations on a
@Beanmethod's return class that you do not own. Annotations on third-party classes are not present. UseinitMethodanddestroyMethod. - Doing a blocking, long task in init. Startup waits for it. Move it to a
SmartLifecyclebean or anApplicationRunner.
Same method, several hooks
If the same method name is registered through several mechanisms, for example afterPropertiesSet implemented and also named as initMethod = "afterPropertiesSet", Spring calls it only once. Different methods, though, each run. Avoid stacking all three init mechanisms on one bean. Choose @PostConstruct for your own classes and initMethod for classes you cannot change.
Exercise
A singleton bean prints "constructor", "@PostConstruct", "afterPropertiesSet" and "@PreDestroy" in its callbacks. A BeanPostProcessor prints in both of its methods. In which order do the five lines (constructor, before initialization, @PostConstruct, afterPropertiesSet, after initialization) appear at startup, and which line appears at shutdown?
Show answer
constructor, before initialization, @PostConstruct, afterPropertiesSet, after initialization. At shutdown only "@PreDestroy" appears, because the bean has no other destroy callback and the post processor does not take part in destruction.
Exercise
A bean's @PostConstruct method calls another method on the same bean that is annotated @Transactional. No transaction starts. Give the reason using the callback order.
Show answer
The AOP proxy is created in postProcessAfterInitialization, after @PostConstruct has run. The call in @PostConstruct goes to the raw object, so no transaction advice applies. Move the work to a later event such as ContextRefreshedEvent.