数据绑定

数据绑定对于将用户输入绑定到目标对象非常有用,其中用户输入是一个以属性路径为键的映射,遵循 JavaBeans 约定DataBinder 是支持此功能的主要类,它提供了两种绑定用户输入的方法:

  • 构造函数绑定 - 将用户输入绑定到公共数据构造函数,并在用户输入中查找构造函数参数值。

  • 属性绑定 - 将用户输入绑定到 setter 方法,将用户输入中的键与目标对象结构的属性匹配。

你可以同时应用构造函数绑定和属性绑定,或者只应用其中一种。

构造函数绑定

要使用构造函数绑定:

  1. 创建一个目标对象为 nullDataBinder

  2. targetType 设置为目标类。

  3. 调用 construct 方法。

目标类应具有一个公共构造函数,或一个带有参数的非公共构造函数。如果存在多个构造函数,则使用默认构造函数(如果存在)。

默认情况下,参数值通过构造函数参数名称查找。如果存在,Spring MVC 和 WebFlux 支持通过构造函数参数或字段上的 @BindParam 注解进行自定义名称映射。如有必要,您还可以通过在 DataBinder 上配置 NameResolver 来自定义要使用的参数名称。

类型转换 会根据需要应用以转换用户输入。如果构造函数参数是一个对象,它会以相同的方式递归构建,但通过嵌套属性路径。这意味着构造函数绑定既创建目标对象,也创建它包含的任何对象。

构造函数绑定支持 ListMap 和数组参数,这些参数可以从单个字符串转换而来(例如,逗号分隔列表),也可以基于索引键(例如 accounts[2].nameaccount[KEY].name)。

绑定和转换错误会反映在 DataBinderBindingResult 中。如果目标对象成功创建,则在调用 construct 后,target 将设置为创建的实例。

使用 BeanWrapper 进行属性绑定

org.springframework.beans 包遵循 JavaBeans 标准。JavaBean 是一个具有默认无参构造函数并遵循命名约定的类,例如,一个名为 bingoMadness 的属性将有一个 setter 方法 setBingoMadness(..) 和一个 getter 方法 getBingoMadness()。有关 JavaBeans 和规范的更多信息,请参阅 javabeans

beans 包中一个非常重要的类是 BeanWrapper 接口及其相应的实现 (BeanWrapperImpl)。正如 javadoc 中引用的,BeanWrapper 提供了设置和获取属性值(单独或批量)、获取属性描述符以及查询属性以确定它们是否可读或可写的功能。此外,BeanWrapper 还支持嵌套属性,可以无限深度地设置子属性上的属性。BeanWrapper 还支持添加标准的 JavaBeans PropertyChangeListenersVetoableChangeListeners,而无需在目标类中编写支持代码。最后但并非最不重要的一点是,BeanWrapper 提供了设置索引属性的支持。应用程序代码通常不直接使用 BeanWrapper,而是由 DataBinderBeanFactory 使用它。

BeanWrapper 的工作方式部分地由其名称表明:它包装一个 bean,以便对该 bean 执行操作,例如设置和检索属性。

设置和获取基本属性和嵌套属性

设置和获取属性是通过 BeanWrappersetPropertyValuegetPropertyValue 方法的重载变体完成的。有关详细信息,请参阅它们的 Javadoc。下表显示了一些遵循这些约定的示例:

表 1. 属性示例
表达式 说明

name

表示对应于 getName()isName() 以及 setName(..) 方法的属性 name

account.name

表示属性 account 的嵌套属性 name,对应于(例如)getAccount().setName()getAccount().getName() 方法。

accounts[2]

表示索引属性 account第三个元素。索引属性可以是 arraylist 或其他自然有序的集合类型。

accounts[KEY]

表示由 KEY 值索引的 map 条目的值。

(如果您不打算直接使用 BeanWrapper,那么下一节对您来说不是至关重要的。如果您只使用 DataBinderBeanFactory 及其默认实现,则应跳到关于 PropertyEditors 的部分。)

