2017-06-20 59 views
0
提供BeanUtils.copyProperties一个Builder

我想一个POJO对象的属性复制到另一个不可变对象的生成器,像这样:复制性能与春天

public class CopyTest { 

    // the source object 
    public static class Pojo1 { 
     private int value; 

     public int getValue() { 
      return value; 
     } 

     public void setValue(int value) { 
      this.value = value; 
     } 
    } 

    // the target object 
    public static class Pojo2 { 
     private final int value; 

     public Pojo2(int value) { 
      this.value = value; 
     } 

     public int getValue() { 
      return value; 
     } 

     public static Pojo2Builder builder() { 
      return new Pojo2Builder(); 
     } 

     // builder of the target object, maybe generated by lombok 
     public static class Pojo2Builder { 
      private int value; 

      private Pojo2Builder() {} 

      public Pojo2Builder value(int value) { 
       this.value = value; 
       return this; 
      } 

      public Pojo2 build() { 
       return new Pojo2(value); 
      } 
     } 
    } 

    public static void main(String[] args) { 

     Pojo1 src = new Pojo1(); 
     src.setValue(1); 

     Pojo2.Pojo2Builder builder = Pojo2.builder(); 

     // this won't work, provided by spring-beans 
     BeanUtils.copyProperties(src, builder); 

     Pojo2 target = builder.build(); 
    } 

} 

的问题是: BeanUtils.copyProperties()spring-beans提供不会拨打Pojo2Builder.value(int),因为它不是setter;

除了生成器类通常是由lombok生成所以无法命名方法Pojo2Builder.value(int)作为Pojo2Builder.setValue(int)

顺便说一句,我已经做了它使用注册一个定制的BeanIntrospector由阿帕奇百科全书提供commons-beanutilsBeanUtilsBean.copyProperties(),但我发现使用commons-beanutils复制性能比使用spring-beans当拷贝中的两个不同之间发生的贵得多类,所以我更喜欢做这个使用spring-beans

所以是有可能的属性复制到生成器类与Spring或其他一些公用事业这比commons-beanutils更有效率?

回答

0

您不仅需要更改方法名称,而且还需要将其返回类型更改为void(对于构建器而言非常愚蠢)。添加@Setter注释会有所帮助,if it was allowed

如果您需要将值复制到同一班级的构建器中,则可以使用Lombok的toBuilder()。或者使用@Wither直接创建对象。

如果你需要坚持使用bean的约定,那么你可能运气不好。考虑使用mapstruct,这应该更灵活。

1

如果构建器不遵循bean约定,那么它不会使用bean实用程序。

请更改构建器或编写自己的复制实用程序。