我有一个用@Configuration和bean注释的类
@Configuration
public class ExampleServiceConfig {
@Bean
@ConditionalOnProperty(value = servicefeature1.enable", havingValue = "true")
public ExampleServices exampleServices() {
return new ExampleServices();
}
然后,我有另一个服务类,它依赖于上面的bean:
@ConditionalOnBean(ExampleServices.class)
public class AnotherService{
@Autowired
public AnotherService(ExampleServices exampleServices){
this.exampleServices = exampleServices
}
}
在春季调试日志中,我看到第一个bean正在创建:
2020-02-28 14:08:51.841 DEBUG 18158 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'exampleServices'
但是没有创建AnotherService():
AnotherService:
Did not match:
- @ConditionalOnBean (types: x.x.x.ReplicationExceptionRepositories; SearchStrategy: all) did not find any beans of type x.x.x.ReplicationExceptionRepositories (OnBeanCondition)
即使成功创建了ExampleService bean,为什么仍未创建AnotherService()?
此外,在创建ExampleService bean之后,我还会看到“不匹配”日志。
我认为添加@DependsOn
可以解决您的问题。这是另一个答案,与您的问题有些相似:https://stackoverflow.com/a/50518946/6908551
@Component
@ConditionalOnBean(ExampleServices.class)
@DependsOn("exampleServices")
public class AnotherService {
@Autowired
public AnotherService(ExampleServices exampleServices) {
this.exampleServices = exampleServices
}
}