1. First go to the official Download Spring jar package, I use sring 4.1.6 has integrated the Ehcache.
2. Write the spring configuration file, and note that you need to add the cache constraint file.
Xmlns:cache= "Http://www.springframework.org/schema/cache"
Http://www.springframework.org/schema/cache
Http://www.springframework.org/schema/cache/spring-cache.xsd
3. Configure the Ehcache cache Manager in the Spring configuration file:
<!--Use the following CacheManager--> by default;
<cache: Annotation-driven/> ---Turn on the cache scan
<bean id= "cachemanagerfactory" class= " Org.springframework.cache.ehcache.EhCacheManagerFactoryBean,
<property name= "configlocation" value= "Classpath:ehcache.xml " > </property>
</bean>
<bean id= "cachemanager "class=" Org.springframework.cache.ehcache.EhCacheCacheManager ";
<property name= "CacheManager" ref= "Cachemanagerfactory" ></property>
</bean>
<bean id= "test" class= "Test.cn.test" > </bean>
4. Configure Ehcache.xml, the above path is written to save the file under SRC.
<?xml version= "1.0" encoding= "UTF-8"?>
<ehcache xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xsi:nonamespaceschemalocation= "http// Ehcache.org/ehcache.xsd ">
<diskstore path= "Java.io.tmpdir/ehcache"/>
<!--default Cache--
<defaultcache
maxelementsinmemory= "1000"
Eternal= "false"
Timetoidleseconds= "120"
Timetoliveseconds= "120"
Overflowtodisk= "false"/>
<!--Menu Cache--
<cache name= "Menucache"
maxelementsinmemory= "1000"
Eternal= "false"
Timetoidleseconds= "120"
Timetoliveseconds= "120"
Overflowtodisk= "false"
memorystoreevictionpolicy= "LRU"/>
</ehcache>
5. Configure Web. XML here is not to say, load the Spring.xml file with the spring listener. (Spring Foundation).
6. The configuration is successful and can be tested.
@Cacheable (value= "Menucache", key= "#id")--Add cache
public int query (int id) {
SYSTEM.OUT.PRINTLN ("Query");
return ID;
}
@Cacheable (value= "Menucache", key= "#str")
public string Querystr (String str) {
System.out.println ("Querystr");
return "123";
}
@CacheEvict (value= "Menucache")---delete cache
public void Update () {
SYSTEM.OUT.PRINTLN ("Update");
}
You can see that the query is not printed again every time you call query (). Indicates that the cache was successful, called cacheevict when modified, and emptied the cache.
Spring uses Ehcache cache