自定义注解实现AOP

自定义注解AOP

package com.log;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author Tobieance
 * @description 日志注解切面类
 * @date 2023-09-07 16:46
 */
@Component
@Aspect
public class LogAspect {

    @Pointcut("@annotation(com.log.MyLog)")//注解
    public void pointcut() {
    }

    @Before("pointcut()")
    public void log(JoinPoint joinPoint) throws NoSuchMethodException {
        //获取目标对象
        Object target = joinPoint.getTarget();
        //获取目标对象方法
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = target.getClass().getMethod(
                methodSignature.getName(),
                methodSignature.getParameterTypes());
        //获取注解对象实例
        MyLog log = method.getAnnotation(MyLog.class);

        String type = log.type();
        String desc = log.desc();

        System.out.println("日志类型:" + type + "\t\t调用方法" + method.getName() + "\t日志描述" + desc);
    }
}
package com.log;


import java.lang.annotation.*;

/**
 * @author Tobieance
 * @description MyLog注解
 * @date 2023-09-07 16:36
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyLog {
    String type();//日志类型
    String desc();//日志描述
}
posted @   一只特立独行的鸭嘴兽  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示