本篇文章给大家带来的内容是关于springboot中aop的使用介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
第一步:添加依赖
org.springframework.boot spring-boot-starter-aop
第二步:定义一个切面类
package com.example.demo.aop;
import java.lang.reflect.Method;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import static com.sun.xml.internal.ws.dump.LoggingDumpTube.Position.Before;
@Component
@Aspect // 将一个java类定义为切面类
@Order(-1)//如果有多个aop,这里可以定义优先级,越小级别越高
public class LogDemo {
private static final Logger LOG = LoggerFactory.getLogger(LogDemo.class);
@Pointcut("execution(* com.example.demo.test.TestController.test(..))")//两个..代表所有子目录,最后括号里的两个..代表所有参数
public void logPointCut() {
}
@Before("logPointCut()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
System.out.println("before");
}
@After(value = "logPointCut()")
public void after(JoinPoint joinPoint) {
System.out.println("after");
}
@AfterReturning(returning = "ret", pointcut = "logPointCut()")// returning的值和doAfterReturning的参数名一致
public void doAfterReturning(Object ret) throws Throwable {
System.out.println("AfterReturning");
}
@Around("logPointCut()")
public void doAround(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("around1");
Object ob = pjp.proceed();//环绕通知的进程方法不能省略,否则可能导致无法执行
System.out.println("around2");
}
}
注意:
如果同一个 切面类,定义了定义了两个 @Before,那么这两个 @Before的执行顺序是无法确定的
对于@Around,不管它有没有返回值,但是必须要方法内部,调用一下 pjp.proceed();否则,Controller 中的接口将没有机会被执行,从而也导致了 @Before不会被触发
测试的controller如下:
这是一款比较精美的企业网站管理系统源码,功能比较完整,比较适合新手学习交流使用,也可以作为毕业设计或者课程设计使用,感兴趣的朋友可以下载看看哦。功能介绍:该源码主要包括前台和后台两大部分,具体功能如下:网站前台模块:主要包括企业简介、新闻中心、产品展示、公司证书、工程业绩、联系我们、客户系统、人才招聘等信息的浏览,以及客户留言的功能。网站后台模块1、常规管理:企业简介、链接管理、投票管理、系统设置
package com.example.demo.test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class TestController {
@RequestMapping(value = "test",method = RequestMethod.GET)
@ResponseBody
public String test(String name){
System.out.println("============method");
return name;
}
}配置完成,看看效果,输出如下:
around1 before============method around2 after AfterReturning
可以看到,切面方法的执行如下:
around-->before-->method-->around-->after-->AfterReturning
如果配置了@AfterThrowing,当有异常时,执行如下:
around-->before-->method-->around-->after-->AfterThrowing









