springboot切面返回值_SpringBoot系列——aop 面向切面

前言

项目中我们经常会用到aop切面,比如日志记录;这里简单记录一下springboot是如何使用aop

#AOP

spring.aop.auto=true #Add @EnableAspectJAutoProxy.

spring.aop.proxy-target-class=true #Whether subclass-based (CGLIB) proxies are to be created (true), as opposed to standard Java interface-based proxies (false).

maven引包

org.springframework.boot

spring-boot-starter-aop

org.slf4j

slf4j-api

org.slf4j

slf4j-log4j12

Aspect 切面

/*** Aspect 切面

* 日志切面*/@Aspect

@Componentpublic classLogAspect {/*** slf4j日志*/

private final static Logger logger = LoggerFactory.getLogger(LogAspect.class);/*** Pointcut 切入点

* 匹配cn.controller包下面的所有方法*/@Pointcut("execution(public * cn.controller.*.*(..))")public voidwebLog(){}/*** 环绕通知*/@Around(value= "webLog()")publicObject arround(ProceedingJoinPoint pjp) {try{

logger.info("1、Around:方法环绕开始.....");

Object o=pjp.proceed();

logger.info("3、Around:方法环绕结束,结果是 :" +o);returno;

}catch(Throwable e) {

logger.error(pjp.getSignature()+ " 出现异常: ", e);return Result.of(null, false, "出现异常:" +e.getMessage());

}

}/*** 方法执行前*/@Before(value= "webLog()")public voidbefore(JoinPoint joinPoint){

logger.info("2、Before:方法执行开始...");//接收到请求,记录请求内容

ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();assert attributes != null;

HttpServletRequest request=attributes.getRequest();//记录下请求内容

logger.info("URL : " +request.getRequestURL().toString());

logger.info("HTTP_METHOD : " +request.getMethod());

logger.info("IP : " +request.getRemoteAddr());

logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." +joinPoint.getSignature().getName());

logger.info("ARGS : " +Arrays.toString(joinPoint.getArgs()));

}/*** 方法执行结束,不管是抛出异常或者正常退出都会执行*/@After(value= "webLog()")public voidafter(JoinPoint joinPoint){

logger.info("4、After:方法最后执行.....");

}/*** 方法执行结束,增强处理*/@AfterReturning(returning= "ret", pointcut = "webLog()")public voiddoAfterReturning(Object ret){//处理完请求,返回内容

logger.info("5、AfterReturning:方法的返回值 : " +ret);

}/*** 后置异常通知*/@AfterThrowing(value= "webLog()")public voidthrowss(JoinPoint joinPoint){

logger.error("AfterThrowing:方法异常时执行.....");

}

}

效果

访问获取所有用户接口

代码开源

代码已经开源、托管到我的GitHub、码云:

你可能感兴趣的:(springboot切面返回值)