Bozho
Bozho

Reputation: 597106

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

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.

Upvotes: 51

Views: 30264

Answers (1)

Bozho
Bozho

Reputation: 597106

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

Upvotes: 43

Related Questions