Spring BeanUtils.copyProperties简化写法

代码

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.util.StopWatch;

public class BeanUtils2 {
  
  
  /**
   * 减少外部调用代码行数,没有其他含义功能
   * Student target = BeanUtils.copyProperties(source, new Student());
   * @param source
   * @param target
   * @param <T>
   * @return
   * @throws BeansException
   */
  public static <T> T copyProperties(Object source, T target) throws BeansException {
    BeanUtils.copyProperties(source, target);
    return target;
  }
  
  public static void main(String[] args) {
    Student source = new Student("name", 10, 170, 100);
    
    
    StopWatch stopWatch = new StopWatch();
    
    stopWatch.start("预热");
    for (int i = 0; i < 1000; i++) {
      Student student = new Student("name", 10, 170, 100);
      Student student1 = copyProperties(student, new Student());
      BeanUtils.copyProperties(source, new Student());
    }
    stopWatch.stop();
    
    stopWatch.start("copy自定义2");
    for (int i = 0; i < 1000000; i++) {
      Student target = copyProperties(source, new Student());
      int age = target.getAge();
    }
    stopWatch.stop();
    
    
    stopWatch.start("原生");
    for (int i = 0; i < 1000000; i++) {
      Student target = new Student();
      BeanUtils.copyProperties(source, target);
      int age = target.getAge();
    }
    stopWatch.stop();
    
    System.out.println(stopWatch.prettyPrint());
  }
  
  @Data
  @AllArgsConstructor
  @NoArgsConstructor
  public static class Student {
    
    private String name;
    
    private int age;
    
    private int height;
    
    private int weight;
    
  }
}

执行时间

时间差不大

-----------------------------------------
ms     %     Task name
-----------------------------------------
00683  063%  预热
00213  020%  copy自定义2
00195  018%  原生


-----------------------------------------
ms     %     Task name
-----------------------------------------
00365  048%  预热
00202  027%  copy自定义2
00188  025%  原生
posted @ 2023-11-10 10:59  BigOrang  阅读(3)  评论(0编辑  收藏  举报