1

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?

Robert Johnson
  • 632
  • 6
  • 25
  • `@Bean(initMethod=)` or a `BeanPostProcessor` – OrangeDog Feb 14 '17 at 13:43
  • If the amount of dependent beans is within certain boundaries, you could use the @DependsOn annotation which will guarantee that the passed bean is constructed before the dependents. I'm not sure how to hook the initializing listener. You could register a BeanPostProcessor and execute your logic when the bean is of the proper type, but when you want to create the indexes with MongoTemplate then this is impossible at that time. – Nico Van Belle Feb 14 '17 at 15:08

1 Answers1

3

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!

Community
  • 1
  • 1
Mechkov
  • 4,294
  • 1
  • 17
  • 25