How to call a method after bean initialization is complete?


I have a use case where I need to call a (non-static) method in the bean only-once at the ApplicationContext load up. Is it ok, if I use MethodInvokingFactoryBean for this? Or we have a some better solution?

As a side note, I use ConfigContextLoaderListener to load the Application Context in web application. And want, that if bean 'A' is instantiated just call methodA() once.

How can this be done nicely?

3/3/2016 6:14:13 PM

Accepted Answer

You can use something like:

    <bean id="myBean" class="..." init-method="init"/>

This will call the "init" method when the bean is instantiated.

4/12/2013 9:38:01 AM

There are three different approaches to consider, as described in the reference

Use init-method attribute


  • Does not require bean to implement an interface.


  • No immediate indication this method is required after construction to ensure the bean is correctly configured.

Implement InitializingBean


  • No need to specify init-method, or turn on component scanning / annotation processing.
  • Appropriate for beans supplied with a library, where we don't want the application using this library to concern itself with bean lifecycle.


  • More invasive than the init-method approach.

Use JSR-250 @PostConstruct lifecyle annotation


  • Useful when using component scanning to autodetect beans.
  • Makes it clear that a specific method is to be used for initialisation. Intent is closer to the code.


  • Initialisation no longer centrally specified in configuration.
  • You must remember to turn on annotation processing (which can sometimes be forgotten)

Have you tried implementing InitializingBean? It sounds like exactly what you're after.

The downside is that your bean becomes Spring-aware, but in most applications that's not so bad.


You could deploy a custom BeanPostProcessor in your application context to do it. Or if you don't mind implementing a Spring interface in your bean, you could use the InitializingBean interface or the "init-method" directive (same link).


To further clear any confusion about the two approach i.e use of

  1. @PostConstruct and
  2. init-method="init"

From personal experience, I realized that using (1) only works in a servlet container, while (2) works in any environment, even in desktop applications. So, if you would be using Spring in a standalone application, you would have to use (2) to carry out that "call this method after initialization.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]