- 首先,需要在Spring配置文件中配置CacheManager和Cache的相关信息,如下所示:
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehCacheManager"/>
</bean>
<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml"/>
</bean>
<bean id="memoryCache" class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">
<property name="name" value="memoryCache"/>
</bean>
其中,cacheManager定义了使用EHCache作为缓存,而memoryCache则定义了使用ConcurrentMap作为缓存。
- 然后,在需要使用缓存的方法上添加@Cacheable注解,并指定缓存名称和key,如下所示:
@Cacheable(value = "memoryCache", key = "#id")
public User getUserById(Long id) {
// ...
}
- 最后,在ehcache.xml中配置缓存过期时间,如下所示:
<cache name="memoryCache" maxEntriesLocalHeap="1000" timeToLiveSeconds="3600"/>
其中,timeToLiveSeconds表示缓存的过期时间,单位为秒。
这样,就可以实现注解自定义过期时间的功能了。如果需要对不同的缓存设置不同的过期时间,只需在ehcache.xml中分别设置即可。