Introduction
Since Ehcache is a library and supports user types both in configuration and in mapping keys or values, it must offer flexibility around class loading.
Default ClassLoader
in Ehcache
The default ClassLoader
from Ehcache will first try to use the thread context class loader, through Thread.currentThread().getContextClassLoader()
.
In case this fails to load the requested resource, it will then use the ClassLoader
that loaded the Ehcache internal classes.
Handling User types
The way to configure a ClassLoader
and the scope of its use differ between Java and XML based configurations.
However, regardless of the configuration method, each CacheManager
and Cache
is always linked individually to a specific ClassLoader
instance.
Java configuration
During the configuration of the CacheManager
or Cache
, there are multiple extension points where a user type can be involved.
This includes Serializer
, CacheLoaderWriter
and other similar companion objects.
You can usually give an instance of these types to the configuration or an instance of the class to use.
This effectively negates the need to think in terms of a class loader here.
However you can still pass a specific ClassLoader
to the CacheManager
configuration.
You can also give a specific ClassLoader
per cache if you need to, taking precedence over the one configured at the CacheManager
level.
These will be used at runtime.
If no class loader is specified, the default class loader from Ehcache will be used.
Xml configuration
When using XML to configure Ehcache, references to custom types are given through a fully qualified class name.
This means that transforming these String
names into the proper class representation may require a specific ClassLoader
.
In order to support this, the XmlConfiguration
constructors can take ClassLoader
parameters:
public XmlConfiguration(URL url)
-
to use only default
ClassLoader
public XmlConfiguration(URL url, final ClassLoader classLoader)
-
to use a specific
ClassLoader
at theCacheManager
level public XmlConfiguration(URL url, final ClassLoader classLoader, final Map<String, ClassLoader> cacheClassLoaders)
-
to use a specific
ClassLoader
at theCacheManager
level and a map of<String, ClassLoader>
which will be used to link a specificClassLoader
to aCache
by its alias
In the same way as for the Java configuration, the Cache
level configuration takes precedence over the CacheManager
level one.
If no class loaders are specified, the default class loader from Ehcache will be used.