AOP的妙用

一、改代码

自定义注解用于提示该代码已经在AOP中重构了

public @interface ReviseToAop {
    // 用于记录修改状态
    String value() default "";
}

使用注解(无意义,只是表名被修改)

   @ReviseToAop("修改于:2023/7/30")
   @GetMapping("/nm/{id}")
   public String Nm(@PathVariable("id") Integer id,@PathParam("name") String name) throws InterruptedException {
        log.info("当前未被修改的方法-------");
        return "当前未被修改的方法 id:"+id;
    }

aop中重构代码

监控类上的注解用@within(注解包地址)

监控方法上的注解用@annotation(注解地址)

监控方法用execution(权限类型 返回值类型 方法地址(参数类型))

    @Around("@annotation(com.example.demo.demos.contorl.ReviseToAop) && execution(String com.example.demo.demos.contorl.Hello.Nm(Integer,String))")
    public Object ReviseNm(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        log.info("数据被修改----");
        return   "已经被修改: "+args[0]+"name:"+args[1];
    }

二、自定义注解

设置一个类似@Value注解实现基本类型的数据注入

自定义注解

@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyValue {
    String value() default "";
}

@MyValue需要在@RestController下才能生效

    @Around("@within(org.springframework.web.bind.annotation.RestController)")
    public  Object setValue(ProceedingJoinPoint joinPoint) throws Throwable {
        Object target = joinPoint.getTarget();
        Field[] declaredFields = target.getClass().getDeclaredFields();
        for(Field field:declaredFields){

            field.setAccessible(true);
            MyValue annotation = field.getAnnotation(MyValue.class);
            if(!Objects.isNull(annotation)) {
                field.set(target, annotation.value());
                log.info("当前对象:{},当前字段:{},当前类名赋值:{}", joinPoint.getTarget().getClass().getName(), field.getName(),annotation.value());
            }
        }

      return   joinPoint.proceed(joinPoint.getArgs());
    }

ProceedingJoinPoint 对象
JoinPoint.getTarget() 获得当前对象
 joinPoint.getArgs() 获得当前参数
joinPoint.getTarget().getClass() 获得当前对象类的反射

你可能感兴趣的:(java,开发语言)