You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot父项目启动报错:缺少javax.cache.CacheManager Bean

问题原因解析

你遇到的报错本质是父项目的Spring上下文加载了子项目的配置类,但缺少配置类依赖的CacheManager Bean,具体原因如下:

  1. 父项目的ParentImpl上添加了@ComponentScan("com.service2.child"),这会让Spring递归扫描子项目包下所有带@Component、@Configuration的类,包括子项目的Child和ChildCacheConfig。
  2. 子项目的ChildCacheConfig是一个@Configuration类,它的构造函数依赖javax.cache.CacheManager,但父项目启动时,Spring Boot的自动缓存配置没有生成这个Bean——要么是子项目依赖引入方式不对,要么是自动配置的触发条件没满足。
  3. 虽然子项目引入了ehcache实现,但如果没有Spring Boot缓存starter的支持,自动配置逻辑不会触发,也就不会自动注册CacheManager Bean。
解决方案

方案1:移除父项目的@ComponentScan,改用更合理的Bean导入方式

不要在父项目的@Component类上直接扫描子项目包,这样会把所有子项目的配置都拉进父项目上下文,容易引发依赖冲突。推荐:

  • 子项目的Child类如果是需要被父项目引用的Bean,确保它被@Component或@Configuration标记(你已经做到了)。
  • 父项目通过@Import(Child.class)直接导入需要的Bean,或者让子项目成为Spring Boot自动配置模块(在子项目的src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件中添加com.service2.child.Child和com.service2.child.ChildCacheConfig,这样父项目依赖子项目后会自动加载这些配置)。

修改后的父项目ParentImpl:

package com.service1.parent;
import com.service2.child.Child;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

@Component
@Import(Child.class)  // 只导入需要的Bean,而非扫描整个包
public class ParentImpl {
  private final Child child;
  
  public ParentImpl(Child child) {
    this.child = child;
  }
}

方案2:修正子项目的依赖,让Spring Boot自动生成CacheManager Bean

子项目直接引入cache-api和ehcache的方式,无法触发Spring Boot的自动缓存配置。应该改用spring-boot-starter-cache,它会自动处理缓存API和实现的整合:
修改子项目的build.gradle:

dependencies {
  api 'org.springframework.retry:spring-retry:1.3.3'
  api 'org.springframework.boot:spring-boot-starter-cache'  // 替换单独的cache-api
  api 'org.ehcache:ehcache:3.9.9'
  ...
}

引入starter后,Spring Boot会自动检测到ehcache实现,生成对应的CacheManager Bean,ChildCacheConfig的依赖就能被满足。

方案3:简化或修正子项目的缓存配置类

如果你的ChildCacheConfig没有自定义逻辑,其实可以直接删除它——@EnableCaching已经在Child类上标注了,加上starter依赖后,自动配置会完成所有缓存初始化工作。

如果确实需要自定义缓存配置,建议手动创建CacheManager Bean,避免依赖未自动生成的Bean:

package com.service2.child;

import javax.cache.CacheManager;
import javax.cache.Caching;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class ChildCacheConfig {
    @Bean
    public CacheManager cacheManager() {
        // 手动初始化Ehcache的CacheManager
        return Caching.getCachingProvider().getCacheManager();
    }
}

内容的提问来源于stack exchange,提问作者user13904118

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 23:23:37