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

多模块项目中如何仅配置一份ehcache.xml并实现复用?

当然可行!几种优雅的共享Ehcache配置方案

完全不用在每个Spring Boot项目里重复复制ehcache.xml,把它放在公共的common项目里共享是非常合理的做法,下面给你几个实用的方案:

方案一:直接依赖公共项目+指定配置路径(简单快速)

如果你的common项目已经是各个Spring Boot子项目的Maven/Gradle依赖,那只需要两步就能搞定:

  • 把ehcache.xml放在common项目的src/main/resources目录下(也可以放在子目录,比如src/main/resources/cache/)
  • 在每个子项目的application.yml(或application.properties)里明确指定配置文件的位置:
    spring:
      cache:
        type: ehcache
        ehcache:
          config: classpath:/ehcache.xml # 若放在子目录则写classpath:/cache/ehcache.xml
    

只要common项目被正确引入为依赖,子项目的类路径就会包含common的资源文件,Spring Boot就能顺利找到这个配置。

方案二:封装成自动配置Starter(最优雅的多项目共享方式)

如果你的子项目数量很多,不想每个都手动写配置,那可以把缓存配置做成Spring Boot自动配置,这样子项目只要依赖common项目就能自动启用缓存并加载ehcache.xml:

  1. 在common项目里创建自动配置类:
    @Configuration
    @EnableCaching
    @ConditionalOnClass(EhCacheCacheManager.class)
    @ConditionalOnProperty(prefix = "spring.cache", name = "type", havingValue = "ehcache", matchIfMissing = true)
    @ImportResource(locations = "classpath:/ehcache.xml")
    public class EhcacheAutoConfiguration {
        // 按需添加缓存管理器等额外配置逻辑
    }
    
  2. 在common项目的src/main/resources/META-INF目录下创建spring.factories文件,内容如下:
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.yourpackage.common.EhcacheAutoConfiguration
    
  3. 确保common项目引入了必要的依赖(Maven示例):
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>
    </dependencies>
    

这样一来,每个子项目只要引入common的依赖,就会自动加载ehcache.xml并启用缓存,完全不用在子项目里写任何缓存相关配置,非常适合大规模多项目场景。

注意事项

  • 确保common项目被正确打包为Jar包,且子项目的依赖配置无误(Maven的<dependency>或Gradle的implementation)
  • 如果子项目有自己的缓存配置,会覆盖公共配置,需要注意配置优先级
  • 若使用Ehcache 3,配置文件格式和路径配置方式一致,仅需将依赖替换为org.ehcache:ehcache

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:37:34