Spring BeanUtils如何忽略空值拷贝

Spring BeanUtils如何忽略空值拷贝

这篇文章主要讲解了“SpringBeanUtils如何忽略空值拷贝”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“SpringBeanUtils如何忽略空值拷贝”吧!

    BeanUtils类所在的包

    Spring BeanUtils如何忽略空值拷贝

    有两个包都提供了BeanUtils类:

    Spring的(推荐):org.springframework.beans.BeanUtilsApache的:org.apache.commons.beanutils.BeanUtils

    忽略null值拷贝属性的用法

    BeanUtils.copyProperties(Objectsource,Objecttarget,String...ignoreProperties)

    获取null属性名(工具类)

    可以自己写一个工具类,用来获取对象里所有null的属性名字。

    packagecom.example.util;importorg.springframework.beans.BeanWrapper;importorg.springframework.beans.BeanWrapperImpl;importjava.beans.PropertyDescriptor;importjava.util.HashSet;importjava.util.Set;publicclassPropertyUtil{publicstaticString[]getNullPropertyNames(Objectsource){BeanWrappersrc=newBeanWrapperImpl(source);PropertyDescriptor[]pds=src.getPropertyDescriptors();Set<String>emptyNames=newHashSet<>();for(PropertyDescriptorpd:pds){//checkifvalueofthispropertyisnullthenaddittothecollectionObjectsrcValue=src.getPropertyValue(pd.getName());if(srcValue==null){emptyNames.add(pd.getName());}}String[]result=newString[emptyNames.size()];returnemptyNames.toArray(result);}}

    示例

    本处为了全面,将以下几种情况都考虑进去:

    • 继承了某个类

    • 某个属性是个Entity

    工具类

    packagecom.example.util;importorg.springframework.beans.BeanWrapper;importorg.springframework.beans.BeanWrapperImpl;importjava.beans.PropertyDescriptor;importjava.util.HashSet;importjava.util.Set;publicclassPropertyUtil{publicstaticString[]getNullPropertyNames(Objectsource){BeanWrappersrc=newBeanWrapperImpl(source);PropertyDescriptor[]pds=src.getPropertyDescriptors();Set<String>emptyNames=newHashSet<>();for(PropertyDescriptorpd:pds){//checkifvalueofthispropertyisnullthenaddittothecollectionObjectsrcValue=src.getPropertyValue(pd.getName());if(srcValue==null){emptyNames.add(pd.getName());}}String[]result=newString[emptyNames.size()];returnemptyNames.toArray(result);}}

    Entity

    基础Entity

    packagecom.example.entity;importcom.fasterxml.jackson.annotation.JsonFormat;importlombok.Data;importjava.time.LocalDateTime;@DatapublicclassBaseEntity{@JsonFormat(pattern="yyyy-MM-ddHH:mm:ss",timezone="GMT+8")privateLocalDateTimecreateTime;privateLocalDateTimeupdateTime;privateLongdeletedFlag;}

    User

    packagecom.example.entity;importlombok.Data;@DatapublicclassUser{privateLongid;privateStringuserName;privateStringnickName;//0:正常1:被锁定privateIntegerstatus;}

    Blog

    packagecom.example.entity;importlombok.Data;importlombok.EqualsAndHashCode;@Data@EqualsAndHashCode(callSuper=true)publicclassBlogextendsBaseEntity{privateLongid;privateStringtitle;privateStringcontent;privateUseruser;}

    VO

    packagecom.example.vo;importcom.example.entity.BaseEntity;importcom.example.entity.User;importlombok.Data;importlombok.EqualsAndHashCode;@Data@EqualsAndHashCode(callSuper=true)publicclassBlogRequestextendsBaseEntity{privateLongid;privateStringtitle;privateStringcontent;privateUseruser;}

    Controller

    packagecom.example.controller;importcom.example.entity.Blog;importcom.example.entity.User;importcom.example.util.PropertyUtil;importcom.example.vo.BlogRequest;importcom.fasterxml.jackson.core.JsonProcessingException;importcom.fasterxml.jackson.databind.ObjectMapper;importorg.springframework.beans.BeanUtils;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RestController;importjava.time.LocalDateTime;importjava.util.Arrays;@RestControllerpublicclassHelloController{@AutowiredprivateObjectMapperobjectMapper;@GetMapping("/test")publicStringtest(){BlogRequestblogRequest=newBlogRequest();blogRequest.setId(10L);blogRequest.setTitle("Java实战");//blogRequest.setContent("本文介绍获取null的字段名的方法");blogRequest.setUser(newUser());blogRequest.setCreateTime(LocalDateTime.now());//blogRequest.setCreateTime(LocalDateTime.now());blogRequest.setDeletedFlag(0L);Useruser=newUser();user.setId(15L);user.setUserName("Tony");//user.setNickName("IronMan");//user.setStatus(1);String[]nullPropertyNames=PropertyUtil.getNullPropertyNames(blogRequest);System.out.println(Arrays.toString(nullPropertyNames));System.out.println("------------------------------");Blogblog=newBlog();BeanUtils.copyProperties(blogRequest,blog,nullPropertyNames);try{System.out.println(objectMapper.writeValueAsString(blog));}catch(JsonProcessingExceptione){e.printStackTrace();}return"testsuccess";}}

    测试

    访问:http://localhost:8080/test/

    后端结果:

    [updateTime,content]------------------------------{"createTime":"2022-03-1719:58:32","updateTime":null,"deletedFlag":0,"id":10,"title":"Java实战","content":null,"user":{"id":null,"userName":null,"nickName":null,"status":null}}

    结论

    • 可以获取父类的null的属性名

    • 不可以获取属性的null的属性名

    其他文件

    pom.xml

    <?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.0.RELEASE</version><relativePath/><!--lookupparentfromrepository--></parent><groupId>com.example</groupId><artifactId>demo_SpringBoot</artifactId><version>0.0.1-SNAPSHOT</version><name>demo_SpringBoot</name><description>DemoprojectforSpringBoot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.16.20</version><scope>provided</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.3.0.RELEASE</version></plugin></plugins></build></project>

    感谢各位的阅读,以上就是“SpringBeanUtils如何忽略空值拷贝”的内容了,经过本文的学习后,相信大家对SpringBeanUtils如何忽略空值拷贝这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是恰卡编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

    发布于 2022-03-18 22:50:11
    收藏
    分享
    海报
    0 条评论
    29
    上一篇:如何使用C++实现酒店管理系统 下一篇:Python代码实现各种酷炫功能的示例分析
    目录

      0 条评论

      本站已关闭游客评论,请登录或者注册后再评论吧~

      忘记密码?

      图形验证码