当前位置: 代码网 > it编程>编程语言>Java > 基于SpringBoot实现自动数据变更追踪需求

基于SpringBoot实现自动数据变更追踪需求

2025年10月12日 Java 我要评论
在企业级应用中,关键配置、业务数据变更的审计追踪是一个常见需求。无论是金融系统、电商平台还是配置管理,都需要回答几个基本问题:谁改了数据、什么时候改的、改了什么。背景痛点传统手工审计的问题最直接的实现

在企业级应用中,关键配置、业务数据变更的审计追踪是一个常见需求。无论是金融系统、电商平台还是配置管理,都需要回答几个基本问题:谁改了数据、什么时候改的、改了什么。

背景痛点

传统手工审计的问题

最直接的实现方式是在每个业务方法中手动记录审计日志:

public void updateprice(long productid, bigdecimal newprice) {
    product old = productrepository.findbyid(productid).get();
    productrepository.updateprice(productid, newprice);

    // 手动记录变更
    auditservice.save("价格从 " + old.getprice() + " 改为 " + newprice);
}

这种做法在项目初期还能应付,但随着业务复杂度增加,会暴露出几个明显问题:

代码重复:每个需要审计的方法都要写类似逻辑

维护困难:业务字段变更时,审计逻辑需要同步修改

格式不统一:不同开发者写的审计格式可能不一致

查询不便:字符串拼接的日志难以进行结构化查询

业务代码污染:审计逻辑与业务逻辑耦合在一起

实际遇到的问题

  • 产品价格改错了,查了半天日志才找到是谁改的
  • 配置被误删了,想恢复时发现没有详细的变更记录
  • 审计要求越来越严格,手工记录的日志格式不规范

需求分析

基于实际需求,审计功能应具备以下特性:

核心需求

1. 零侵入性:业务代码不需要关心审计逻辑

2. 自动化:通过配置或注解就能启用审计功能

3. 精确记录:字段级别的变更追踪

4. 结构化存储:便于查询和分析的格式

5. 完整信息:包含操作人、时间、操作类型等元数据

技术选型考虑

本方案选择使用 javers 作为核心组件,主要考虑:

  • 专业的对象差异比对算法
  • spring boot 集成简单
  • 支持多种存储后端
  • json 输出友好

设计思路

整体架构

我们采用 aop + 注解的设计模式:

┌─────────────────┐
│   controller    │
└─────────┬───────┘
          │ aop 拦截
┌─────────▼───────┐
│     service     │ ← 业务逻辑保持不变
└─────────┬───────┘
          │
┌─────────▼───────┐
│   auditaspect   │ ← 统一处理审计逻辑
└─────────┬───────┘
          │
┌─────────▼───────┐
│   javers core   │ ← 对象差异比对
└─────────┬───────┘
          │
┌─────────▼───────┐
│  audit storage  │ ← 结构化存储
└─────────────────┘

核心设计

1. 注解驱动:通过 @audit 注解标记需要审计的方法

2. 切面拦截:aop 自动拦截带注解的方法

3. 差异比对:使用 javers 比较对象变更

4. 统一存储:审计日志统一存储和查询

关键代码实现

项目依赖

<dependencies>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-aop</artifactid>
    </dependency>
    <dependency>
        <groupid>org.javers</groupid>
        <artifactid>javers-core</artifactid>
        <version>7.3.1</version>
    </dependency>
    <dependency>
        <groupid>org.projectlombok</groupid>
        <artifactid>lombok</artifactid>
        <optional>true</optional>
    </dependency>
</dependencies>

审计注解

@target(elementtype.method)
@retention(retentionpolicy.runtime)
public @interface audit {
    // id字段名,用于从实体中提取id
    string idfield() default "id";

    // id参数名,直接从方法参数中获取id
    string idparam() default "";

    // 操作类型,根据方法名自动推断
    actiontype action() default actiontype.auto;

    // 操作人参数名
    string actorparam() default "";

    // 实体参数位置
    int entityindex() default 0;

    enum actiontype {
        create, update, delete, auto
    }
}

审计切面

@slf4j
@aspect
@component
@requiredargsconstructor
public class auditaspect {

    private final javers javers;

