Springboot自定义注解,支持SPEL表达式

Springboot自定义注解,支持SPEL表达式举例,自定义redis模糊删除注解1.自定义注解importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;@Target(E…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全家桶1年46,售后保障稳定

举例,自定义redis模糊删除注解

1.自定义注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CacheEvictFuzzy {
    /**
     * redis key集合,模糊删除
     * @return
     */
    String[] key() default "";

}

Jetbrains全家桶1年46,售后保障稳定

2.使用AOP拦截方法,解析注解参数

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Set;
@Aspect
@Order(1)
@Component
public class CacheCleanFuzzyAspect {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisUtil redis;

    //指定要执行AOP的方法
    @Pointcut(value = "@annotation(cacheEvictFuzzy)")
    public void pointCut(CacheEvictFuzzy cacheEvictFuzzy){}


    // 设置切面为加有 @RedisCacheable注解的方法
    @Around("@annotation(cacheEvictFuzzy)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint, CacheEvictFuzzy cacheEvictFuzzy){
        return doRedis(proceedingJoinPoint, cacheEvictFuzzy);
    }
    @AfterThrowing(pointcut = "@annotation(cacheEvictFuzzy)", throwing = "error")
    public void afterThrowing (Throwable  error, CacheEvictFuzzy cacheEvictFuzzy){
        logger.error(error.getMessage());
    }

    /**
     * 删除缓存
     * @param proceedingJoinPoint
     * @param cacheEvictFuzzy
     * @return
     */
    private Object doRedis (ProceedingJoinPoint proceedingJoinPoint, CacheEvictFuzzy cacheEvictFuzzy){
        Object result = null;
        //得到被切面修饰的方法的参数列表
        Object[] args = proceedingJoinPoint.getArgs();
        // 得到被代理的方法
        Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod();
        String[] keys = cacheEvictFuzzy.key();
        Set<String> keySet = null;
        String realkey = "";
        for (int i = 0; i < keys.length; i++) {
            if (StringUtils.isBlank(keys[i])){
                continue;
            }
            realkey = parseKey(keys[i], method, args);
            keySet = redis.keys("*"+realkey+"*");
            if (null != keySet && keySet.size()>0){
                redis.delKeys(keySet);
                logger.debug("拦截到方法:" + proceedingJoinPoint.getSignature().getName() + "方法");
                logger.debug("删除的数据key为:"+keySet.toString());
            }
        }
        try {
            result = proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }finally {
            return result;
        }
    }
    /**
     * 获取缓存的key
     * key 定义在注解上,支持SPEL表达式
     * @return
     */
    private String parseKey(String key, Method method, Object [] args){

        if(StringUtils.isEmpty(key)) return null;

        //获取被拦截方法参数名列表(使用Spring支持类库)
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paraNameArr = u.getParameterNames(method);

        //使用SPEL进行key的解析
        ExpressionParser parser = new SpelExpressionParser();
        //SPEL上下文
        StandardEvaluationContext context = new StandardEvaluationContext();
        //把方法参数放入SPEL上下文中
        for(int i=0;i<paraNameArr.length;i++){
            context.setVariable(paraNameArr[i], args[i]);
        }
        return parser.parseExpression(key).getValue(context,String.class);
    }
}

完事啦!

大家可以注意到关键方法就是parseKey

    /**
     * 获取缓存的key
     * key 定义在注解上,支持SPEL表达式
     * @return
     */
    private String parseKey(String key, Method method, Object [] args){

        if(StringUtils.isEmpty(key)) return null;

        //获取被拦截方法参数名列表(使用Spring支持类库)
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paraNameArr = u.getParameterNames(method);

        //使用SPEL进行key的解析
        ExpressionParser parser = new SpelExpressionParser();
        //SPEL上下文
        StandardEvaluationContext context = new StandardEvaluationContext();
        //把方法参数放入SPEL上下文中
        for(int i=0;i<paraNameArr.length;i++){
            context.setVariable(paraNameArr[i], args[i]);
        }
        return parser.parseExpression(key).getValue(context,String.class);
    }

ok啦,大家记得点赞加关注啊!

双击评论666走起!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/230826.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 从零开始学android编程之Toast提示信息框「建议收藏」

    从零开始学android编程之Toast提示信息框「建议收藏」Toast类可以在程序界面上显示一个简单的提示信息,这个提示信息框用于向用户生成简单的提示信息。1创建包含信息的提示框通过Toast类的静态方法makeText()创建信息提示框,该提示框中包含了指定的信息。该方法的格式为publicstaticToastmakeText(Contextcontext,CharSequencetext,intduration);其

    2022年6月10日
    52
  • java实现Math.sqrt函数

    java实现Math.sqrt函数难易程度:★★★重要性:★★★★★度小满金融的面试中出现过:自己实现Math.sqrt函数//计算:Math.sqrt(num)//原理:牛顿迭代法://https://baike.baidu.com/item/%E7%89%9B%E9%A1%BF%E8%BF%AD%E4%BB%A3%E6%B3%95/10887580?fr=aladdinprivate…

    2022年5月20日
    61
  • js刷新当前页面方法「建议收藏」

    js刷新当前页面方法「建议收藏」js刷新当前页面js刷新当前页面在写JS代码时,用到JS来刷新当前页面的方法有几种,比如最常用的reload(),location等reload方法,该方法强迫浏览器刷新当前页面。语法:location.reload([bForceGet])参数:bForceGet,可选参数,默认为false,从客户端缓存里取当前页。true,则以GET方式,从服务端取最新的页面,相当于客户端点击F5(“刷新”)replace方法,该方法通过指定URL替换当前缓存在历史里(客

    2022年10月26日
    0
  • 网络交换机光口和电口_交换机的光口

    网络交换机光口和电口_交换机的光口 一、光口1、基本概念     光口是光纤接口的简称。   也可称之为:G口 (意思是G光纤口)   光口:所应用于机房,机柜等大型设备的一个光纤带宽接口。   光纤可以用于音频(声卡有光输出的),网络(光纤作为传输介质),磁盘(光纤代替电缆传输数据)等等。   光纤又可分为单模光纤和多模光纤区别如下:   单模光纤和多模光纤可以从纤芯的尺…

    2022年10月21日
    0
  • pycharm搭建python环境_pycharm如何配置编译环境

    pycharm搭建python环境_pycharm如何配置编译环境1.安装python27双击执行python-2.7.15.msi,选择装到根目录,建议d:\Python27。一路下一步,直到完成。安装完成之后,打开cmd,输入:python,如果显示以下内容则说明安装python成功如果提示命令不存在则需要设置环境变量。windows:右键我的电脑–属性–高级系统设置–高级–环境变量–系统变量找到path项,加上值,D:\Python27;D:\P…

    2022年8月25日
    6
  • Autoencoder自动编码器的发展

    Autoencoder自动编码器的发展Autoencoder自动编码器的发展0、玻尔兹曼机中的测试实验——编码问题(1985)0.1、玻尔兹曼机0.2、受限的玻尔兹曼机0.3、编码问题——自动编码器雏形1、反向传播中的仿真——单层自动编码器(1986)2、利用神经网络进行数据降维——深度自动编码器(2006)3、去噪自编码器(2008)4、稀疏自编码器(2011)5、卷积自编码器(2011)6、变分自编码器(2013)6.1、模型6….

    2022年5月1日
    46

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号