使用AOP把spring mvc controller方法的参数输出到日志

使用AOP把spring mvc controller方法的参数输出到日志

Advisor
pakcage com.iteye.dwangel.util.spring;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * AOP advicer to get log
 * Created by Simon Xianyu on 2015/11/18 0018.
 */
@Aspect
public class MvcMethodLogAdvice {
  private static Logger log = LoggerFactory.getLogger("com.iteye.dwangel.MVC");

  @Around("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
  public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {

    Object args[] = joinPoint.getArgs();
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    // join arguments.
    log.debug("{}.{} : {} ",method.getDeclaringClass().getName(), method.getName(), StringUtils.join(args," ; "));

    return joinPoint.proceed();
  }
}


spring 的xml配置中增加:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
			http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
			http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
			">

<aop:aspectj-autoproxy />
    <bean id="webMvcAdvisor" class="com.iteye.dwangel.util.spring.MvcMethodLogAdvice" />
</beans>


注意如果有拦截器 interceptor需要访问方法上的自定义 annotation,需要获取target类的方法或者在annotation的定义上 加上 @Inherited

猜你喜欢

转载自dwangel.iteye.com/blog/2257645
今日推荐