SpringMVC中使用AOP环绕方式记录日志
第一步,加入相关jar包(当然还用到log4j相关jar包,这里未列出)
<dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.5.3</version> </dependency> <dependency> <groupId>aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.5.3</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.2.0</version> </dependency>
第二步,要让Spring MVC支持AOP,在其配置文件中加入CGLib动态代理
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
第三步,修改SpringMVC配置文件的beans声明,加入
xmlns:aop="http://www.springframework.org/schema/aop 和
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
加入后:
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
第四步,编写切面bean
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
/**
* 日志服务
* @author zain
*
*/
@Aspect
@Component
public class LogServer {
private static Logger logger = Logger.getLogger(LogServer.class);
@Resource
private ApiLogsService apiLogsService;
/**
* 拦截指定的方法,环绕的形式。
* @param context
* @return
* @throws Throwable
*/
@Around(value = "execution(public * com.xxx.xxxx.controller..*.*(..))")
public Object invoke(ProceedingJoinPoint context) throws Throwable {
Object result = null;
try {
apiLogsService.logRequest(); //记录请求内容
result = context.proceed(); //执行目标方法
Response response = LogUtils.parseCustomResponse(result);
apiLogsService.logResponse(response); //记录返回内容
} catch (Exception e) {
logger.error(e);
apiLogsService.logException(e);
throw e;
} finally {
apiLogsService.logFinish();
}
return result;
}
}

浙公网安备 33010602011771号