    // 内存存储审计日志(生产环境建议使用数据库)
    private final list<auditlog> audittimeline = new copyonwritearraylist<>();
    private final map<string, list<auditlog>> auditbyentity = new concurrenthashmap<>();
    private final atomiclong auditsequence = new atomiclong(0);

    // 数据快照存储
    private final map<string, object> datastore = new concurrenthashmap<>();

    @around("@annotation(auditannotation)")
    public object auditmethod(proceedingjoinpoint joinpoint, audit auditannotation) throws throwable {
        methodsignature signature = (methodsignature) joinpoint.getsignature();
        method method = signature.getmethod();
        string[] paramnames = signature.getparameternames();
        object[] args = joinpoint.getargs();

        // 提取实体id
        string entityid = extractentityid(args, paramnames, auditannotation);
        if (entityid == null) {
            log.warn("无法提取实体id,跳过审计: {}", method.getname());
            return joinpoint.proceed();
        }

        // 提取实体对象
        object entity = null;
        if (auditannotation.entityindex() >= 0 && auditannotation.entityindex() < args.length) {
            entity = args[auditannotation.entityindex()];
        }

        // 提取操作人
        string actor = extractactor(args, paramnames, auditannotation);

        // 确定操作类型
        audit.actiontype actiontype = determineactiontype(auditannotation, method.getname());

        // 执行前快照
        object beforesnapshot = datastore.get(buildkey(entityid));

        // 执行原方法
        object result = joinpoint.proceed();

        // 执行后快照
        object aftersnapshot = determineaftersnapshot(entity, actiontype);

        // 比较差异并记录审计日志
        diff diff = javers.compare(beforesnapshot, aftersnapshot);
        if (diff.haschanges() || beforesnapshot == null || actiontype == audit.actiontype.delete) {
            recordaudit(
                entity != null ? entity.getclass().getsimplename() : "unknown",
                entityid,
                actiontype.name(),
                actor,
                javers.getjsonconverter().tojson(diff)
            );
        }

        // 更新数据存储
        if (actiontype != audit.actiontype.delete) {
            datastore.put(buildkey(entityid), aftersnapshot);
        } else {
            datastore.remove(buildkey(entityid));
        }

        return result;
    }

    // 辅助方法:提取实体id
    private string extractentityid(object[] args, string[] paramnames, audit audit) {
        // 优先从方法参数中获取id
        if (!audit.idparam().isempty() && paramnames != null) {
            for (int i = 0; i < paramnames.length; i++) {
                if (audit.idparam().equals(paramnames[i])) {
                    object idvalue = args[i];
                    return idvalue != null ? idvalue.tostring() : null;
                }
            }
        }
        return null;
    }

    // 其他辅助方法...
}

业务服务示例

@service
public class productservice {

    private final map<string, product> products = new concurrenthashmap<>();

    @audit(
            action = audit.actiontype.create,
            idparam = "id",
            actorparam = "actor",
            entityindex = 1
    )
    public product create(string id, productrequest request, string actor) {
        product newproduct = new product(id, request.name(), request.price(), request.description());
        return products.put(id, newproduct);
    }

    @audit(
            action = audit.actiontype.update,
            idparam = "id",
            actorparam = "actor",
            entityindex = 1
    )
    public product update(string id, productrequest request, string actor) {
        product existingproduct = products.get(id);
        if (existingproduct == null) {
            throw new illegalargumentexception("产品不存在: " + id);
        }

        product updatedproduct = new product(id, request.name(), request.price(), request.description());
        return products.put(id, updatedproduct);
    }

    @audit(
            action = audit.actiontype.delete,
            idparam = "id",
            actorparam = "actor"
    )
    public boolean delete(string id, string actor) {
        return products.remove(id) != null;
    }

    @audit(
            idparam = "id",
            actorparam = "actor",
            entityindex = 1
    )
    public product upsert(string id, productrequest request, string actor) {
        product newproduct = new product(id, request.name(), request.price(), request.description());
        return products.put(id, newproduct);
    }
}

审计日志实体

public record auditlog(
        string id,
        string entitytype,
        string entityid,
        string action,
        string actor,
        instant occurredat,
        string diffjson
) {}

javers 配置

@configuration
public class javersconfig {

    @bean
    public javers javers() {
        return javersbuilder.javers()
                .withprettyprint(true)
                .build();
    }
}

