Springboot集成ehcache时获取CacheManager自定义添加其他缓存

问题引入:当我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配置文件



    

    















你可能感兴趣的:(Springboot集成ehcache时获取CacheManager自定义添加其他缓存)