1、增加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>${spring-version}</version>
</dependency>
2、自定义注解类
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AfLog {
//模块名
String module() default "";
//具体操作
String operation() default "";
}
3、定义切面类
@Aspect
@Component
public class LogAspect {
@Resource
private LogService logService;
@Pointcut("@annotation(com.gebiafu.log.AfLog)")
public void logPointcut() {}
@After("logPointcut() && @annotation(afLog)")
private void handleLog(JoinPoint joinPoint,AfLog afLog) {
//日志实体,用来保存到数据库
LogEntity logEntity = new LogEntity();
//获取模块信息
logEntity.setModule(afLog.module());
//获取操作信息
logEntity.setOperation(afLog.operation());
//记录时间
logEntity.setOperateTime(new Date());
logService.save(logEntity);
}
}
4、日志实体
@Data
@TableName("t_af_log")
public class LogEntity implements Serializable {
@TableId(type = IdType.ASSIGN_ID)
private String id;
private String module;
private String operation;
@TableField("operate_time")
private Date operateTime;
}