XML Programmatic Parsing
The following section goes through the steps and possibilities of
automatically configuring a
CacheManager using XML.
CacheManager through API calls based on JSR-107, what
follows is done automatically when invoking
javax.cache.spi.CachingProvider.getCacheManager(java.net.URI,
java.lang.ClassLoader).
final URL myUrl =
getClass().getResource("/configs/docs/getting-started.xml"); // <1>
XmlConfiguration xmlConfig = new XmlConfiguration(myUrl); // <2>
CacheManager myCacheManager =
CacheManagerBuilder.newCacheManager(xmlConfig); // <3>
myCacheManager.init(); // <4>
-
Obtain a
URLto your XML file's location -
Instantiate an
XmlConfigurationpassing the URL of the XML file to it. - Create your
CacheManagerinstance using theConfigurationfrom theXmlConfiguration. -
Initialize the
CacheManagerbefore it is used.
We can also use
<cache-template> declared in the XML file to seed
instances of
CacheConfigurationBuilder. In order to use a
<cache-template> element from an XML file, the XML
file contains the following XML fragment:
<cache-template name="example">
<key-type>java.lang.Long</key-type>
<value-type>java.lang.String</value-type>
<heap unit="entries">200</heap>
</cache-template>
Creating a
CacheConfigurationBuilder of that example
<cache-template> element would be done as follows:
XmlConfiguration xmlConfiguration = new XmlConfiguration(getClass()
.getResource("/configs/docs/template-sample.xml"));
CacheConfigurationBuilder<Long, String> configurationBuilder =
xmlConfiguration.newCacheConfigurationBuilderFromTemplate("example",
Long.class, String.class); // <1>
configurationBuilder = configurationBuilder.
withResourcePools(ResourcePoolsBuilder.heap(1000)); // <2>
-
Creates a builder, inheriting the capacity constraint of 200 entries.
-
The inherent properties can be overridden by simply providing a different value prior to building the
CacheConfiguration.