Spring源码系列:BeanWrapper

7,186 阅读2分钟

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

欢迎关注微信公众号