Spring Boot自动配置中@ConditionalOnBean(DataSource.class)未按预期生效问题求助
Spring Boot自动配置中@ConditionalOnBean(DataSource.class)未按预期生效问题求助
我正在尝试给Togglz的状态仓库做一个极简的自动配置逻辑:当容器中存在DataSource Bean时,使用JDBCStateRepository;如果是跑不含数据库的测试场景或者其他没有DataSource的情况,就保留默认的状态仓库实现。
这是一个搭配了数据库连接和Togglz库的简单Spring Boot应用,我写了如下自动配置类:
@Configuration(proxyBeanMethods = false) @AutoConfigureAfter({DataSourceAutoConfiguration.class}) public class TogglzStateRepositoryAutoConfiguration { @Bean @ConditionalOnBean(DataSource.class) public StateRepository getStateRepository(DataSource dataSource) { return new JDBCStateRepository(dataSource); } }
但现在遇到了问题:这个StateRepository Bean永远不会被创建,Spring总是提示找不到DataSource,自动配置报告里的相关内容如下:
TogglzStateRepositoryAutoConfiguration#getStateRepository:
Did not match:
- @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) did not find any beans of type javax.sql.DataSource (OnBeanCondition)
但就在这份报告的几行之上,明明有另一个自动配置类成功匹配了DataSource:
DataSourceHealthContributorAutoConfiguration matched:
- @ConditionalOnClass found required classes 'org.springframework.jdbc.core.JdbcTemplate', 'org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource' (OnClassCondition)
- @ConditionalOnEnabledHealthIndicator management.health.defaults.enabled is considered true (OnEnabledHealthIndicatorCondition)
- @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) found bean 'dataSource' (OnBeanCondition)
我试过调整配置顺序,比如用@DependsOn、@AutoConfigureAfter、@AutoConfigureBefore这些注解,但都没效果。有没有大佬能指点下我该怎么排查或者解决这个问题?或者帮我看看我哪里考虑漏了?
谢谢!
备注:内容来源于stack exchange,提问作者Emilien
相关产品推荐
相关产品推荐

