业务描述:需要记录系统中谁操作了那个方法,参数是什么,做个简单的日志查看。需要先添加依赖,然后写注解类,配置切面,在启动类启用即可。下面是具体步骤:
如果你喜欢SpringBoot的干货,可以关注我,这都是我工作中用到的技术,我会继续分享的。也欢迎去我个人技术博客,有其他技术资料:https://www.vsalw.com
![67bc5b1025c9608b32a537473f8d01fb.png](https://i-blog.csdnimg.cn/blog_migrate/e8c21f0a1fd12571aa4303331ef33ebb.jpeg)
1.添加依赖,主要是加这2个依赖,日志等依赖根据实际情况添加
org.springframework.boot
spring-boot-starter-aop
org.springframework.boot
spring-boot-starter-web
2.编写注解类Ulog
@Documented
@Target({ElementType.METHOD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface Ulog {
String msg() default “No Msg”;//操作标识,用来表明这个方法是做什么的,会保存在日志里
}
3.编写切面来拦截日志
@Aspect
@Component
public class UlogAspect {
//这里是Ulog注解的路径,注意此方法不能有返回值
@Pointcut(“@annotation(com.redies.demo.log.Ulog)”)
public void annotationPointCut() {
}@Before(“annotationPointCut()”)
public void before(JoinPoint joinPoint) throws UnsupportedEncodingException {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
joinPoint.proceed();//让目标方法执行,具体见下面解释
MethodSignature sign = (MethodSignature)joinPoint.getSignature();
Method method = sign.getMethod();
Ulog ulog=method.getAnnotation(Ulog.class);
System.out.println(“方法名称:”+method.getName());
System.out.println(“方法类型:”+request.getMethod());
System.out.println(“业务标识:”+ulog.msg());
System.out.println(“请求地址:”+request.getRequestURI()+”&”+(request.getQueryString()==null?””: URLDecoder.decode(request.getQueryString(), “UTF-8”)));
}
}
4.启用对切面的支持
在启动类上加注解@EnableAspectJAutoProxy
另外:关于操作人,根据实际登录逻辑添加。环绕通知 ProceedingJoinPoint 执行proceed方法的作用是让目标方法执行,这也是环绕通知和前置、后置通知方法的一个最大区别。简单理解,环绕通知=前置+目标方法执行+后置通知,proceed方法就是用于启动目标方法执行的。