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%  原生
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章