方法一:使用 @EnableScheduling 注解
先上代码
package com.eason.spring.cache; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import com.eason.spring.dao.entity.User; import com.eason.spring.dao.mapper.UserMapper; @EnableScheduling @Service(value = "userService") public class UserService { private static final Log LOGGER = LogFactory.getLog(UserService.class); @Autowired private UserMapper userMapper; @Cacheable(value = "userCache") public User getUser(String uid) { LOGGER.info("Load user from DB, uid=" + uid); return userMapper.getUser(uid); } /** * 将当前更新的user从cache里删除 * * @param user */ @CacheEvict(value = "userCache", key = "#user.getUid()") public void updateUser(User user) { userMapper.update(user); } /** * 定时任务, 每分钟清除一次缓存 */ @Scheduled(cron = "0/1 * * * * ?") @CacheEvict(value = "userCache", allEntries = true) public void reload() { LOGGER.info("Remove all entries from userCache."); } }
注意事项:
1、spring的@Scheduled注解 需要写在实现上、
2、 定时器的任务方法不能有返回值(如果有返回值,spring初始化的时候会告诉你有个错误、需要设定一个proxytargetclass的某个值为true、具体就去百度google吧)
3、实现类上要有组件的注解@Component
方法二:使用spring配置文件,这时就不需要给实现类加上@EnableScheduling 和 @Component 注解,这样我们就可以将bean定义在spring的配置文件里了。
<context:component-scan base-package="com.eason.spring.cache" /> <context:annotation-config /> <task:annotation-driven />
注意事项:需要 spring 4.x