Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the expected behaviour of @PostConstruct in @Configuration classes?

Tags:

java

spring

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.

like image 541
Bozho Avatar asked Jul 03 '14 07:07

Bozho


People also ask

What is the @PostConstruct annotation used for?

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.

What does @PostConstruct do 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.

How many times a @PostConstruct method is called?

2. @PostConstruct. Spring calls the methods annotated with @PostConstruct only once, just after the initialization of bean properties.

What is @PostConstruct and @PreDestroy?

@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.


1 Answers

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).

like image 154
Bozho Avatar answered Oct 22 '22 01:10

Bozho