We are reusing a project that defines its beans with spring java-config (using @Configuration), and in one such class it has a @PostConstruct
init method.
What is the expected behaviour here - when is this method invoked? In regard to beans, that is. I.e. does this method behave exactly as if the configuration class is a bean (and is it actually one?)
What we observe is that, depending on the operating system, it can be invoked before the beans that are @Autowired
into the configuration class are initialized, and thus it ends up working with incomplete dependencies.
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.
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.
2. @PostConstruct. Spring calls the methods annotated with @PostConstruct only once, just after the initialization of bean properties.
@PostConstruct : is called after the bean has been initialized and before this bean is returned to the requested object. @PreDestroy : is called just before the bean is removed from the container.
Even for @Configuration
, @PostConstruct
behaves as expected - it gets invoked after the dependencies of the class are injected. Although this is a bit confusing (together with the fact that @Configuration
classes are beans), it is correct.
The problem at hand was a hidden circular dependency introduced with the help of spring-security-oauth - it's a convoluted set of configurations that is beyond the scope of this discussion.
So, @PostConstruct
can be invoked if the dependent beans are not fully initialized only in case of circular dependencies. If dependencies are supplied via setter or field injection the circular dependency is not reported, and instead incomplete beans are used.
Also something to note here is that it seems the circular dependency handling depends on the OS (which means some JVM or JRE differences).
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