即使属性存在,Spring Boot也不会因为 @ConditionalOnProperty而创建一个bean

后端开发 2026-07-09

我正在使用Java 17的 Spring Boot 3应用。该应用可以通过来自 application.properties 的属性来切换树算法策略。

我的 application.properties 文件包含:

app.storage=memory
app.tree-strategy=custom
server.port=8080

这是我的配置类:

@Configuration
public class TreeStrategyConfig {

    @Bean
    @ConditionalOnProperty(name = "app.tree-strategy", havingValue = "custom", matchIfMissing = true)
    public TreeAlgorithmStrategy customTreeStrategy() {
        return new CustomTreeImpl();
    }

    @Bean
    @ConditionalOnProperty(name = "app.tree-strategy", havingValue = "collections")
    public TreeAlgorithmStrategy collectionsTreeStrategy() {
        return new CollectionsTreeStrategy();
    }
}

而这个服务依赖于TreeAlgorithmStrategy:

@Service
public class CategoryTreeService {

    private final TreeAlgorithmStrategy strategy;

    public CategoryTreeService(TreeAlgorithmStrategy strategy) {
        this.strategy = strategy;
    }
}

启动应用程序时,我得到如下信息:

CategoryTreeService构造函数的第1 个参数需要一个类型为 'org.tree.engine.model.TreeAlgorithmStrategy' 的bean, 但未能找到

application.properties文件位于src/main/resources。

可能是什么原因导致 @ConditionalOnProperty在属性看起来已正确定义时仍然不创建任何bean?

解决方案

我认为原因可能是该类被放在 @SpringBootApplication之外,导致扫描失败。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章