我们有这样子的需求,需要记录用户操作某个方法的信息并记录到日志里面,例如,用户在保存和更新任务的时候,我们需要记录下用户的ip,具体是保存还是更新,调用的是哪个方法,保存和更新的任务名称以及操作是否成功。
这里最好的技术就是spring aop + annotation,首先我来定义个注解类
/**
* 参数命名好麻烦,我就随便了,只是演示下用法
* @author liuxg
* @date 2016年4月13日 上午7:53:52
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Logger {
String param1() default "";
String param2() default "" ;
String param3() default "" ;
String param4() default "" ;
}
然后我们在controller中定义一个方法,即用户具体调用的保存或者更新的方法
@RequestMapping("/mvc24")
@Logger(param1 = "#{task.project.projectName}",param2 = "#{task.taskName}",param3 = "#{name}",param4 = "常量")
public void mvc24(Task task ,String name){
//...
}
在这里我们就可以把参数中的task或者name的相关信息绑定到注解类中
然后我们再定义一个切面,我们就可以动态的获取和处理注解类的一些信息了
/**
* 日志切面
* @author liuxg
* @date 2015年10月13日 下午5:55:44
*/
@Component
@Aspect
public class LoggerAspect {
@Around("@annotation(com.liuxg.logger.annotation.Logger)")
public Object around(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
Method method = methodSignature.getMethod();
Logger logger = (Logger) method.getAnnotation(Logger.class);
Object value1 = AnnotationResolver.newInstance().resolver(joinPoint, logger.param1());
Object value2 = AnnotationResolver.newInstance().resolver(joinPoint, logger.param1());
Object value3 = AnnotationResolver.newInstance().resolver(joinPoint, logger.param1());
Object value4 = AnnotationResolver.newInstance().resolver(joinPoint, logger.param1());
return null ;
}
}
AnnotationResolver是我这边写的一个解析注解类语法的一个解析器,利用该解析器,可以把注解类中这样子的语法直接解析#{方法变量名}
该解析器只有唯一的一个方法
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
/**
* 该类的作用可以把方法上的参数绑定到注解的变量中,注解的语法#{变量名}
* 能解析类似#{task}或者#{task.taskName}或者{task.project.projectName}
*/
public class AnnotationResolver {
private static AnnotationResolver resolver ;
public static AnnotationResolver newInstance(){
if (resolver == null) {
return resolver = new AnnotationResolver();
}else{
return resolver;
}
}
/**
* 解析注解上的值
* @param joinPoint
* @param str 需要解析的字符串
* @return
*/
public Object resolver(JoinPoint joinPoint, String str) {
if (str == null) return null ;
Object value = null;
if (str.matches("#\\{\\D*\\}")) {// 如果name匹配上了#{},则把内容当作变量
String newStr = str.replaceAll("#\\{", "").replaceAll("\\}", "");
if (newStr.contains(".")) { // 复杂类型
try {
value = complexResolver(joinPoint, newStr);
} catch (Exception e) {
e.printStackTrace();
}
} else {
value = simpleResolver(joinPoint, newStr);
}
} else { //非变量
value = str;
}
return value;
}
private Object complexResolver(JoinPoint joinPoint, String str) throws Exception {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
String[] names = methodSignature.getParameterNames();
Object[] args = joinPoint.getArgs();
String[] strs = str.split("\\.");
for (int i = 0; i < names.length; i++) {
if (strs[0].equals(names[i])) {
Object obj = args[i];
Method dmethod = obj.getClass().getDeclaredMethod(getMethodName(strs[1]), null);
Object value = dmethod.invoke(args[i]);
return getValue(value, 1, strs);
}
}
return null;
}
private Object getValue(Object obj, int index, String[] strs) {
try {
if (obj != null && index < strs.length - 1) {
Method method = obj.getClass().getDeclaredMethod(getMethodName(strs[index + 1]), null);
obj = method.invoke(obj);
getValue(obj, index + 1, strs);
}
return obj;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private String getMethodName(String name) {
return "get" + name.replaceFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase());
}
private Object simpleResolver(JoinPoint joinPoint, String str) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
String[] names = methodSignature.getParameterNames();
Object[] args = joinPoint.getArgs();
for (int i = 0; i < names.length; i++) {
if (str.equals(names[i])) {
return args[i];
}
}
return null;
}
}
总结:
使用aop注解方式实现日志记录可以减少代码冗余,降低维护成本。相比于传统的aop取固定入参,动态注解方式可以降低代码侵入,使用简单、取值方便。