前言
记录用户全流程操作日志,网上搜了搜,参考着写了下,使用Spring Aop和自定义注解完成,参考博客见最后,感谢。
正文
自定义注解
/**
* @program: springaop
* @description 自定义注解,作用于方法,运行时有效
* @author: jjh
* @create: 2020-05-16
**/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface LogAnnotation {
//模块名称
String moudleName() default "";
//操作内容
String option() default "";
}
要记录操作的模块
定义一个用户管理模块接口UserManager
/**
* @program: springaop
* @description
* @author: jjh
* @create: 2020-05-16
**/
public interface UserManager {
/**
* 添加了一个用户
*/
public void addUser();
/**
* 添加一个角色
*/
public void addRole();
}
实现类 UserManagerImpl
/**
* @program: springaop
* @description
* @author: jjh
* @create: 2020-05-16
**/
@Component("usrmanageraction")
public class UserManagerImpl implements UserManager {
@LogAnnotation(moudleName = "用户管理模块", option = "添加用户")
@Override
public void addUser() {
//假装执行了用户添加操作
System.out.println("添加了一个用户");
}
@LogAnnotation(moudleName = "用户管理模块", option = "添加用户")
@Override
public void addRole() {
//假装添加了一个角色
System.out.println("添加了一个角色");
}
}
定义切面类
/**
* @program: springaop
* @description 切面类,用于记录用户操作后日志
* @author: jjh
* @create: 2020-05-16
**/
@Aspect
@Component
public class LogInterceptor {
/**
* 定义用户管理模块的切点
*/
@Pointcut("execution(* com.jjh.testoperation..*.*(..))")
public void userManagerPointcut(){
}
@After("userManagerPointcut()")
public void afterLog(JoinPoint joinPoint) throws NoSuchMethodException {
//用的最多通知的签名
Signature signature = joinPoint.getSignature();
MethodSignature msg=(MethodSignature) signature;
Object target = joinPoint.getTarget();
//获取注解标注的方法
Method method = target.getClass().getMethod(msg.getName(), msg.getParameterTypes());
//通过方法获取到自定义的注解
LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
//记录日志 看实际情况,日志存表入库
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(format.format(new Date())
+ " " + annotation.moudleName() + " " + annotation.option());
}
}
测试
/**
* @program: springaop
* @description
* @author: jjh
* @create: 2020-05-16
**/
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserManagerImpl userManager = (UserManagerImpl) ac.getBean("usrmanageraction");
userManager.addRole();
userManager.addUser();
}
}
由于我这就是几个java文件,没有用户,所以也就不能记录了,记录用户可参考最后的第一个参考博客。
最后
参考博客: