Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 942
zkn Avatar asked Dec 08 '15 11:12

zkn


People also ask

What does @PostConstruct do in Java?

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection.

In what order do the @PostConstruct annotated method the Init-method parameter method on beans and the afterPropertiesSet () method execute?

If you have a @PostConstruct method, this will be called first before the initializing methods are called. If your bean implements InitializingBean and overrides afterPropertiesSet , first @PostConstruct is called, then the afterPropertiesSet and then init-method .

What is @PostConstruct annotation in Spring boot?

When we annotate a method in Spring Bean with @PostConstruct annotation, it gets executed after the spring bean is initialized. We can have only one method annotated with @PostConstruct annotation. This annotation is part of Common Annotations API and it's part of JDK module javax.


1 Answers

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
    }
}
like image 188
Braj Avatar answered Nov 09 '22 01:11

Braj