spring boot 添加aop功能
来源:互联网 发布:关于护肤的软件 编辑:程序博客网 时间:2024/06/15 07:34
spring aop 具体的定义自己百度,这里只简单说下spring boot 添加aop功能
aop一般会用来和memcached一起做缓存,方法执行时间统计,还有日志的跟踪等等。
首先引入aop的起始依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
然后配置文件把aop打开即可
spring: aop: auto: true
上面是.yml的配置方法,如果是用的properties
spring.aop.auto= true
这样就可以了,剩下的就和spring中的一样了
package com.example.controller;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.aspectj.lang.reflect.MethodSignature;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import org.springframework.util.StopWatch;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.lang.reflect.Method;import java.util.LinkedHashSet;import java.util.Map;import java.util.Set;/** * Created by mazhenhua on 2017/1/4. */@Aspect@Componentpublic class AopControll { private static final Logger logger = LoggerFactory.getLogger(AopControll.class); /** * 定义拦截规则:拦截com.example.controller包下面的所有类中,有@RequestMapping注解的方法。 */ @Pointcut("execution(* com.example.controller..*(..)) && @annotation(org.springframework.web.bind.annotation.RequestMapping)") public void controllerMethodPointcut(){} /** * 环绕通知 * @param pjp * @return */ @Around("controllerMethodPointcut()") public Object Interceptor(ProceedingJoinPoint pjp){ StopWatch clock = new StopWatch(); clock.start(); MethodSignature signature = (MethodSignature) pjp.getSignature(); Method method = signature.getMethod(); String methodName = method.getName(); Set<Object> allParams = new LinkedHashSet<>(); logger.info("请求开始,方法:{}", methodName); Object result = null; Object[] args = pjp.getArgs(); for(Object arg : args){ if (arg instanceof Map<?, ?>) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) arg; allParams.add(map); }else if(arg instanceof HttpServletRequest){ HttpServletRequest request = (HttpServletRequest) arg; Map<String, String[]> paramMap = request.getParameterMap(); if(paramMap!=null && paramMap.size()>0){ allParams.add(paramMap); } }else if(arg instanceof HttpServletResponse){ }else{ } } try { if(result == null){ result = pjp.proceed(); } } catch (Throwable e) { logger.info("exception: ", e); } clock.stop(); logger.info("{}请求结束,耗时:{}ms", methodName, clock.getTotalTimeMillis()); return result; }}