版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014022405/article/details/78804236
问题引入:当我spring集成ehcache的时候全程使用注解开发,需要缓存就在方法上添加@Cacheable注解(这里不讨论如何集成和使用,自行百度),有时候如果我们需要自己加缓存,并不想用注解作用在方法上,那该怎么办呢?
第一步:获取ApplicationContext,编写ApplicationContextUtils 类,实现ApplicationContextAware 接口
@Component
@EnableAutoConfiguration
public class ApplicationContextUtils implements ApplicationContextAware {
public static ApplicationContext applicationContext=null;//可写成单利模式,这里为了方便
@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
applicationContext=arg0;
System.out.println("设置ApplicationContext成功!");
}
}
上面这个类,Spring在初始化ApplicationContextUtils的时候会自动调用setApplicationContext方法。
然后,利用ApplicationContext获取IOC容器里面的EhCacheCacheManager
//获取EhCacheCacheManager类
EhCacheCacheManager cacheCacheManager=ApplicationContextUtils.applicationContext.getBean(EhCacheCacheManager.class);
//获取CacheManager类
CacheManager cacheManager=cacheCacheManager.getCacheManager();
//获取Cache
Cache cache=cacheManager.getCache("userCache");
cache.put(new Element("Hello", "123"));
System.out.println(cache.get("Hello").getObjectValue());
附上ehcache配置文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<defaultCache
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="100"
memoryStoreEvictionPolicy="LRU" />
<cache
name="userCache"
eternal="false"
maxElementsInMemory="100"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="30"
memoryStoreEvictionPolicy="LRU" />
</ehcache>