春季启动ConditionalOnBean批注 [英] Spring boot ConditionalOnBean annotation
问题描述
有spring boot 2.0.2配置
There are spring boot 2.0.2 configuration
@Configuration
public class ApiConfig {
@Bean
@Profile("!tests")
@ConditionalOnProperty(name = "enabled", havingValue = "true")
public MyService service() {
return new MyServiceImpl();
}
}
...以及一些仅在MyService bean初始化后才应创建并添加到应用程序上下文中的控制器.
... and some controller which should be created and added to application context only if MyService bean is initialized.
@RestController
@ConditionalOnBean(MyService.class)
public class MyController {
@Autowired
private MyService service;
}
可以.但是偶尔春季引导会跳过MyController的创建.根据日志,创建了MyService,但最后是所有其他bean(包括所有控制器)之后.
It works Ok. But occasionally spring boot skips MyController creating. According to the logs MyService is created, but after any other beans(including all controllers), at the end.
为什么引导在 @RestController
之前不处理 @Configuration
bean?谢谢.
Why boot does not process @Configuration
beans prior to @RestController
?
Thanks.
推荐答案
为什么引导在@Controller之前不处理@Configuration bean?谢谢.
Why boot does not process @Configuration beans prior to @Controller? Thanks.
因为Spring不能保证.
以及 @ConditionalOnBean
在
Because Spring doesn't guarantee that.
As well as @ConditionalOnBean
warns about this kind of issue in this specification :
条件只能匹配已被定义的bean定义到目前为止,已由应用程序上下文处理,因此强烈建议在自动配置中使用此条件仅限类.如果候选bean可能是由另一个bean创建的自动配置,请确保使用此条件的设备运行之后.
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
注释的类中指定了它.
And you don't use the annotation in an auto-configuration class. You indeed specified it in a class annotated with @RestController
.
我认为要实现您的要求,应将 @RestController
bean声明移至通过 EnableAutoConfiguration
条目导入的 @Configuration
类中在 spring.factories
中.
I think that to achieve your requirement you should move the @RestController
bean declaration in a @Configuration
class that's imported via an EnableAutoConfiguration
entry in spring.factories
.
这篇关于春季启动ConditionalOnBean批注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!