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 {
@Cacheable(value = { "sampleCache" })
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;
@Configuration
@EnableCaching
public class CachingConfig {
@Bean
public Book book() {
return new Book();
}
@Bean
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