【译】Spring的@EnableCaching注解
Spring的@EnableCaching注解
@EnableCaching注解是spring framework中的注解驱动的缓存管理功能。自spring版本3.1起加入了该注解。如果你使用了这个注解,那么你就不需要在XML文件中配置cache manager了。
当你在配置类(@Configuration)上使用@EnableCaching注解时,会触发一个post processor,这会扫描每一个spring bean,查看是否已经存在注解对应的缓存。如果找到了,就会自动创建一个代理拦截方法调用,使用缓存的bean执行处理。
如果你对缓存感兴趣并想了解更多,请阅读spring caching. 本文会帮助你了解如何使用@EnableCaching注解。
接下来的例子演示了@EnableCaching的用法。在代码中,我缓存了Book类找那个的方法。
代码
- //Book.java
- import org.springframework.cache.annotation.Cacheable;
- public class Book {
- public String getBook(int id) {
- System.out.println("Method executed..");
- if (id == 1) {
- return "Book 1";
- } else {
- return "Book 2";
- }
- }
- }
- //CachingConfig.java
- import java.util.Arrays;
- import org.springframework.cache.CacheManager;
- import org.springframework.cache.annotation.EnableCaching;
- import org.springframework.cache.concurrent.ConcurrentMapCache;
- import org.springframework.cache.support.SimpleCacheManager;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- public class CachingConfig {
- public Book book() {
- return new Book();
- }
- public CacheManager cacheManager() {
- SimpleCacheManager cacheManager = new SimpleCacheManager();
- cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("sampleCache")));
- return cacheManager;
- }
- }
上面的java config和下面的xml配置文件是等效的:
- <beans>
- <cache:annotation-driven/>
- <bean id="book" class="Book"/>
- <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
- <property name="caches">
- <set>
- <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">
- <property name="name" value="sampleCache"/>
- bean>
- set>
- property>
- bean>
- beans>
- //EnableCachingAnnotationExample.java
- import org.springframework.context.annotation.AnnotationConfigApplicationContext;
- public class EnableCachingAnnotationExample {
- public static void main(String[] args) {
- AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
- ctx.register(CachingConfig.class);
- ctx.refresh();
- Book book = ctx.getBean(Book.class);
- // calling getBook method first time.
- System.out.println(book.getBook(1));
- // calling getBook method second time. This time, method will not
- // execute.
- System.out.println(book.getBook(1));
- // calling getBook method third time with different value.
- System.out.println(book.getBook(2));
- ctx.close();
- }
- }
会得到如下的输出
- Method executed..
- Book 1
- Book 1
- Method executed..
- Book 2