一,介绍
项目中我们经常会用到aop切面,比如日志记录,权限校验,参数过滤等
二,实现过程和示例代码
(1)Maven引包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
(2)Aspect 切面
package com.eceibs.report.aspect;
import org.apache.commons.lang3.ArrayUtils;
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 org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* 请求数据过滤
*/
@Aspect
@Component
public class HttpAspect {
/**
* 定义一个公共的方法
* 拦截DemoController下面的所有方法
* 拦截DemoController下面方法里的任何参数(..表示拦截任何参数)
* 写法: @Pointcut("execution(public * com.itaofly.aspect.controller.UserController.*(..))")
*/
@Pointcut(value = "execution(public * com.eceibs.report.controller.DemoController.*(..))")
public void checkHttpParams(){
}
@Before("checkHttpParams()")
public void doBefore(JoinPoint joinPoint){
ServletRequestAttributes attributes = (ServletRequestAttributes)
RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
System.out.println("doBefore");
//@todo 需要实现的逻辑代码
}
@After("checkHttpParams()")
public void doAfter(JoinPoint joinPoint){
System.out.println("doAfter");
//@todo 需要实现的逻辑代码
}
@After("checkHttpParams()")
public void doAfter(JoinPoint joinPoint){
System.out.println("doAfter");
//@todo 需要实现的逻辑代码
}
@AfterThrowing(pointcut = "checkHttpParams()")
public void doAfterThrowing() {
System.out.println("doAfterThrowing");
}
@Around("checkHttpParams()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) {
try {
Object obj = proceedingJoinPoint.proceed();
System.out.println("方法环绕..., 结果是 : {}" + obj);
return obj;
}catch (Throwable e) {
return null;
}
}
}
(3)测试
三,小结
虽然Around功能强大,但通常需要在线程安全的环境下使用。因此,如果使用普通的Before、AfterReturing增强方法就可以解决的事情,就没有必要使用Around增强处理了