标签:aop interceptor 方法拦截器 spring mvc
对每个接口的请求记录log的方法有很多种,比如用filter、mvc interceptor、method interceptor等。如果需要记录请求消息的payload,前两种不适用。下面介绍第三种的实现方法。
第一步:引入包依赖
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span><pre name="code" class="java"> <!-- For AOP --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.6</version> </dependency> <!-- databind会自动引用core和annotations,所以不用声明另外两个 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.3</version> </dependency>
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">(其他log、spring包依赖:略)</span>
第二步:继承org.aopalliance.intercept.MethodInterceptor,实现invoke方法:
/** * 方法拦截器,拦截Controller中的方法,记录log * */ public class ControllerMethodInterceptor implements MethodInterceptor { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final static ObjectMapper jsonMapper = new ObjectMapper(); @Override public Object invoke(MethodInvocation invocation) throws Throwable { logger.info("Before: interceptor name: {}", invocation.getMethod().getName()); logger.info("Arguments: {}", jsonMapper.writeValueAsString(invocation.getArguments())); Object result = invocation.proceed(); logger.info("After: result: {}", jsonMapper.writeValueAsString(result)); return result; } }
<bean id="controllerMethodInterceptor" class="com.xjj.web.interceptor.ControllerMethodInterceptor"/> <!-- 方法拦截器(拦截Controller包中的所有被RequestMapping注解的方法) MethodInterceptor --> <aop:config proxy-target-class="true"> <aop:pointcut id="controllerMethodPointcut" expression="execution(* com.xjj.web.controller..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)"/> <aop:advisor advice-ref="controllerMethodInterceptor" pointcut-ref="controllerMethodPointcut" /> </aop:config>
具体的全部代码请参考:https://github.com/xujijun/MyJavaStudio
(原创文章,转载请注明转自Clement-Xu的博客)
使用方法拦截器MethodInterceptor和AOP统一处理log
标签:aop interceptor 方法拦截器 spring mvc
原文地址:http://blog.csdn.net/clementad/article/details/46474881