Java @Configuration 类中 @PostConstruct 的预期行为是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24548004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:52:07  来源:igfitidea点击:

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

javaspring

提问by Bozho

We are reusing a project that defines its beans with spring java-config (using @Configuration), and in one such class it has a @PostConstructinit method.

我们正在重用一个使用 spring java-config(使用@Configuration)定义其 bean 的项目,并且在一个这样的类中它有一个@PostConstructinit 方法。

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

这里的预期行为是什么 - 何时调用此方法?关于豆类,就是这样。即这个方法的行为与配置类是一个 bean 完全一样(它实际上是一个 bean 吗?)

What we observe is that, depending on the operating system, it can be invoked before the beans that are @Autowiredinto the configuration class are initialized, and thus it ends up working with incomplete dependencies.

我们观察到的是,根据操作系统的不同,它可以在@Autowired进入配置类的 bean被初始化之前被调用,因此它最终会处理不完整的依赖项。

采纳答案by Bozho

Even for @Configuration, @PostConstructbehaves as expected - it gets invoked after the dependencies of the class are injected. Although this is a bit confusing (together with the fact that @Configurationclasses are beans), it is correct.

即使 for @Configuration, 也@PostConstruct按预期运行 - 在注入类的依赖项后调用它。虽然这有点令人困惑(连@Configuration同类是 bean的事实),但它是正确的。

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.

手头的问题是在 spring-security-oauth 的帮助下引入的隐藏循环依赖 - 这是一组复杂的配置,超出了本讨论的范围。

So, @PostConstructcan 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.

因此,@PostConstruct只有在循环依赖的情况下才可以在依赖 bean 未完全初始化的情况下调用。如果依赖项是通过 setter 或字段注入提供的,则不会报告循环依赖项,而是使用不完整的 bean。

Also something to note here is that it seems the circular dependency handling depends on the OS (which means some JVM or JRE differences).

这里还需要注意的是,循环依赖处理似乎取决于操作系统(这意味着一些 JVM 或 JRE 差异)。