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 @Component
s and @Bean
s.
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!
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.
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 .
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With