以下两个示例类使用 BeanWrapper 来获取和设置属性:

  • Java

  • Kotlin

public class Company {

	private String name;
	private Employee managingDirector;

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Employee getManagingDirector() {
		return this.managingDirector;
	}

	public void setManagingDirector(Employee managingDirector) {
		this.managingDirector = managingDirector;
	}
}
class Company {
	var name: String? = null
	var managingDirector: Employee? = null
}
  • Java

  • Kotlin

public class Employee {

	private String name;

	private float salary;

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public float getSalary() {
		return salary;
	}

	public void setSalary(float salary) {
		this.salary = salary;
	}
}
class Employee {
	var name: String? = null
	var salary: Float? = null
}

以下代码片段展示了如何检索和操作实例化后的 CompanyEmployee 对象的一些属性:

  • Java

  • Kotlin

BeanWrapper company = new BeanWrapperImpl(new Company());
// setting the company name..
company.setPropertyValue("name", "Some Company Inc.");
// ... can also be done like this:
PropertyValue value = new PropertyValue("name", "Some Company Inc.");
company.setPropertyValue(value);

// ok, let's create the director and tie it to the company:
BeanWrapper jim = new BeanWrapperImpl(new Employee());
jim.setPropertyValue("name", "Jim Stravinsky");
company.setPropertyValue("managingDirector", jim.getWrappedInstance());

// retrieving the salary of the managingDirector through the company
Float salary = (Float) company.getPropertyValue("managingDirector.salary");
val company = BeanWrapperImpl(Company())
// setting the company name..
company.setPropertyValue("name", "Some Company Inc.")
// ... can also be done like this:
val value = PropertyValue("name", "Some Company Inc.")
company.setPropertyValue(value)

// ok, let's create the director and tie it to the company:
val jim = BeanWrapperImpl(Employee())
jim.setPropertyValue("name", "Jim Stravinsky")
company.setPropertyValue("managingDirector", jim.wrappedInstance)

// retrieving the salary of the managingDirector through the company
val salary = company.getPropertyValue("managingDirector.salary") as Float?

PropertyEditor

Spring 使用 PropertyEditor 的概念来实现 ObjectString 之间的转换。以与对象本身不同的方式表示属性会很方便。例如,Date 可以以人类可读的方式表示(如 String'2007-14-09'),同时我们仍然可以将人类可读的形式转换回原始日期(或者更好,将任何以人类可读形式输入的日期转换回 Date 对象)。这种行为可以通过注册类型为 java.beans.PropertyEditor 的自定义编辑器来实现。在 BeanWrapper 或特定 IoC 容器(如前一章所述)中注册自定义编辑器,使其具备将属性转换为所需类型的能力。有关 PropertyEditor 的更多信息,请参阅 Oracle 的 java.beans 包的 javadoc

Spring 中使用属性编辑的几个例子:

  • 通过使用 PropertyEditor 实现来设置 bean 的属性。当您在 XML 文件中声明某个 bean 的属性值使用 String 类型时,Spring(如果相应属性的 setter 方法有一个 Class 参数)会使用 ClassEditor 尝试将参数解析为 Class 对象。

  • 在 Spring 的 MVC 框架中解析 HTTP 请求参数是通过使用各种 PropertyEditor 实现来完成的,您可以在 CommandController 的所有子类中手动绑定它们。

Spring 内置了许多 PropertyEditor 实现,以简化开发。它们都位于 org.springframework.beans.propertyeditors 包中。大多数(但并非全部,如下表所示)默认情况下由 BeanWrapperImpl 注册。如果属性编辑器可以在某种程度上配置,您仍然可以注册自己的变体来覆盖默认编辑器。下表描述了 Spring 提供的各种 PropertyEditor 实现:

表 2. 内置的 PropertyEditor 实现
说明

ByteArrayPropertyEditor

字节数组的编辑器。将字符串转换为相应的字节表示。默认由 BeanWrapperImpl 注册。

ClassEditor

