Issue
In my Spring Boot application I'd like to run some code after a bean has been initialized, but before any dependent beans get initialized. (In my particular scenario I want to run some code to set up some MongoDB indexes once the connection pool has started, but before any beans dependent on the pool start.)
I'm familiar with the @PostConstruct
annotation, which is very close to what I'm after except that you have to add it to a method defined within the class itself. I'm also familiar with Spring lifecycle hooks, but this isn't good enough either because I need to hook into the point immediately after one particular bean has been initialized.
What I'm after is basically just what @PostConstruct
does, but lets you add a hook externally to an instance at runtime. Does such a thing exist?
Solution
Have you looked into the BeanPostProcessor
interface?
Basically, you implement this interface, which gives you hooks, among which are: postProcessBeforeInitialization
and postProcessAfterInitialization
. The method signatures are like:
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// DO SOMETHING HERE WITH THE BEAN before initialization
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
//DO SOMETHING HERE WITH THE BEAN after INITIALIZATION
return bean;
}
So, in a nutshell, your implementation of the BeanPostProcessor
would scan each Spring
bean and then execute the logic in whichever method you want (or both).
I especially love this SO topic and its answers (for more info)
Hope this info helps!
Answered By - Mechkov