首先定义一个切面,用注解@Aspect
设置切入点
@Pointcut("execution(public * com.myspringboottest.springbootdemo.controller.*.*(..))")
声明要切的是controller包下的
具体所有代码
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
/**
* @Auther: AmbroseLee
* @Date: 2018/9/4 16:56
* @Description: web层日志切面
*/
//@Aspect
// 作用是把当前类标识为一个切面供容器读取
@Aspect
@Component
public class LogAspect {
// 设置切入点
@Pointcut("execution(public * com.myspringboottest.springbootdemo.controller.*.*(..))")
public void webLog(){}
//@Before
//标识一个前置增强方法,相当于BeforeAdvice的功能
@Before("webLog()")
public void deBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
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()));
}
// @AfterReturning
// 后置增强,相当于AfterReturningAdvice,方法退出时执行
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
System.out.println("方法的返回值 : " + ret);
}
//@AfterThrowing
//异常抛出增强,相当于ThrowsAdvice
//后置异常通知
@AfterThrowing("webLog()")
public void throwss(JoinPoint jp){
System.out.println("方法异常时执行.....");
}
//@After
//final增强,不管是抛出异常或者正常退出都会执行
//后置最终通知,final增强,不管是抛出异常或者正常退出都会执行
@After("webLog()")
public void after(JoinPoint jp){
System.out.println("方法最后执行.....");
}
//@Around
//环绕增强,相当于MethodInterceptor
//环绕通知,环绕增强,相当于MethodInterceptor
@Around("webLog()")
public Object arround(ProceedingJoinPoint pjp) {
System.out.println("方法环绕start.....");
try {
Object o = pjp.proceed();
System.out.println("方法环绕proceed,结果是 :" + o);
return o;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
}
写一个controller进行测试一下
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Auther: AmbroseLee
* @Date: 2018/9/4 16:52
* @Description:
*/
@RestController
@RequestMapping("/aop")
public class AopController {
@RequestMapping("demoOne")
public String demoOne(){
return "demoOne";
}
@RequestMapping("demoTwo")
public Object demoTwo(){
return 1/0;
}
@RequestMapping("demoThree")
public Object demoThree(){
return new int [-1];
}
}
扫描二维码关注公众号,回复:
3155375 查看本文章
![](/qrcode.jpg)