11/*
2- * Copyright 2019-2023 VMware, Inc.
2+ * Copyright 2019-2026 VMware, Inc.
33 * SPDX-License-Identifier: EPL-2.0
44 */
55package com .vmware .vip .common .cache ;
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,10 +29,34 @@ 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 );
31- this .manager .init ();
32+ try {
33+ URL configUrl = getEhcacheConfigUrl ();
34+ if (configUrl == null ) {
35+ throw new IllegalStateException (
36+ "Ehcache config resource not found: " + EHCACHE_CONFIG_RESOURCE
37+ + ". Ensure it is on the classpath (e.g. in src/main/resources)." );
38+ }
39+ Configuration xmlConf = new XmlConfiguration (configUrl );
40+ this .manager = CacheManagerBuilder .newCacheManager (xmlConf );
41+ this .manager .init ();
42+ } catch (Exception e ) {
43+ String msg = e .getMessage () != null ? e .getMessage () : e .getClass ().getName ();
44+ throw new IllegalStateException (
45+ "Failed to initialize singleton cache: " + msg , e );
46+ }
47+ }
48+ }
49+
50+ /**
51+ * Resolve ehcache3.xml from the classpath. Tries thread context class loader first
52+ * (for Spring Boot fat jars), then the class loader of this class.
53+ */
54+ private static URL getEhcacheConfigUrl () {
55+ URL url = Thread .currentThread ().getContextClassLoader ().getResource (EHCACHE_CONFIG_RESOURCE );
56+ if (url == null ) {
57+ url = SingletonCacheImpl .class .getResource ("/" + EHCACHE_CONFIG_RESOURCE );
3258 }
59+ return url ;
3360 }
3461
3562 private <K , V > Cache <K , V > getCache (CacheName cachename , Class <K > keyType , Class <V > valueType ) throws VIPCacheException {
0 commit comments