公共字段自动填充

什么是公共字段自动填充呢,那什么又是公共字段呢,所谓的公共字段就是共用同一个数据库字段的变量,比如数据库中有create_time,create_user,update_time和update_user的字段,进行update(即修改信息)和insert(即添加或插入信息)操作时,update操作时需要改变这4个字段,而insert则只需要改变create_time,create_user这两个字段,(更新或插入信息是)后端设置值时是不是时常需要重复使用这些字段,这就会很麻烦,这时候我们就需要写一个注解和类帮我们把这些字段自动填充(即自动识别并补充该字段):

AOP

实现代码前,我们需要知道Spring中AOP(面向切面编程),简单的说,就像给核心流程(如“泡咖啡”)自动添加“插件”:在方法执行的特定节点(如调用前、后),动态插入通用操作(如日志、权限检查),而无需修改原代码,将分散的横切逻辑(如监控、事务)抽离为独立模块,实现解耦和复用。

举个例子

假设你每天都要「泡咖啡」——核心流程是烧水、倒咖啡粉、冲泡,但每次泡咖啡前后你总会自动执行一些重复动作:泡之前检查咖啡豆库存(前置通知),泡之后清洗杯子(后置通知)。Spring AOP 就像给你的生活添加了一个“智能管家”,它会自动在“泡咖啡”这个切入点前后插入检查库存和清洗杯子的操作,而无需你手动写进流程,既保持核心步骤清晰,又能复用通用逻辑(比如泡茶时也能复用检查库存)。

实现公共字段自动填充(示例)

首先创建一个注解(用于识别哪些方法需要处理 ),即切点

package com.sky.annotation;

import com.sky.enumeration.OperationType;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 自定义注解,用于某个方法需要功能字段自动填充处理
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoFill {
    //数据库操作类型:UPDATE,INSERT
    OperationType value();
}

接下来创建类,作为实现的操作,即切面

package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 自定义切面,实现公共字段自动填充逻辑
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    /**
     * 切入点
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut() {}

    /**
     * 前置通知,在通知中进行公共字段的赋值
     */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {
        log.info("开始进行公共字段自动填充...");

        //获取到当前被拦截的方法上的数据库操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法签名对象
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);//获得方法上的注解对象
        OperationType operationType = autoFill.value();//获得数据库操作类型

        //获取到当前被拦截的方法上的参数--实体对象
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }

        Object entity = args[0];
        //准备赋值的数据
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();//这个获取id的方法就是我们之前说的ThreadLocal,如果不了解,可以去我主页看看

        //根据当前不同的操作类型,为对应的属性通过反射来赋值
        if (operationType == OperationType.INSERT) {
            //为4个公共字段赋值
            try {
                Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                //通过反射为对象属性赋值
                setCreateTime.invoke(entity, now);
                setCreateUser.invoke(entity, currentId);
                setUpdateTime.invoke(entity, now);
                setUpdateUser.invoke(entity, currentId);
            } catch (Exception e) {
                e.printStackTrace();
            }


        } else if (operationType == OperationType.UPDATE) {
            //为2个公共字段赋值
            try {
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                //通过反射为对象属性赋值
                setUpdateTime.invoke(entity, now);
                setUpdateUser.invoke(entity, currentId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
    }
}

然后为需要进行操作的方法添加注解,让它(方法)被识别到

最后我们就可以减少很多代码冗余了

### Spring Boot 中实现公共字段自动填充Spring Boot项目中,为了简化代码并减少重复操作,可以采用面向切面编程(AOP)来实现在插入和更新数据库记录时对某些公共字段自动填充。这确保了诸如`create_time`、`update_time`、`creator_id`等字段能够自动且一致地获得初始值或最新时间戳。 #### 添加 AOP 依赖 要启用AOP功能,在项目的`pom.xml`文件里加入如下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> ``` 此依赖项允许定义切面逻辑用于拦截特定的方法调用[^1]。 #### 定义枚举类 `OperateType` 对于不同的业务场景可能需要区分是新增还是修改操作,因此可以通过自定义枚举类型来表示这些情况: ```java public enum OperateType { INSERT, UPDATE; } ``` 该枚举将帮助识别当前正在进行的操作以便于适当地设置相应的时间戳或其他属性。 #### 创建注解 @AutoFill 为了让开发者能够在Mapper接口的方法上标记哪些应该触发自动填充行为,建议创建一个新的自定义注解: ```java @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface AutoFill { OperateType value(); } ``` 这个简单的注解接收一个参数指定是要处理插入还是更新事件。 #### 编写 Aspect 切片 最后一步就是编写实际执行自动填充工作的Aspect组件。这里假设有一个名为`BaseEntity`的基础实体基类包含了所有待填充值的字段,则可以在切面前置通知内完成具体工作: ```java @Component @Aspect @Slf4j public class AutoFillAspect { @Pointcut("@annotation(com.example.demo.annotation.AutoFill)") public void autoFill() {} @Before("autoFill()") public void doAutoFill(JoinPoint joinPoint){ Object[] args = joinPoint.getArgs(); Arrays.stream(args).forEach(arg -> { if (arg instanceof BaseEntity) { BaseEntity baseEntity = (BaseEntity)arg; MethodSignature signature = (MethodSignature)joinPoint.getSignature(); Method method = signature.getMethod(); AutoFill annotation = method.getDeclaredAnnotation(AutoFill.class); OperateType operateType = annotation.value(); switch (operateType) { case INSERT: baseEntity.setCreateTime(new Date()); baseEntity.setUpdateTime(baseEntity.getCreateTime()); break; case UPDATE: baseEntity.setUpdateTime(new Date()); break; } } }); log.info("Automatically filled common fields."); } } ``` 上述代码片段展示了如何利用反射机制访问目标对象及其方法上的元数据,并据此调整实例变量的内容以反映最新的时间和状态变化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值