将表示类的字符串解析为实际的类,反之亦然。当找不到类时,会抛出 IllegalArgumentException。默认由 BeanWrapperImpl 注册。

CustomBooleanEditor

用于 Boolean 属性的可定制属性编辑器。默认由 BeanWrapperImpl 注册,但可以通过注册其自定义实例作为自定义编辑器来覆盖。

CustomCollectionEditor

集合的属性编辑器,将任何源 Collection 转换为给定的目标 Collection 类型。

CustomDateEditor

用于 java.util.Date 的可定制属性编辑器,支持自定义 DateFormat。默认情况下*不*注册。必须根据需要使用适当的格式进行用户注册。

CustomNumberEditor

用于任何 Number 子类(如 IntegerLongFloatDouble)的可定制属性编辑器。默认由 BeanWrapperImpl 注册,但可以通过注册其自定义实例作为自定义编辑器来覆盖。

FileEditor

将字符串解析为 java.io.File 对象。默认由 BeanWrapperImpl 注册。

InputStreamEditor

单向属性编辑器,可以接受字符串并通过中间的 ResourceEditorResource 生成 InputStream,从而可以将 InputStream 属性直接设置为字符串。请注意,默认用法不会为您关闭 InputStream。默认由 BeanWrapperImpl 注册。

LocaleEditor

可以将字符串解析为 Locale 对象,反之亦然(字符串格式为 [language]_[country]_[variant],与 LocaletoString() 方法相同)。也接受空格作为分隔符,替代下划线。默认由 BeanWrapperImpl 注册。

PatternEditor

可以将字符串解析为 java.util.regex.Pattern 对象,反之亦然。

PropertiesEditor

可以将字符串(使用 java.util.Properties 类的 javadoc 中定义的格式)转换为 Properties 对象。默认由 BeanWrapperImpl 注册。

StringTrimmerEditor

去除字符串首尾空白的属性编辑器。可选地允许将空字符串转换为 null 值。默认情况*不*注册——必须由用户注册。

URLEditor

可以将 URL 的字符串表示解析为实际的 URL 对象。默认由 BeanWrapperImpl 注册。

Spring 使用 java.beans.PropertyEditorManager 来设置可能需要的属性编辑器的搜索路径。搜索路径还包括 sun.bean.editors,其中包含用于 FontColor 和大多数原始类型等类型的 PropertyEditor 实现。另请注意,标准 JavaBeans 基础设施会自动发现 PropertyEditor 类(无需显式注册),如果它们与它们处理的类位于同一包中,并且与该类同名,只是附加了 Editor 后缀。例如,可以有以下类和包结构,这足以使 SomethingEditor 类被识别并用作 Something 类型属性的 PropertyEditor

com
  chank
    pop
      Something
      SomethingEditor // the PropertyEditor for the Something class

请注意,您这里也可以使用标准的 BeanInfo JavaBeans 机制(在 这里 有一定程度的描述)。以下示例使用 BeanInfo 机制为关联类的属性显式注册一个或多个 PropertyEditor 实例:

com
  chank
    pop
      Something
      SomethingBeanInfo // the BeanInfo for the Something class

以下是引用的 SomethingBeanInfo 类的 Java 源代码,它将 CustomNumberEditorSomething 类的 age 属性关联起来:

  • Java

  • Kotlin

public class SomethingBeanInfo extends SimpleBeanInfo {

	public PropertyDescriptor[] getPropertyDescriptors() {
		try {
			final PropertyEditor numberPE = new CustomNumberEditor(Integer.class, true);
			PropertyDescriptor ageDescriptor = new PropertyDescriptor("age", Something.class) {
				@Override
				public PropertyEditor createPropertyEditor(Object bean) {
					return numberPE;
				}
			};
			return new PropertyDescriptor[] { ageDescriptor };
		}
		catch (IntrospectionException ex) {
			throw new Error(ex.toString());
		}
	}
}
class SomethingBeanInfo : SimpleBeanInfo() {

