java - Spring boot ConditionalOnBean 注解

有spring boot 2.0.2配置

@Configuration
public class ApiConfig {

    @Bean
    @Profile("!tests")
    @ConditionalOnProperty(name = "enabled", havingValue = "true")
    public MyService service() {
        return new MyServiceImpl();
    }

}

...和一些 Controller ,只有在初始化 MyService bean 时才应该创建并添加到应用程序上下文。

@RestController
@ConditionalOnBean(MyService.class)
public class MyController {
   @Autowired
   private MyService service;
}

它工作正常。但偶尔 spring boot 会跳过 MyController 创建。根据日志,MyService 已创建,但在任何其他 bean(包括所有 Controller )之后,最后。

为什么引导不在 @RestController 之前处理 @Configuration bean? 谢谢。

最佳答案

Why boot does not process @Configuration beans prior to @Controller? Thanks.

因为 Spring 不保证这一点。
以及 @ConditionalOnBean 在 this specification 中警告此类问题。 :

The condition can only match the bean definitions that have been processed by the application context so far and, as such, it is strongly recommended to use this condition on auto-configuration classes only. If a candidate bean may be created by another auto-configuration, make sure that the one using this condition runs after.

并且您不在自动配置类中使用注释。您确实在用 @RestController 注释的类中指定了它。

我认为,为了实现您的要求,您应该在通过 EnableAutoConfiguration 条目导入的 @Configuration 类中移动 @RestController bean 声明在 spring.factories 中。

https://stackoverflow.com/questions/50518696/

相关文章:

css - 如何突出显示 ionic 列表中的选定元素

ruby-on-rails - 提交 Rails 的 credentials.yml.enc 文件是

python-3.x - 如何在不更改 css 的情况下共享 pytest-html 的 html

python - 遍历列表,比较值并删除重复项 - Python

python - PyQt5标签切断

python-3.x - 使用 xarray 计算月平均值

c# - 在程序文件下运行 .exe 时出现 System.UnauthorizedAccessEx

regex - 为什么我不能在 clojure 中的 "|"拆分

python - 自定义转换器和 GridSearch - 管道中的 ValueError

python - 如何将 Pyspark Dataframe header 设置为另一行?