什么是AOP?AOP使用场景?AOP相关概念?Spring AOP组件?如何使用Spring AOP?等等这些问题请参考博文:Spring AOP 实现原理
下面重点介绍如何写事件日志功能,把日志保存到数据库中。
事件日志是与主业务功能无关的逻辑,用AOP实现是再好不过了,其中因为有些数据库日志表中的字段参数需要传递,所以会用到自定义注解,将这些参数用自定义注解传递过来。
1.自定义注解Operation
package com.jykj.demo.filter;
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;
/**
* @Descrption该注解描述方法的操作类型和方法的参数意义
*/
@Target(value = ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
public @interface Operation {
/**
* @Description描述操作类型 为必填项,1:登录日志2:操作日志
*/
int type();
/**
* @Description描述操作意义 比如申报通过或者不通过等
*/
String desc() default "";
/**
* @Description描述操作方法的参数意义 数组长度需与参数长度一致,否则会参数与描述不一致的情况
*/
String[] arguDesc() default {};
}
2.切面类EventLogAspect
package com.jykj.demo.filter;
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import com.jykj.demo.service.SysEventService;
//事件日志 切面,凡是带有 @Operation 注解的service方法都将会写日志
public class EventLogAspect {
@Autowired
SysEventService sysEventService;
public void doAfterReturning(JoinPoint jp) {
System.out.println(
"log Ending method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());
Method proxyMethod = ((MethodSignature) jp.getSignature())