What is the proper way to activate @PostConstruct via CommonAnnotationBeanPostProcessor by Java configuration?

zkn picture zkn · Dec 8, 2015 · Viewed 16.8k times · Source

I'm using Spring 4 with SpringBoot and Spring-Web with Java configuration.

To have my @PostConstruct annotated methods executed by Spring at launch, it is necessary to register CommonAnnotationBeanPostProcessor with the context, otherwise @PostConstruct is ignored.

In a XML-based Spring configuration, the docs say to use (under the beans element)

<context:annotation-config/>

I have also seen an example where registration is done on an individual bean basis, like so:

<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />

I wish to avoid this if possible. My project does not include any XML file, and none is generated for me in my build folder.

Currently, my solution is to annotate my class with @ComponentScan, which I believe causes Spring to detect and register @Components and @Beans. Somehow, this causes CommonAnnotationBeanPostProcessor to be invoked, although I have no idea why, but it solves my problem!

(This class has one @Autowired property, which is null at startup - hence the need to do the initialization via @PostConstruct)

But again, my question, what is the proper way to achieve this using Java configuration? Thank you!

Answer

Braj picture Braj · Dec 8, 2015

You can use InitializingBean as an alternate solution.

Simply extend this interface and override afterPropertiesSet method that will be called after setting all the properties of the bean just like post construct.

For example:

@Component
public class MyBean implements InitializingBean 
{
    @Override
    public void afterPropertiesSet()
    {
        // do whatever you want to do here
    }
}