How to deal with common public fields in daily business

How to deal with common public fields in daily business

In daily business processing, common businesses such as adding or modifying often need to assign and update some commonly used fields that have nothing to do with business. In order to facilitate code development, you can use a face-to-face approach to unify them , Simplify the development of the basic code, which is more conducive to the specification of the project and the maintenance of the code

1 Overview Operation

Build an ordinary Spring Boot project, which can start normally.

User class

@Data
public class User{
    
    
    // id
   private String id; 
    // 姓名
   private String name; 
    // 创建人
   private String crtUser; 
    // 创建时间
   private Date crtTime; 
    // 更新人
   private String updUser; 
    // 更新时间
   private Date updTime; 

}

Create

@Target(ElementType.METHOD) // 适用于方法上
@Retention(RetentionPolicy.RUNTIME) // 适用在运行时
@Documented //  是java 在生成文档,是否显示注解的开关 (加上则有)
public @interface Create {
    
    

}

Update

@Target(ElementType.METHOD) // 适用于方法上
@Retention(RetentionPolicy.RUNTIME) // 适用在运行时
@Documented //  是java 在生成文档,是否显示注解的开关 (加上则有)
public @interface Update {
    
    

}

Aspect analysis class

@Component
@Aspect
@Slf4j
public class ObjectAspect {
    
    

    // id
    private String ID = "id";

    // 创建人
    private String CRT_USER = "crtUser";

    // 创建时间
    private String CRT_TIME = "crtTime";

    // 更新时间
    private String UPD_TIME = "updTime";

    // 更新人
    private String UPD_USER = "updUser";



    // 添加切点, 关联注解, 多个注解 使用加号拼加 和 ||
    @Pointcut("@annotation(com.cf.easyexcel.annotation.Create)" +
            "|| @annotation(com.cf.easyexcel.annotation.Update)")
    public void pointCut() {
    
    
    }


    @Before("pointCut()")
    public void around(JoinPoint joinPoint) {
    
    
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        Create create = method.getAnnotation(Create.class);
        Update update = method.getAnnotation(Update.class);

        if (create != null) {
    
    
            this.create(joinPoint);
        }

        if (update != null) {
    
    
            this.update(joinPoint);
        }


    }

    /**
     * 对象更新时添加属性
     */
    private void update(JoinPoint joinPoint) {
    
    
        Object[] args = joinPoint.getArgs();
        if (args != null && args.length > 0) {
    
    
            Object arg = args[0];
            // 获取系统上下文对象 获取用户名
            String userName = "xXX";
            // 获取当前日期
            Date date = new Date();

            // 修改人属性
            try {
    
    
                Field updUser = arg.getClass().getDeclaredField(UPD_USER);
                updUser.setAccessible(true);
                updUser.set(arg, userName);
            } catch (NoSuchFieldException | IllegalAccessException e) {
    
    
                log.info("{} 属性赋值错误  ", UPD_USER);
            }

            // 修改时间属性
            try {
    
    
                Field updTime = arg.getClass().getDeclaredField(UPD_TIME);
                updTime.setAccessible(true);
                updTime.set(arg, date);
            } catch (NoSuchFieldException | IllegalAccessException e) {
    
    
                log.info("{} 属性赋值错误  ", UPD_TIME);
            }

        }
    }

    /**
     * 对象创建前添加属性
     */
    private void create(JoinPoint joinPoint) {
    
    
        Object[] args = joinPoint.getArgs();
        if (args != null && args.length > 0) {
    
    
            Object arg = args[0];
            // 获取系统上下文对象 获取用户名
            String userName = "xXX";
            // 获取当前日期
            Date date = new Date();

            // id属性
            String uuid = "adbasdfsdfs";
            try {
    
    
                Field id = arg.getClass().getDeclaredField(ID);
                id.setAccessible(true);
                if (id.get(arg) == null || "".equals(id.get(arg))) {
    
    
                    id.set(arg, uuid);
                }

            } catch (NoSuchFieldException | IllegalAccessException e) {
    
    
                log.info("{} 属性赋值错误  ", ID);
            }

            // 创建人属性
            try {
    
    
                Field crtUser = arg.getClass().getDeclaredField(CRT_USER);
                crtUser.setAccessible(true);
                crtUser.set(arg, userName);
            } catch (NoSuchFieldException | IllegalAccessException e) {
    
    
                log.info("{} 属性赋值错误  ", CRT_USER);
            }

            // 创建时间属性
            try {
    
    
                Field crtTime = arg.getClass().getDeclaredField(CRT_TIME);
                crtTime.setAccessible(true);
                crtTime.set(arg, date);
            } catch (NoSuchFieldException | IllegalAccessException e) {
    
    
                log.info("{} 属性赋值错误  ", CRT_TIME);
            }

        }

    }

}

Controller class

@RestController
@RequestMapping("/test")
@Slf4j
public class EasyExcelController {
    
    
    
    @Create
    @PostMapping("/add")
    public void add(@RequestBody User user) throws IOException {
    
    
        String id = user.getId();

        log.info("初始化对象为 add = {}", user);
    }

    @Update
    @PostMapping("/update")
    public void update(@RequestBody User user) throws IOException {
    
    
        String id = user.getId();
        log.info("初始化对象为 update = {}", user);
    }
}

2 tests

Start the service locally and use postman for testing.

create test

Local access:

http:localhost:8080/test/add

operation result:

初始化对象为 add = User(id=adbasdfsdfs, name=null, crtUser=xXX, crtTime=Thu Oct 13 20:21:38 CST 2022, updTime=null, updUser=null)

update test

Local access:

http:localhost:8080/test/update

operation result:

初始化对象为 update = User(id=null, name=null, crtUser=null, crtTime=null, updTime=Thu Oct 13 20:21:38 CST 2022, updUser=xXX)

Guess you like

Origin blog.csdn.net/ABestRookie/article/details/127309549