http://www.javacodegeeks.com/2011/02/spring-31-cache-abstraction-tutorial.html

http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/cache.html

1. 캐시 선언

2. 캐시 설정

캐시 선언

1. @Cacheable

캐시할 메서드 위에 선언하면 된다. 그런데 key값을 무조건 메서드의 모든 매개변수의 해시 코드 값을 사용하기는 뭐하다. 내가 사용하고 싶은 속성만 사용해서 key값을 정하고 싶다. 그럴 수 있다. key라는 속성에 SpEL을 사용하면 된다.

[java]
@Cacheable(value="book", key="isbn"
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

@Cacheable(value="book", key="isbn.rawNumber")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

@Cacheable(value="book", key="T(someType).hash(isbn)")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
[/java]

@Cacheable의 key에서 사용할 수 있는 SpEL에서 참조할 수 있는 객체

- methodName | @Cacheable을 호출한 메서드 이름 | #root.methodName

- caches | 현재 메서드 실행 했을 때의 캐시 컬렉션 | #root.caches[0].name

- 매개변수 이름 | 메서드 매개변수에 선언되어 있는 변수명 | 암거나..

그리고 메서드 호출될 때마다 캐시로 저장하지 말고, 특정 조건을 만족할 때만 캐시하고 싶다. 그럴 수 있다. condition이라는 속성을 사용하면 된다.

[java]
@Cacheable(value="book", condition="name.length < 32")
public Book findBook(String name)
[/java]
2. @CacheEvict

캐시에서 빼고 싶을 때 사용하고, 속성은 @cacheable과 비슷하다. allEntries가 하나 더 있는데, 특정 캐시 영역을 전부 날리고 싶을 때 사용하면 된다.

@CacheEvict(value=”books”, allEntires=true)

캐시 설정

애노테이션은 선언일 뿐, 선언해둔다고 다 되진 않는다. 선언을 읽어서 실제 처리를 할 빈을 등록해야 함. cache라는 네임스페이스 추가해뒀기 때문에 편하게 설정할 수 있다.

[xml]
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<cache:annotation-driven />
[/xml]
현재 기본 구현체로는 ConcurrentHashMap 기반의 구현체를 사용하며, Ehcache 기반 구현체를 스프링에서 따로 제공한다. Ehcache 기반의 구현체를 사용하고 싶다면 다음과 같이 설정하면 된다.

[xml]
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhcacheCacheManager" p:cache-manager="ehcache"/>

<!-- Ehcache library setup -->
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="ehcache.xml"/>
[/xml]