做一个自定义的缓存注解策略,比如要在新增、修改的操作时,使用自定义注解更灵活的去清除指定的缓存:
spring自己的CacheEvict中key="#user.id" 是能起作用的,在Cacheable..中去使用spel都可以获取入参的信息
但是我自己定义的注解MyCacheEvict里,在属性中一样的表达式去获取方法入参信息却拿不到值。
是需要额外加入什么配置才能使用springEL吗?跪求各位大神解惑!!
service方法截图:
import org.springframework.cache.annotation.CacheEvict;
import com.example.common.cacheCustomer.MyCacheEvict;
@CacheEvict(value = "users",key = "'user_'.concat(#user.id)")
@MyCacheEvict(value = "users",key ="'user_'.concat(#user.id)", keys = {"#{user.id}", "list"}, keyRegex = "list")
// spel: #user.id 或者 #user.getId()
public int updateOne(Users user){
return userMapper.updateByPrimaryKeySelective(user);
}
自定义注解:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Component
@Documented
public @interface MyCacheEvict{
//设置default值,则属性为非必填项
String value(); //cacheName
String key() default "" ; //key
String[] keys() default {} ; //key 数组
String keyRegex() default "" ; //key 模糊匹配
boolean allEntries() default false ; //是否清除此 cache 下所有缓存
}
aop 配置缓存策略:
@Pointcut("@annotation(com.example.common.cacheCustomer.MyCacheEvict)")
//声明切点
public void annotationPointCut(){};
@Autowired
CacheManager cacheManager;
@After("annotationPointCut()")
public void after(JoinPoint joinpoint){
MethodSignature signature = (MethodSignature) joinpoint.getSignature();
Method method = signature.getMethod();
MyCacheEvict myCacheEvict = method.getAnnotation(MyCacheEvict.class);
//反射得到注解上的属性
String value = myCacheEvict.value();
String key = myCacheEvict.key();
String regex = myCacheEvict.keyRegex();
String[] keys = myCacheEvict.keys();
boolean allEntries = myCacheEvict.allEntries();
System.out.println("注解式缓存策略---"+value+"-"+key);//
Cache cache = cacheManager.getCache(value);
Element element = cache.get(key);
System.out.println(element);
}
@Before("annotationPointCut()")
public void before(JoinPoint joinpoint){
}
转载于:https://blog.51cto.com/bumpkin/1941470