1212import org .ehcache .config .builders .CacheManagerBuilder ;
1313import org .ehcache .xml .XmlConfiguration ;
1414
15+ import java .net .URL ;
1516import java .util .ArrayList ;
1617import java .util .List ;
1718
1819public class SingletonCacheImpl implements SingletonCache {
1920
21+ private static final String EHCACHE_CONFIG_RESOURCE = "ehcache3.xml" ;
22+
2023 private boolean cacheEnable ;
2124
2225 private CacheManager manager ;
@@ -26,12 +29,30 @@ public class SingletonCacheImpl implements SingletonCache{
2629 public SingletonCacheImpl (boolean enable ){
2730 this .cacheEnable = enable ;
2831 if (this .cacheEnable ){
29- Configuration xmlConf = new XmlConfiguration (SingletonCacheImpl .class .getResource ("/ehcache3.xml" ));
30- this .manager = CacheManagerBuilder .newCacheManager (xmlConf );
32+ URL configUrl = getEhcacheConfigUrl ();
33+ if (configUrl == null ) {
34+ throw new IllegalStateException (
35+ "Ehcache config resource not found: " + EHCACHE_CONFIG_RESOURCE
36+ + ". Ensure it is on the classpath (e.g. in src/main/resources)." );
37+ }
38+ Configuration xmlConf = new XmlConfiguration (configUrl );
39+ this .manager = CacheManagerBuilder .newCacheManager (xmlConf );
3140 this .manager .init ();
3241 }
3342 }
3443
44+ /**
45+ * Resolve ehcache3.xml from the classpath. Tries thread context class loader first
46+ * (for Spring Boot fat jars), then the class loader of this class.
47+ */
48+ private static URL getEhcacheConfigUrl () {
49+ URL url = Thread .currentThread ().getContextClassLoader ().getResource (EHCACHE_CONFIG_RESOURCE );
50+ if (url == null ) {
51+ url = SingletonCacheImpl .class .getResource ("/" + EHCACHE_CONFIG_RESOURCE );
52+ }
53+ return url ;
54+ }
55+
3556 private <K , V > Cache <K , V > getCache (CacheName cachename , Class <K > keyType , Class <V > valueType ) throws VIPCacheException {
3657 return this .manager .getCache (cachename .name (), keyType ,valueType );
3758 }
0 commit comments