AOP组合使用切面和自定义注解
添加切面依赖
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.5</version> </dependency>
注解代码:
@Target({ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Document public @interface LogPrint{ //可附加属性 public String desc();//注意属性后面有括号 }
切面如下所示:
package com.springboot.study.aspjectj; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; /** * @Author: guodong * @Date: 2021/12/17 11:35 * @Version: 1.0 * @Description: */ @Aspect @Component public class LogPrintAspect1{ //自定义切点位置 //把切面连接点放在我们注解上 @Pointcut("@annotation(com.springboot.study.aspjectj.LogPrint)") private void controllerAspect(){} //自定义前置切面 //访问controller方法前先执行的方法 @Before(value = "controllerAspect()&&@annotation(logPrint)", argNames = "logPrint") public void printLog(LogPrint logPrint){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.ms"); System.out.println(sdf.format(new Date())+" || "+ logPrint.desc()); } @Around("controllerAspect()") public Object introcepter(ProceedingJoinPoint pjp) throws Throwable{ System.out.println("拦截到了" + pjp.getSignature().getName() +"方法..."); return pjp.proceed(); } /** * 可以处理返回参数等信息 * @param objList */ @AfterReturning(returning = "objList", pointcut = "controllerAspect()") public void around(String objList) { System.out.println("-----------AfterReturning" + objList); } }
参考博客:
https://www.cnblogs.com/qiumingcheng/p/5923928.html
https://blog.csdn.net/huofuman960209/article/details/82223787
https://www.jianshu.com/p/1329dfcb5c15?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation
郭慕荣博客园