SpringBoot 中日志管理用AOP如何轻松实现
1.项目中导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAnnotation {
String type() default "select";
String content();
}
3.写切面
package com.baizhi.aop;
import cn.hutool.http.server.HttpServerRequest;
import com.baizhi.annotation.LogAnnotation;
import com.baizhi.dao.BzLogMapper;
import com.baizhi.entity.BzAdmin;
import com.baizhi.entity.BzLog;
import com.baizhi.util.IPKit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
@Aspect
@Configuration
public class LogAop {
@Autowired
private BzLogMapper logMapper;
@Autowired
private HttpServletRequest request;
@Around("@annotation(com.baizhi.annotation.LogAnnotation)")
public Object logAround(ProceedingJoinPoint joinPoint){
BzLog bzLog = new BzLog();
bzLog.setLogDate(new Date());
String ipAddrByRequest = IPKit.getIpAddrByRequest(request);
bzLog.setLogIp(ipAddrByRequest);
BzAdmin admin = (BzAdmin) request.getSession().getAttribute("admin");
if (admin != null) {
bzLog.setUsername(admin.getUsername());
}else {
bzLog.setUsername("hhh");
}
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
String type = annotation.type();
bzLog.setLogType(type);
bzLog.setLogContent(annotation.content());
bzLog.setLogMethod(method.toString());
long startTime = System.currentTimeMillis();
Object result = null;
try {
result = joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
long endTime = System.currentTimeMillis();
bzLog.setLogTime((int) (endTime-startTime));
System.out.println(bzLog);
logMapper.insert(bzLog);
return result;
}
}
4.在要记录日志的方法上添加注解

5.启动项目测试