用SpringAop实现日志

自定义注解

//注解可以加在什么地方
@Target(value = ElementType.METHOD)
//注解的生命周期
@Retention(value = RetentionPolicy.RUNTIME)
public @interface LogAnnotation {
    String type() default "select";
    String content() default "";
}

在需要生成的方法上添加注解

 @LogAnnotation(type = "select",content = "查询所有品牌")

最后通过aop用注解切入

@Aspect  //这是一个切面
@Configuration  //配置类
public class LogAop {
    @Autowired
    BzLogMapper bzLogMapper;
    @Autowired
    HttpServletRequest request;
   
  //环绕增强
@Around(
"@annotation(com.xx.annotation.LogAnnotation)") public Object logAround(ProceedingJoinPoint joinPoint){ BzAdmin user = (BzAdmin)request.getSession().getAttribute("user"); //username String userName = ""; if (user != null) { userName = user.getUsername(); } //ip 通过工具类 String ip = IPKi.getIpAddrByRequest(request); //获取方法签名 MethodSignature signature =(MethodSignature) joinPoint.getSignature(); //通过方法签名获取方法对象 Method method = signature.getMethod(); //拿到方法名 String methodName = method.getName(); //拿到方法上的注解 LogAnnotation annotation = method.getAnnotation(LogAnnotation.class); //通过注解拿到其中的值 //content String content = annotation.content(); //type String type = annotation.type(); //date Date date = new Date(); //time long l = System.currentTimeMillis(); Object proceed = null; try { proceed = joinPoint.proceed(); } catch (Throwable throwable) { throwable.printStackTrace(); } long l1 = System.currentTimeMillis(); long time = l1 - l; BzLog bzLog = new BzLog(null,userName,ip,type,content,date,methodName,time); bzLogMapper.insert(bzLog); return proceed; } }
原文地址:https://www.cnblogs.com/huahualove/p/13928530.html