溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Spring?BeanUtils如何忽略空值拷貝

發布時間:2022-03-18 13:35:02 來源:億速云 閱讀:347 作者:iii 欄目:開發技術

這篇文章主要講解了“Spring BeanUtils如何忽略空值拷貝”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Spring BeanUtils如何忽略空值拷貝”吧!

    BeanUtils類所在的包

    有兩個包都提供了BeanUtils類:

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

    忽略null值拷貝屬性的用法

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

    獲取null屬性名(工具類)

    可以自己寫一個工具類,用來獲取對象里所有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();
            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

    工具類

    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

    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

    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

    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

    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

    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/

    后端結果:

    [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

    <?xml version="1.0" encoding="UTF-8"?>
    <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">
        <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如何忽略空值拷貝這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!

    向AI問一下細節

    免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

    AI

    亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女