	override fun getPropertyDescriptors(): Array<PropertyDescriptor> {
		try {
			val numberPE = CustomNumberEditor(Int::class.java, true)
			val ageDescriptor = object : PropertyDescriptor("age", Something::class.java) {
				override fun createPropertyEditor(bean: Any): PropertyEditor {
					return numberPE
				}
			}
			return arrayOf(ageDescriptor)
		} catch (ex: IntrospectionException) {
			throw Error(ex.toString())
		}

	}
}

自定义 PropertyEditor

将 bean 属性设置为字符串值时,Spring IoC 容器最终使用标准的 JavaBeans PropertyEditor 实现将这些字符串转换为属性的复杂类型。Spring 预先注册了许多自定义的 PropertyEditor 实现(例如,将表示类名的字符串转换为 Class 对象)。此外,Java 的标准 JavaBeans PropertyEditor 查找机制允许为类指定适当名称并将 PropertyEditor 放置在与其支持的类相同的包中,以便可以自动找到它。

如果需要注册其他自定义 PropertyEditors,有几种机制可用。最手动的方法(通常不方便或不推荐)是使用 ConfigurableBeanFactory 接口的 registerCustomEditor() 方法,前提是您有一个 BeanFactory 引用。另一种(稍微方便一点)的机制是使用一个特殊的 bean 工厂后处理器,称为 CustomEditorConfigurer。尽管您可以将 bean 工厂后处理器与 BeanFactory 实现一起使用,但 CustomEditorConfigurer 具有嵌套属性设置,因此我们强烈建议您将其与 ApplicationContext 一起使用,在那里您可以像部署任何其他 bean 一样部署它,并且它可以被自动检测和应用。

请注意,所有 bean 工厂和应用上下文都会通过使用 BeanWrapper 来处理属性转换,从而自动使用许多内置的属性编辑器。BeanWrapper 注册的标准属性编辑器列在 上一节 中。此外,ApplicationContext 还会覆盖或添加额外的编辑器,以适当的方式处理资源查找,以适应特定的应用上下文类型。

标准的 JavaBeans PropertyEditor 实例用于将表示为字符串的属性值转换为属性的实际复杂类型。您可以使用 CustomEditorConfigurer(一个 bean 工厂后处理器)方便地为 ApplicationContext 添加对额外 PropertyEditor 实例的支持。

考虑以下示例,它定义了一个名为 ExoticType 的用户类,以及另一个名为 DependsOnExoticType 的类,后者需要将 ExoticType 设置为一个属性:

  • Java

  • Kotlin

package example;

public class ExoticType {

	private String name;

	public ExoticType(String name) {
		this.name = name;
	}
}

public class DependsOnExoticType {

	private ExoticType type;

	public void setType(ExoticType type) {
		this.type = type;
	}
}
package example

class ExoticType(val name: String)

class DependsOnExoticType {

	var type: ExoticType? = null
}

正确设置后,我们希望能够将 type 属性指定为字符串,由 PropertyEditor 将其转换为实际的 ExoticType 实例。以下 bean 定义显示了如何设置这种关系:

<bean id="sample" class="example.DependsOnExoticType">
	<property name="type" value="aNameForExoticType"/>
</bean>

PropertyEditor 实现可能看起来类似于以下内容:

  • Java

  • Kotlin

package example;

import java.beans.PropertyEditorSupport;

// converts string representation to ExoticType object
public class ExoticTypeEditor extends PropertyEditorSupport {

	public void setAsText(String text) {
		setValue(new ExoticType(text.toUpperCase()));
	}
}
package example

import java.beans.PropertyEditorSupport

// converts string representation to ExoticType object
class ExoticTypeEditor : PropertyEditorSupport() {

	override fun setAsText(text: String) {
		value = ExoticType(text.toUpperCase())
	}
}

最后,以下示例展示了如何使用 CustomEditorConfigurerApplicationContext 注册新的 PropertyEditor,然后 ApplicationContext 就可以根据需要使用它了:

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
	<property name="customEditors">
		<map>
			<entry key="example.ExoticType" value="example.ExoticTypeEditor"/>
		</map>
	</property>
