Spring BeanUtils如何忽略空值拷贝
Spring BeanUtils如何忽略空值拷贝
这篇文章主要讲解了“SpringBeanUtils如何忽略空值拷贝”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“SpringBeanUtils如何忽略空值拷贝”吧!
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如何忽略空值拷贝这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是恰卡编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!
推荐阅读
-
Spring Security 实战干货:手把手教你实现JWT Token
-
「web安全」Spring Boot eureka xstream 反序列化
-
spring中的特殊注解@RequiredArgsConstructor怎么用
spring中的特殊注解@RequiredArgsConstructor怎么用...
-
SpringBoot+Spring Security无法实现跨域怎么解决
-
Spring Security基于注解的接口角色访问控制怎么实现
-
Spring代理对象导致的获取不到原生对象注解怎么解决
Spring代理对象导致的获取不到原生对象注解怎么解决本文小编为大...
-
解析Spring漏洞及修复的方法
-
Spring和IDEA为什么都不推荐使用@Autowired注解
-
Spring中Spring Boot与Spring MVC的核心概念是什么
-
如何使用Spring Expression Language