SpringBoot@Aspect 打印访问请求和返回数据
为什么要用aspect, 使用aspect 可以使记录日志的功能面向切面,这样可以降低代码的耦本文来源gaodaima#com搞(代@码$网6合性。提供了两种方式对输入输出的数据进行打日志,如下:
aspect:第一种方式
@Before 和 @AfterReturning 来对 controller 进行切面。
输出数据:
aspect:第二种方式
@Around 来对controller 进行切面。
输出数据:
两种方法都是能够对请求数据做日志监控。
第一种方式和第二种方式有一些不同,第二种方式使用的是@Around 环绕的方式去做的处理,joinPoint.proceed()返回数据需要等方法执行完才能执行下面的代码,这种是阻塞式的请求,所以个人建议还是采用第一种方法比较合适。
SpringBoot @Aspect注解详情
1、添加maven依赖注解
<!--springBoot的aop--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
2、添加AOP类
@Component @Aspect public class JournalServiceAspect { }
3、设置切面点
/**切面点*/ private final String POINT_CUT = "execution(* com.xx.xx..*(..))"; @Pointcut(POINT_CUT) private void pointcut(){}
4、配置前置通知
/** * 前置通知,方法调用前被调用 * @param joinPoint */ @Before(value = POINT_CUT) public void before(JoinPoint joinPoint){ logger.info("前置通知"); //获取目标方法的参数信息 Object[] obj = joinPoint.getArgs(); //AOP代理类的信息 joinPoint.getThis(); //代理的目标对象 joinPoint.getTarget(); //用的最多 通知的签名 Signature signature = joinPoint.getSignature(); //代理的是哪一个方法 logger.info("代理的是哪一个方法"+signature.getName()); //AOP代理类的名字 logger.info("AOP代理类的名字"+signature.getDeclaringTypeName()); //AOP代理类的类(class)信息 signature.getDeclaringType(); //获取RequestAttributes RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); //从获取RequestAttributes中获取HttpServletRequest的信息 HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST); //如果要获取Session信息的话,可以这样写: //HttpSession session = (HttpSession) requestAttributes.resolveReference(RequestAttributes.REFERENCE_SESSION); //获取请求参数 Enumeration<String> enumeration = request.getParameterNames(); Map<String,String> parameterMap = Maps.newHashMap(); while (enumeration.hasMoreElements()){ String parameter = enumeration.nextElement(); parameterMap.put(parameter,request.getParameter(parameter)); } String str = JSON.toJSONString(parameterMap); if(obj.length > 0) { logger.info("请求的参数信息为:"+str); } }