Spring AOP 实现日志记录
一. 功能要点
自定义注解用于描述某个记录日志的操作说明,再使用AOP获取这个操作说明及入参参数,将其记录在日志里。
二、自定义注解@Log
@Log主要用于定义切入点标识及操作说明
package com.test.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 日志记录
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
/** 操作内容 */
String value() default "";
}
三、日志业务处理
package com.test.aspect;
import com.test.entity.Admin;
import com.test.entity.Log;
import com.test.service.AdminService;
import com.test.service.LogService;
import com.test.utils.JsonUtils;
import com.test.utils.WebUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
/**
* 日志记录
*/
@Aspect
@Component
public class LogAspect {
@Autowired
private LogService logService;
@Autowired
private AdminService adminService;
@AfterReturning("@annotation(com.test.annotation.Log)")
public void afterReturning(JoinPoint joinPoint) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//获取当前登录用户
Admin admin = adminService.getCurrent();
if (admin == null) {
admin = adminService.getAppCurrent();
if (admin == null) {
return;
}
}
//日志记录
Log log = new Log();
log.setIp(WebUtils.getRemoteIp(request));
log.setOperator(admin.getUsername());
StringBuilder arg = new StringBuilder();
//获取切点的参数
for (Object object : joinPoint.getArgs()) {
if (object instanceof MultipartFile) {
MultipartFile file = (MultipartFile) object;
arg.append("{uploadFile:").append(file.getOriginalFilename()).append("}").append(";");
} else if (object instanceof RedirectAttributes) {
continue;
} else if (object instanceof ModelMap) {
continue;
} else {
try {
arg.append(JsonUtils.toJson(object)).append(";");
} catch (Exception e) {
}
}
}
log.setParameter(arg.toString());
log.setParameter(arg.toString());
try {
//获取切点自定义Log注解的参数
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
log.setOperation(method.getAnnotation(com.test.annotation.Log.class).value());
logService.save(log);
} catch (Exception e) {
// e.printStackTrace();
}
}
}
四、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:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd"
default-lazy-init="true">
<!-- 扫描组件 -->
<context:component-scan base-package="com.test" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
<!-- 启动对@AspectJ注解的支持 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
...
</beans>
五、应用
@Log("档案资料添加")
@RequestMapping(value = "/add/{vehicleRentalId}", method = RequestMethod.POST)
public String archiveAdd(@PathVariable Long vehicleRentalId, String type, MaterialCategory category, MultipartFile material, RedirectAttributes redirectAttributes){
...
addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
return INDEX_REDIRECT_URL + "/archive_detail/" + vehicleRentalId;
}