有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/