</bean>

PropertyEditorRegistrar

向 Spring 容器注册属性编辑器的另一种机制是创建和使用 PropertyEditorRegistrar。当您需要在多种不同情况下使用同一组属性编辑器时,此接口特别有用。您可以编写相应的注册器并在每种情况下重用它。PropertyEditorRegistrar 实例与一个名为 PropertyEditorRegistry 的接口协同工作,该接口由 Spring 的 BeanWrapper(和 DataBinder)实现。PropertyEditorRegistrar 实例与 CustomEditorConfigurer此处 描述)结合使用时特别方便,后者暴露了一个名为 setPropertyEditorRegistrars(..) 的属性。以这种方式添加到 CustomEditorConfigurerPropertyEditorRegistrar 实例可以轻松地与 DataBinder 和 Spring MVC 控制器共享。此外,它避免了自定义编辑器上的同步需求:PropertyEditorRegistrar 预计为每次 bean 创建尝试创建全新的 PropertyEditor 实例。

以下示例展示了如何创建自己的 PropertyEditorRegistrar 实现:

  • Java

  • Kotlin

package com.foo.editors.spring;

public final class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {

	public void registerCustomEditors(PropertyEditorRegistry registry) {

		// it is expected that new PropertyEditor instances are created
		registry.registerCustomEditor(ExoticType.class, new ExoticTypeEditor());

		// you could register as many custom property editors as are required here...
	}
}
package com.foo.editors.spring

import org.springframework.beans.PropertyEditorRegistrar
import org.springframework.beans.PropertyEditorRegistry

class CustomPropertyEditorRegistrar : PropertyEditorRegistrar {

	override fun registerCustomEditors(registry: PropertyEditorRegistry) {

		// it is expected that new PropertyEditor instances are created
		registry.registerCustomEditor(ExoticType::class.java, ExoticTypeEditor())

		// you could register as many custom property editors as are required here...
	}
}

另请参阅 org.springframework.beans.support.ResourceEditorRegistrar 以获取 PropertyEditorRegistrar 实现的示例。请注意在其 registerCustomEditors(..) 方法实现中,它如何为每个属性编辑器创建新的实例。

下一个示例展示了如何配置 CustomEditorConfigurer 并将我们的 CustomPropertyEditorRegistrar 实例注入其中:

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
	<property name="propertyEditorRegistrars">
		<list>
			<ref bean="customPropertyEditorRegistrar"/>
		</list>
	</property>
</bean>

<bean id="customPropertyEditorRegistrar"
	class="com.foo.editors.spring.CustomPropertyEditorRegistrar"/>

最后(稍微偏离本章重点),对于使用 Spring MVC web 框架 的用户,将 PropertyEditorRegistrar 与数据绑定 web 控制器结合使用会非常方便。以下示例在 @InitBinder 方法的实现中使用了 PropertyEditorRegistrar

  • Java

  • Kotlin

@Controller
public class RegisterUserController {

	private final PropertyEditorRegistrar customPropertyEditorRegistrar;

	RegisterUserController(PropertyEditorRegistrar propertyEditorRegistrar) {
		this.customPropertyEditorRegistrar = propertyEditorRegistrar;
	}

	@InitBinder
	void initBinder(WebDataBinder binder) {
		this.customPropertyEditorRegistrar.registerCustomEditors(binder);
	}

	// other methods related to registering a User
}
@Controller
class RegisterUserController(
	private val customPropertyEditorRegistrar: PropertyEditorRegistrar) {

	@InitBinder
	fun initBinder(binder: WebDataBinder) {
		this.customPropertyEditorRegistrar.registerCustomEditors(binder)
	}

	// other methods related to registering a User
}

这种 PropertyEditor 注册风格可以带来简洁的代码(@InitBinder 方法的实现只有一行长),并且可以将通用的 PropertyEditor 注册代码封装在一个类中,然后在需要时在多个控制器之间共享。