JBoss.org Community Documentation

3.2.2. Programmatic Configuration

In addition to the XML-based configuration above, the Configuration can be built up programatically, using the simple property mutators exposed by Configuration and its components. When constructed, the Configuration object is preset with JBoss Cache defaults and can even be used as-is for a quick start.

Following is an example of programatically creating a Configuration configured to match the one produced by the XML example above, and then using it to create a Cache :



   Configuration config = new Configuration();
   String tmlc = GenericTransactionManagerLookup.class.getName();
   config.setTransactionManagerLookupClass(tmlc);
   config.setIsolationLevel(IsolationLevel.READ_COMMITTED);
   config.setCacheMode(CacheMode.LOCAL);
   config.setLockParentForChildInsertRemove(true);
   config.setLockAcquisitionTimeout(15000);

   EvictionConfig ec = new EvictionConfig();
   ec.setWakeupIntervalSeconds(5);
   ec.setDefaultEvictionPolicyClass(LRUPolicy.class.getName());

   EvictionRegionConfig erc = new EvictionRegionConfig();
   erc.setRegionName("_default_");

   LRUConfiguration lru = new LRUConfiguration();
   lru.setMaxNodes(5000);
   lru.setTimeToLiveSeconds(1000);

   erc.setEvictionPolicyConfig(lru);

   List<EvictionRegionConfig> ercs = new ArrayList<EvictionRegionConfig>();
   ercs.add(erc);
   ec.setEvictionRegionConfigs(erc);

   config.setEvictionConfig(ec);

   CacheFactory factory = DefaultCacheFactory.getInstance();
   Cache cache = factory.createCache(config);

Even the above fairly simple configuration is pretty tedious programming; hence the preferred use of XML-based configuration. However, if your application requires it, there is no reason not to use XML-based configuration for most of the attributes, and then access the Configuration object to programatically change a few items from the defaults, add an eviction region, etc.

Note that configuration values may not be changed programmatically when a cache is running, except those annotated as @Dynamic . Dynamic properties are also marked as such in the configuration reference table. Attempting to change a non-dynamic property will result in a ConfigurationException .