本文用示例介绍Spring(SpringBoot)如何使用BeanUtils拷贝对象属性忽略空置,忽略null值拷贝属性的用法,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下
简介
解释
本文用例子介绍了Spring(SpringBoot)如何使用BeanUtils来复制对象属性(忽略空值)。
Nutils类所在的包。
有两个包提供了BeanUtils类:
Spring的(推荐):org . spring framework . beans . bean utils Apache的:org . Apache . commons . bean utils . bean utils
忽略空值复制属性的使用。
BeanUtils.copyProperties(Object source, Object target, String... ignoreProperties)
获取null属性名(工具类)
您可以自己编写一个工具类来获取对象中所有的空属性名。
package com.example.util; import org.springframework.beans.BeanWrapper;import org.springframework.beans.BeanWrapperImpl;import java.beans.PropertyDescriptor;import java.util.HashSet;import java.util.Set;public class PropertyUtil { public static String[] getNullPropertyNames(Object source) { BeanWrapper src = new BeanWrapperImpl(source); PropertyDescriptor[] pds = src.getPropertyDescriptors(); Setlt;Stringgt; emptyNames = new HashSetlt;gt;(); for (PropertyDescriptor pd : pds) { //check if value of this property is null then add it to the collection Object srcValue = src.getPropertyValue(pd.getName()); if (srcValue == null){ emptyNames.add(pd.getName()); } } String[] result = new String[emptyNames.size()]; return emptyNames.toArray(result); }}
示例
为了全面起见,我们将考虑以下情况:
继承了某个类某个属性是个Entity
工具类package com.example.util; import org.springframework.beans.BeanWrapper;import org.springframework.beans.BeanWrapperImpl;import java.beans.PropertyDescriptor;import java.util.HashSet;import java.util.Set;public class PropertyUtil { public static String[] getNullPropertyNames(Object source) { BeanWrapper src = new BeanWrapperImpl(source); PropertyDescriptor[] pds = src.getPropertyDescriptors(); Setlt;Stringgt; emptyNames = new HashSetlt;gt;(); for (PropertyDescriptor pd : pds) { //check if value of this property is null then add it to the collection Object srcValue = src.getPropertyValue(pd.getName()); if (srcValue == null){ emptyNames.add(pd.getName()); } } String[] result = new String[emptyNames.size()]; return emptyNames.toArray(result); }}
Entity
基本实体
package com.example.entity; import com.fasterxml.jackson.annotation.JsonFormat;import lombok.Data;import java.time.LocalDateTime;@Datapublic class BaseEntity { @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") private LocalDateTime createTime; private LocalDateTime updateTime; private Long deletedFlag;}
用户
package com.example.entity; import lombok.Data;@Datapublic class User { private Long id; private String userName; private String nickName; // 0:正常 1:被锁定 private Integer status;}
博客
package com.example.entity; import lombok.Data;import lombok.EqualsAndHashCode;@Data@EqualsAndHashCode(callSuper = true)public class Blog extends BaseEntity{ private Long id; private String title; private String content; private User user;}
维多利亚皇家勋章
package com.example.vo; import com.example.entity.BaseEntity;import com.example.entity.User;import lombok.Data;import lombok.EqualsAndHashCode;@Data@EqualsAndHashCode(callSuper = true)public class BlogRequest extends BaseEntity { private Long id; private String title; private String content; private User user;}
Controllerpackage com.example.controller; import com.example.entity.Blog;import com.example.entity.User;import com.example.util.PropertyUtil;import com.example.vo.BlogRequest;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.beans.BeanUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import java.time.LocalDateTime;import java.util.Arrays;@RestControllerpublic class HelloController { @Autowired private ObjectMapper objectMapper; @GetMapping("/test") public String test() { BlogRequest blogRequest = new BlogRequest(); blogRequest.setId(10L); blogRequest.setTitle("Java实战"); // blogRequest.setContent("本文介绍获取null的字段名的方法"); blogRequest.setUser(new User()); blogRequest.setCreateTime(LocalDateTime.now()); // blogRequest.setCreateTime(LocalDateTime.now()); blogRequest.setDeletedFlag(0L); User user = new User(); user.setId(15L); user.setUserName("Tony"); // user.setNickName("Iron Man"); // user.setStatus(1); String[] nullPropertyNames = PropertyUtil.getNullPropertyNames(blogRequest); System.out.println(Arrays.toString(nullPropertyNames)); System.out.println("------------------------------"); Blog blog = new Blog(); BeanUtils.copyProperties(blogRequest, blog, nullPropertyNames); try { System.out.println(objectMapper.writeValueAsString(blog)); } catch (JsonProcessingException e) { e.printStackTrace(); } return "test success"; }}
测试
请访问:http://localhost:8080/test/
后端结果:
[updateTime, content]------------------------------{"createTime":"2022-03-17 19: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
lt;xml version="1.0" encoding="UTF-8"gt;lt;project xmlns="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.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"gt; lt;modelVersiongt;4.0.0lt;/modelVersiongt; lt;parentgt; lt;groupIdgt;org.springframework.bootlt;/groupIdgt; lt;artifactIdgt;spring-boot-starter-parentlt;/artifactIdgt; lt;versiongt;2.3.0.RELEASElt;/versiongt; lt;relativePath/gt; lt;!-- lookup parent from repository --gt; lt;/parentgt; lt;groupIdgt;com.examplelt;/groupIdgt; lt;artifactIdgt;demo_SpringBootlt;/artifactIdgt; lt;versiongt;0.0.1-SNAPSHOTlt;/versiongt; lt;namegt;demo_SpringBootlt;/namegt; lt;descriptiongt;Demo project for Spring Bootlt;/descriptiongt; lt;propertiesgt; lt;java.versiongt;1.8lt;/java.versiongt; lt;/propertiesgt; lt;dependenciesgt; lt;dependencygt; lt;groupIdgt;org.springframework.bootlt;/groupIdgt; lt;artifactIdgt;spring-boot-starter-weblt;/artifactIdgt; lt;/dependencygt; lt;dependencygt; lt;groupIdgt;org.projectlomboklt;/groupIdgt; lt;artifactIdgt;lomboklt;/artifactIdgt; lt;versiongt;1.16.20lt;/versiongt; lt;scopegt;providedlt;/scopegt; lt;/dependencygt; lt;/dependenciesgt; lt;buildgt; lt;pluginsgt; lt;plugingt; lt;groupIdgt;org.springframework.bootlt;/groupIdgt; lt;artifactIdgt;spring-boot-maven-pluginlt;/artifactIdgt; lt;versiongt;2.3.0.RELEASElt;/versiongt; lt;/plugingt; lt;/pluginsgt; lt;/buildgt; lt;/projectgt;
其他网址
Spring BeanUtils忽略空值副本使用-掘金
这就是本文关于Spring BeanUtils忽略空值复制的方法示例代码。
精彩评论