自定义注解动态赋值


需求

实现自定义注解动态赋值,针对请求传输过来参数进行动态赋值,拦截处理redis缓存中文章的阅读浏览量。。

直接上代码

一、自定义注解类

代码如下(示例):

/**
 * created By gywenlover on 2020-08-11
 *
 * 该注解作用在方法上,需要传入动态el值进行阅读量增加(el内容为el表达式)
 *
 *
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ReadNum {

    String front() default "";
    String el() default "";
    String key() default "";

}

二、请求方法添加注解类

1.请求方法添加注解

代码如下(示例):

    @GetMapping(value = "/{id}")
    @ApiOperation("获取活动详情 - 需要活动id")
    @ReadNum(front = ReadCode.ACTIVITY_KEY_CODE,el = "#id")
    public AjaxResult getInfo(@PathVariable("id") String id) {
    	return null;
    }

三、AOP拦截器

1.请求方法添加注解

代码如下(示例):

    
/**
 * @ClassName: viewsAspect
 * @description: 甘孜州自建频道各模块浏览量统计
 * @author: Apache_MYK
 * @createDate: 2021/8/5 10:06
 * @version: 1.0
 */
@Aspect
@Component
public class ViewsAspect {

    private static final Logger log = LoggerFactory.getLogger(ViewsAspect.class);

    @Autowired
    private RedisCache redisCache;

    // 配置织入点
//    @Pointcut(
//            "execution(* com.api.controller..GzActivityController.getInfo(String))" +
//                    "|| execution(* com.api.controller..GzWorkController.getInfo(Long))" +
//                    "|| execution(* com.api.controller..GzCurriculumController.getInfo(String))"+
//                    "|| execution(* com.api.controller..GzAnnouncementController.getAnnouncementInfo(*))"
//    )
    @Pointcut("@annotation(com.api.common.annotation.ReadNum)")
    public void viewsPointCut() {
    }

    /**
     * 只有正常返回才会执行此方法
     * 如果程序执行失败,则不执行此方法
     */
    @AfterReturning(pointcut = "viewsPointCut()")
    public void doAfterReturning(JoinPoint joinPoint) throws Exception {
        //获取注解
        ReadNum controllerLog = getAnnotationReadNum(joinPoint);
        String viewType = controllerLog.front()+controllerLog.key();
        Integer cacheObject = redisCache.getCacheObject(viewType);
        if (Objects.isNull(cacheObject)) {
            cacheObject = 0;
        }
        redisCache.setCacheObject(viewType, cacheObject + 1);
    }


    /**
     * 是否存在注解,如果存在就获取
     */
    private ReadNum getAnnotationReadNum(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(ReadNum.class);
        }
        return null;
    }


    private SpelExpressionParser spelParser = new SpelExpressionParser();


    /**
     * 前置通知
     */
    @Before("@annotation(com.api.common.annotation.ReadNum)")
    public void before(JoinPoint joinPoint) throws Exception {
        ReadNum readNum = getAnnotationReadNum(joinPoint);
        //获取方法的参数名和参数值
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        List<String> paramNameList = Arrays.asList(methodSignature.getParameterNames());
        List<Object> paramList = Arrays.asList(joinPoint.getArgs());
        //将方法的参数名和参数值一一对应的放入上下文中
        EvaluationContext ctx = new StandardEvaluationContext();
        for (int i = 0; i < paramNameList.size(); i++) {
            ctx.setVariable(paramNameList.get(i), paramList.get(i));
        }
        // 解析SpEL表达式获取结果
        String value = spelParser.parseExpression(readNum.el()).getValue(ctx).toString();
        //获取 sensitiveOverride 这个代理实例所持有的 InvocationHandler
        InvocationHandler invocationHandler = Proxy.getInvocationHandler(readNum);
        // 获取 invocationHandler 的 memberValues 字段
        Field hField = invocationHandler.getClass().getDeclaredField("memberValues");
        // 因为这个字段是 private final 修饰,所以要打开权限
        hField.setAccessible(true);
        // 获取 memberValues
        Map memberValues = (Map) hField.get(invocationHandler);
        // 修改 value 属性值
        memberValues.put("key", value);
    }

}

总结

例如:以上就是今天要讲的内容,其中内容有对aop内容使用对详细流程,通过代码对反射,动态赋值,针对el表达式封装获取对象中对属性,动态的对自定义注解进行赋值,完成基本功能,自己也做一个记录。谢谢
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Java中,我们可以通过自定义注解的方式为某一字段赋值。首先,我们需要定义一个注解,使用@interface关键字声明,并可以在注解内部定义一些属性。接下来,在需要赋值的字段上,通过在字段前加上该注解的方式来使用自定义注解。 首先,我们创建一个自定义注解,例如@MyAnnotation: ```java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) // 指定注解的生命周期为运行时 @Target(ElementType.FIELD) // 指定注解的作用目标为字段 public @interface MyAnnotation { String value(); // 定义一个属性value,用于赋值 } ``` 然后,我们可以在需要赋值的字段上使用@MyAnnotation注解,并通过value属性给字段赋值: ```java public class MyClass { @MyAnnotation("Hello") // 通过@MyAnnotation注解给field赋值为"Hello" private String field; public String getField() { return field; } public void setField(String field) { this.field = field; } } ``` 最后,我们可以使用反射获取字段的注解信息,并获取注解中的值,实现给字段赋值的功能: ```java import java.lang.reflect.Field; public class Main { public static void main(String[] args) throws Exception { MyClass obj = new MyClass(); Field field = obj.getClass().getDeclaredField("field"); // 获取字段 MyAnnotation annotation = field.getAnnotation(MyAnnotation.class); // 获取字段上的注解 if (annotation != null) { String value = annotation.value(); // 获取注解的值 field.setAccessible(true); // 设置字段可访问 field.set(obj, value); // 给字段赋值 } System.out.println(obj.getField()); // 输出 "Hello" } } ``` 通过以上方法,我们可以通过自定义注解的方式为某一字段赋值,实现更加灵活和可扩展的代码编写方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丶moli

您的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值