应用场景示例

场景1:产品信息更新审计

操作请求

put /api/products/prod-001
content-type: application/json
x-user: 张三

{
  "name": "iphone 15",
  "price": 99.99,
  "description": "最新款手机"
}

审计日志结构

{
  "id": "1",
  "entitytype": "product",
  "entityid": "prod-001",
  "action": "update",
  "actor": "张三",
  "occurredat": "2025-10-12t10:30:00z",
  "diffjson": "{\"changes\":[{\"field\":\"price\",\"oldvalue\":100.00,\"newvalue\":99.99}]}"
}

diffjson 的具体内容

{
  "changes": [
    {
      "changetype": "valuechange",
      "globalid": {
        "valueobject": "com.example.objectversion.dto.productrequest"
      },
      "property": "price",
      "propertychangetype": "property_value_changed",
      "left": 100.00,
      "right": 99.99
    },
    {
      "changetype": "valuechange",
      "globalid": {
        "valueobject": "com.example.objectversion.dto.productrequest"
      },
      "property": "description",
      "propertychangetype": "property_value_changed",
      "left": null,
      "right": "最新款手机"
    }
  ]
}

场景2:完整操作历史查询

get /api/products/prod-001/audits

响应结果

[
  {
    "id": "1",
    "entitytype": "product",
    "entityid": "prod-001",
    "action": "create",
    "actor": "system",
    "occurredat": "2025-10-10t08:00:00z",
    "diffjson": "{\"changes\":[{\"field\":\"name\",\"oldvalue\":null,\"newvalue\":\"iphone 15\"},{\"field\":\"price\",\"oldvalue\":null,\"newvalue\":100.00}]}"
  },
  {
    "id": "2",
    "entitytype": "product",
    "entityid": "prod-001",
    "action": "update",
    "actor": "张三",
    "occurredat": "2025-10-12t10:30:00z",
    "diffjson": "{\"changes\":[{\"field\":\"price\",\"oldvalue\":100.00,\"newvalue\":99.99}]}"
  }
]

场景3:删除操作审计

删除请求

delete /api/products/prod-001
x-user: 李四

审计日志

{
  "id": "3",
  "entitytype": "product",
  "entityid": "prod-001",
  "action": "delete",
  "actor": "李四",
  "occurredat": "2025-10-13t15:45:00z",
  "diffjson": "{\"changes\":[]}"
}

场景4:批量操作审计

创建多个产品

// 执行多次创建操作
productservice.create("prod-002", new productrequest("手机壳", 29.99, "透明保护壳"), "王五");
productservice.create("prod-003", new productrequest("充电器", 59.99, "快充充电器"), "王五");

审计日志

[
  {
    "id": "4",
    "entitytype": "product",
    "entityid": "prod-002",
    "action": "create",
    "actor": "王五",
    "occurredat": "2025-10-13t16:00:00z",
    "diffjson": "{\"changes\":[{\"field\":\"name\",\"oldvalue\":null,\"newvalue\":\"手机壳\"},{\"field\":\"price\",\"oldvalue\":null,\"newvalue\":29.99}]}"
  },
  {
    "id": "5",
    "entitytype": "product",
    "entityid": "prod-003",
    "action": "create",
    "actor": "王五",
    "occurredat": "2025-10-13t16:01:00z",
    "diffjson": "{\"changes\":[{\"field\":\"name\",\"oldvalue\":null,\"newvalue\":\"充电器\"},{\"field\":\"price\",\"oldvalue\":null,\"newvalue\":59.99}]}"
  }
]

总结

通过 javers + aop + 注解的组合,我们实现了一个零侵入的数据变更审计系统。这个方案的主要优势:

开发效率提升:无需在每个业务方法中编写审计逻辑

维护成本降低:审计逻辑集中在切面中,便于统一管理

数据质量改善:结构化的审计日志便于查询和分析

技术方案没有银弹,需要根据具体业务场景进行调整。如果您的项目也有数据审计需求,这个方案可以作为参考。

github.com/yuboon/java-examples/tree/master/springboot-object-version

到此这篇关于基于springboot实现自动数据变更追踪需求的文章就介绍到这了,更多相关springboot数据变更追踪内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com