自定义注解实现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();//日志描述
}
The whole significance of life lies in the unremitting efforts to explore the unknown and increase knowledge.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了