Spring原始碼系列:BeanWrapper

glmapper發表於2019-03-04

BeanWrapper 是Spring提供的一個用來操作javaBean屬性的工具,使用它可以直接修改一個物件的屬性。

對於bean屬性的操作,大家熟知的主要有下面這些工具類:

  • 1.Apache的BeanUtils和PropertyUtils
  • 2.cglib的BeanMap和BeanCopier
  • 3.spring的BeanUtils

Spring中BeanWrapper 的主要功能在於:

  • 1.支援設定巢狀屬性
  • 2.支援屬性值的型別轉換(設定ConversionService)
  • 3.提供分析和操作標準JavaBean的操作:獲取和設定屬性值(單獨或批量),獲取屬性描述符以及查詢屬性的可讀性/可寫性的能力。

BeanWrapper本身是一個介面,它提供了一整套處理Bean的方法。原始碼如下:

public interface BeanWrapper extends ConfigurablePropertyAccessor {
	 //為陣列和集合自動增長指定一個限制。在普通的BeanWrapper上預設是無限的。
	void setAutoGrowCollectionLimit(int autoGrowCollectionLimit);
	//返回陣列和集合自動增長的限制。
	int getAutoGrowCollectionLimit();
    //如果有的話,返回由此物件包裝的bean例項
	Object getWrappedInstance();
	//返回被包裝的JavaBean物件的型別。
	Class<?> getWrappedClass();
	//獲取包裝物件的PropertyDescriptors(由標準JavaBeans自省確定)。
	PropertyDescriptor[] getPropertyDescriptors();
	//獲取包裝物件的特定屬性的屬性描述符。
	PropertyDescriptor getPropertyDescriptor(String propertyName) throws InvalidPropertyException;
}
複製程式碼

上面的BeanWrapper是基於4.3.6版本的,這個介面在4.1版本之後略有改動。BeanWrapperImpl是BeanWrapper的實現類,BeanWrapperImpl的父類是AbstractNestablePropertyAccessor,通過這個使得BeanWrapper具有處理屬性的能力。

下面是一個使用BeanWrapper 包裝物件的例子:

package com.glmapper.spring.test;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.PropertyValue;
/**
 * BeanWrapper 測試類
 */
public class BeanWrapperTest {
    public static void main(String[] args) {
        User user=new User();
        //通過PropertyAccessorFactory將user物件封裝成BeanWrapper
        BeanWrapper bw=PropertyAccessorFactory.forBeanPropertyAccess(user);
        //方式一:直接對屬性值進行設定
        bw.setPropertyValue("userName", "張三");
        //方式二:通過PropertyValue進行設定
        PropertyValue pv=new PropertyValue("userName","李四");
        bw.setPropertyValue(pv);
        
        
        System.out.println(user.getUserName());
    }
}
//一個User類
class User{
    private String userName;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
}
複製程式碼

在Spring中,有很多Bean屬性的操作都是通過BeanWrapper來完成的,比如常見的HttpServletBean的屬性設定就是。

注:本文摘自我的部落格園文章,進行了一些包裝,放在Spring原始碼系列中。 Spring中的 BeanWrapper

Spring原始碼系列:BeanWrapper
歡迎關注微信公眾號

相關文章