欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring BeanUtils忽略空值拷貝的方法示例代碼

 更新時間:2022年03月18日 11:46:35   作者:IT利刃出鞘  
本文用示例介紹Spring(SpringBoot)如何使用BeanUtils拷貝對象屬性忽略空置,忽略null值拷貝屬性的用法,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧

簡介

說明

本文用示例介紹Spring(SpringBoot)如何使用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

基礎(chǔ)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實戰(zhàn)");
        // 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/

后端結(jié)果:

[updateTime, content]
------------------------------
{"createTime":"2022-03-17 19:58:32","updateTime":null,"deletedFlag":0,"id":10,"title":"Java實戰(zhàn)","content":null,"user":{"id":null,"userName":null,"nickName":null,"status":null}}

結(jié)論

  • 可以獲取父類的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>

其他網(wǎng)址

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

到此這篇關(guān)于Spring BeanUtils忽略空值拷貝的方法示例代碼的文章就介紹到這了,更多相關(guān)Spring BeanUtils忽略空值拷貝內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • springmvc請求轉(zhuǎn)發(fā)和重定向問題(攜帶參數(shù)和不攜帶參數(shù))

    springmvc請求轉(zhuǎn)發(fā)和重定向問題(攜帶參數(shù)和不攜帶參數(shù))

    這篇文章主要介紹了springmvc請求轉(zhuǎn)發(fā)和重定向問題(攜帶參數(shù)和不攜帶參數(shù)),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-10-10
  • Java中的動態(tài)代理原理及實現(xiàn)

    Java中的動態(tài)代理原理及實現(xiàn)

    這篇文章主要介紹了Java中的動態(tài)代理原理及實現(xiàn),動態(tài)是相對于靜態(tài)而言,何為靜態(tài),即編碼時手動編寫代理類、委托類,而動態(tài)呢,是不編寫具體實現(xiàn)類,等到使用時,動態(tài)創(chuàng)建一個來實現(xiàn)代理的目的,需要的朋友可以參考下
    2023-12-12
  • Spring Security獲取用戶認證信息的實現(xiàn)流程

    Spring Security獲取用戶認證信息的實現(xiàn)流程

    Spring Security是一個能夠為基于Spring的企業(yè)應(yīng)用系統(tǒng)提供聲明式的安全訪問控制解決方案的安全框架。它提供了一組可以在Spring應(yīng)用上下文中配置的Bean,充分利用了Spring IoC,DI和AOP功能,為應(yīng)用系統(tǒng)提供聲明式的安全訪問控制功能
    2022-12-12
  • 從lombok的val和var到JDK的var關(guān)鍵字方式

    從lombok的val和var到JDK的var關(guān)鍵字方式

    這篇文章主要介紹了從lombok的val和var到JDK的var關(guān)鍵字方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • Java中類加載過程全面解析

    Java中類加載過程全面解析

    這篇文章主要介紹了Java中類加載過程全面解析,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11
  • Spring定時任務(wù)注解@Scheduled詳解

    Spring定時任務(wù)注解@Scheduled詳解

    這篇文章主要介紹了Spring定時任務(wù)注解@Scheduled詳解,@Scheduled注解是包org.springframework.scheduling.annotation中的一個注解,主要是用來開啟定時任務(wù),本文提供了部分實現(xiàn)代碼與思路,需要的朋友可以參考下
    2023-09-09
  • 新手了解java 集合基礎(chǔ)知識

    新手了解java 集合基礎(chǔ)知識

    今天小編就為大家分享一篇關(guān)于Java集合總結(jié),小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧,希望對你有所幫助
    2021-07-07
  • MyBatis特殊字符轉(zhuǎn)義攔截器問題針對(_、\、%)

    MyBatis特殊字符轉(zhuǎn)義攔截器問題針對(_、\、%)

    這篇文章主要介紹了MyBatis特殊字符轉(zhuǎn)義攔截器問題針對(_、\、%),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • 基于Springboot2.3訪問本地路徑下靜態(tài)資源的方法(解決報錯:Not allowed to load local resource)

    基于Springboot2.3訪問本地路徑下靜態(tài)資源的方法(解決報錯:Not allowed to load local

    這篇文章主要介紹了基于Springboot2.3訪問本地路徑下靜態(tài)資源的方法(解決報錯:Not allowed to load local resource),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • Java對List進行排序的方法總結(jié)

    Java對List進行排序的方法總結(jié)

    在Java中,對List進行排序是一項常見的任務(wù),Java提供了多種方法來對List中的元素進行排序,本文將詳細介紹如何使用Java來實現(xiàn)List的排序操作,涵蓋了常用的排序方法和技巧,需要的朋友可以參考下
    2024-07-07

最新評論