导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
开启注解
@SpringBootApplication
@EnableAspectJAutoProxy //开启aop注解
public class AOP_example {
public static void main(String[] args) {
SpringApplication.run(AOP_example.class,args);
}
}
配置切面
@Component
@Aspect
public class AspectService { //切面
//切点
@Pointcut("execution(public * com.qyc.service.impl..*(..))")
public void webPointCut(){
}
@Before("webPointCut()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
System.out.println("通过");
// 记录下请求内容
System.out.println("URL : " + request.getRequestURL().toString());
System.out.println("HTTP_METHOD : " + request.getMethod());
System.out.println("IP : " + request.getRemoteAddr());
System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
System.out.println("ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
@After("webPointCut()")
public void doAfter(){
System.out.println("@doAfter");
}
@AfterReturning("webPointCut()")
public void doAfterReturning(){
System.out.println("@doAfterReturning");
}
@AfterThrowing("webPointCut()")
public void doAfterThrowing(){
System.out.println("@AfterThrowing");
}
@Around("webPointCut()")
public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint){
System.out.println("环绕通知的目标方法名:"+proceedingJoinPoint.getSignature().getName());
Long start = System.currentTimeMillis();
try {
Object obj = proceedingJoinPoint.proceed();
Long end = System.currentTimeMillis();
System.out.println("环绕通知结束"+ (end-start));
return obj;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}
}
环绕通知的目标方法名:test02
通过
URL : http://localhost:8889/test/2
HTTP_METHOD : GET
IP : 127.0.0.1
CLASS_METHOD : com.qyc.service.impl.TestServiceImpl.test02
ARGS : [强月城]环绕通知结束 7
@doAfter
@doAfterReturning