好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring BeanUtils忽略空值拷贝的方法示例代码

简介

说明

本文用示例介绍Spring(SpringBoot)如何使用BeanUtils拷贝对象属性(忽略空值)。

BeanUtils类所在的包

有两个包都提供了BeanUtils类:

Spring的(推荐):org.springframework.beans.BeanUtilsApache的:org.apache测试数据mons.beanutils.BeanUtils

忽略null值拷贝属性的用法

?

1

BeanUtils.copyProperties(Object source, Object target, String... ignoreProperties)

获取null属性名(工具类)

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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();

         Set<String> emptyNames = new HashSet<>();

         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

工具类

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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();

         Set<String> emptyNames = new HashSet<>();

         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

基础Entity

?

1

2

3

4

5

6

7

8

9

10

11

12

package com.example.entity;

 

import com.fasterxml.jackson.annotation.JsonFormat;

import lombok.Data;

import java.time.LocalDateTime;

@Data

public class BaseEntity {

     @JsonFormat (pattern = "yyyy-MM-dd HH:mm:ss" ,timezone= "GMT+8" )

     private LocalDateTime createTime;

     private LocalDateTime updateTime;

     private Long deletedFlag;

}

User

?

1

2

3

4

5

6

7

8

9

10

11

package com.example.entity;

 

import lombok.Data;

@Data

public class User {

     private Long id;

     private String userName;

     private String nickName;

     // 0:正常 1:被锁定

     private Integer status;

}

Blog

?

1

2

3

4

5

6

7

8

9

10

11

12

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;

}

VO

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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;

}

Controller

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

package 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;

@RestController

public 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/

后端结果:

?

1

2

3

[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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

<? xml version = "1.0" encoding = "UTF-8" ?>

< project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://HdhCmsTestw3.org/2001/XMLSchema-instance"

          xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 https://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 /> <!-- lookup parent from repository -->

     </ parent >

     < groupId >com.example</ groupId >

     < artifactId >demo_SpringBoot</ artifactId >

     < version >0.0.1-SNAPSHOT</ version >

     < name >demo_SpringBoot</ name >

     < description >Demo project for Spring Boot</ 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 >

其他网址

Spring BeanUtils忽略空值拷贝用法 - 掘金

到此这篇关于Spring BeanUtils忽略空值拷贝的方法示例代码的文章就介绍到这了,更多相关Spring BeanUtils忽略空值拷贝内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/feiying0canglang/article/details/123532488

查看更多关于Spring BeanUtils忽略空值拷贝的方法示例代码的详细内容...

  阅读:20次