1.在pom.xml添加aop依赖
<!-- aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.定义切面类
a.@Aspect将其定义为切面
b.@Component让spring可以ioc操作
c.@Pointcut定义切点
d.@Before,@After等等定义通知
package com.cwh.webProject.Aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LogAspect {
@Pointcut("execution(public * com.cwh.webProject.controller.userController.*(..))")
public void webLog() {}
@Before("webLog()")
public void doBefore() {
System.out.println("在方法调用前输出");
}
@AfterReturning(returning="ret",pointcut="webLog()")
public void afterReturning(Object ret) {
System.out.println("方法返回的结果+"+ ret);
}
@After("webLog()")
public void doAfter() {
System.out.println("在方法介绍后调用");
}
@AfterThrowing("webLog()")
public void doThrow(){
System.out.println("在抛出异常后输出");
}
@Around("webLog()")
public Object doRround(ProceedingJoinPoint pjp) {
System.out.println("环绕方法开始");
try {
Object o = pjp.proceed();
System.out.println("方法环绕proceed,结果是 :" + o);
return o;
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
3.测试
image.png4.详情参考地址
a.http://ju.outofmemory.cn/entry/342084
b.https://www.cnblogs.com/onlymate/p/9605165.html
网友评论