Aop记录用户操作日志相关依赖
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
自定义注解
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperLog {
String value() default "";
}
创建数据库表和实体
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
@Setter
@Getter
@Entity
@Table(name = "sys_log")
public class SysLog {
@Id
private String id;
private String username;
private String operation;
private Integer time;
private String method;
private String params;
private String ip;
private Date operationTime;
private String url;
}
dao层接口
import org.springframework.data.jpa.repository.JpaRepository;
public interface SysLogDao extends JpaRepository<SysLog,Integer> {
}
访问指定接口时生成日志,保存日志
@Aspect
@Component
@Slf4j
public class OperLogAspect {
@Autowired
private SysLogDao sysLogDao;
@Pointcut("execution(* com.baidu.well.controller.*.*(..))")
public void operLogPoinCut() {
}
@AfterReturning(value = "operLogPoinCut()", returning = "keys")
public void saveOperLog(JoinPoint joinPoint, Object keys) {
long beginTime = System.currentTimeMillis();
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = (HttpServletRequest) requestAttributes
.resolveReference(RequestAttributes.REFERENCE_REQUEST);
SysLog sysLog = new SysLog();
String id = UUID.randomUUID().toString().replace("-", "");
sysLog.setId(id);
try {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
OperLog opLog = method.getAnnotation(OperLog.class);
if (opLog != null) {
String value = opLog.value();
sysLog.setOperation(value);
}
String className = joinPoint.getTarget().getClass().getName();
String methodName = method.getName();
methodName = className + "." + methodName + "()";
sysLog.setMethod(methodName);
String params = getParams(joinPoint, method);
sysLog.setParams(params);
User user = (User) SecurityUtils.getSubject().getPrincipal();
sysLog.setUsername(user.getUserName);
sysLog.setUrl(request.getRequestURL().toString());
sysLog.setIp(IPUtils.getIpAddr(request));
sysLog.setOperationTime(new Date());
sysLog.setTime((int) (System.currentTimeMillis() - beginTime));
sysLogDao.save(sysLog);
} catch (Exception e) {
e.printStackTrace();
}
}
private String getParams(JoinPoint joinPoint, Method method) {
Object[] args = joinPoint.getArgs();
LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
String[] paramNames = u.getParameterNames(method);
String params = null;
if (args != null && paramNames != null) {
for (int i = 0; i < args.length; i++) {
params += " " + paramNames[i] + ": " + args[i];
}
}
return params;
}
}
获取Ip地址的工具类
import javax.servlet.http.HttpServletRequest;
public class IPUtils {
private static final String X_FORWARDED_FOR = "x-forwarded-for";
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader(X_FORWARDED_FOR);
if (ip == null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("Proxy-client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}
}
注意:在Controller接口上添加自定的注解@OperLog,实现记录用户的操作日志
SpringBoot项目启动类添加包扫描的注解
@EnableAspectJAutoProxy(proxyTargetClass=true) 默认值就是true
@SpringBootApplication
@ComponentScan("com.nec.wellness.*")
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class WellnessDbApplication {
public static void main(String[] args) {
SpringApplication.run(WellnessDbApplication.class, args);
}
}