@Configuration类中@PostConstruct的预期行为是什么? [英] What is the expected behaviour of @PostConstruct in @Configuration classes?
问题描述
我们正在重用一个使用spring java-config(使用@Configuration)定义其bean的项目,并且在一个这样的类中它有一个 @PostConstruct
init方法。 / p>
此处的预期行为是什么 - 何时调用此方法?关于豆类,就是这样。即这个方法的行为是否与配置类是bean一样(实际上是一个?)
我们观察到的是,根据操作系统的不同,它可以在配置类中的 @Autowired
的bean初始化之前调用,因此它最终使用不完整的依赖项。
即使是 @Configuration
, @ PostConstruct
按预期运行 - 在注入类的依赖项后调用它。虽然这有点令人困惑(连同 @Configuration
类都是bean),这是正确的。
手头的问题是在spring-security-oauth的帮助下引入的一个隐藏的循环依赖 - 它是一个令人费解的配置集,超出了本讨论的范围。
因此,如果依赖bean仅在循环依赖的情况下未完全初始化,则可以调用 @PostConstruct
。如果通过setter或field injection提供依赖关系,则不会报告循环依赖关系,而是使用不完整的bean。
此处需要注意的是,它似乎是循环依赖关系处理取决于操作系统(这意味着一些JVM或JRE差异)。
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.
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).
这篇关于@Configuration类中@PostConstruct的预期行为是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!