AOP切面

deity-night / 2025-01-25 / 原文

切面修改注解内部属性值

注解

@Target(ElementType.METHOD)
// 运行时
@Retention(RetentionPolicy.RUNTIME)
// 可以出现在 生成的doc文档上
@Documented
public @interface RepeatSubmit {
    // 属性以方法的形式  可以设置默认值
    int lockTime() default 5;

    String methodName() default  "";

}

 切面

@Order(0)
@Slf4j
@Aspect
@Component
public class RepeatSubmitAspect {

    @Before("execution(* *(..))&&@annotation(com.springboot.demo.webbase.annotation.RepeatSubmit)")
    public void logExecutionTime(JoinPoint joinPoint) throws Throwable {
        System.out.println("aop start");
        long start = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest  request = attributes.getRequest();
        Map<String, String[]> parameterMap = request.getParameterMap();
        MethodSignature  signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod( );
        RepeatSubmit repeatSubmit = method.getAnnotation(RepeatSubmit.class);
        // System.out.println(repeatSubmit);
        InvocationHandler invocationHandler = Proxy.getInvocationHandler(repeatSubmit);
        Field memberValues = invocationHandler.getClass().getDeclaredField("memberValues");
        memberValues.setAccessible(true);
        Map map = (Map)memberValues.get(invocationHandler);
        System.out.println(map);
        map.put("lockTime", Integer.valueOf(String.join("",parameterMap.get("lockTime"))));
        map.put("methodName", String.join("", parameterMap.get("methodName")));
        System.out.println(repeatSubmit);

        long executionTime = System.currentTimeMillis() - start;
        log.info("Method {} execution time: {} ms", joinPoint.getSignature().toShortString(), executionTime);
        System.out.println("aop end");
    }
}

  

接口

@RequiredArgsConstructor
@RestController
@RequestMapping("/aop")
public class AopTestController {
    private final AopTestService aopTestService;

    @RepeatSubmit
    @GetMapping("/doSomeThing")
    public String doSomeThing() {
        aopTestService.doSomeThingOther();
        return "success";
    }
}