BeanWrapper 是Spring提供的一个用来操做javaBean属性的工具,使用它能够直接修改一个对象的属性。html
对于bean属性的操做,你们熟知的主要有下面这些工具类:java
Spring中BeanWrapper 的主要功能在于:spring
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 包装对象的例子:app
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测试
欢迎关注微信公众号