Top Description Inners Fields Constructors Methods
org.springframework.validation

public Class DataBinder

extends Object
implements PropertyEditorRegistry, TypeConverter
Class Inheritance
All Implemented Interfaces
org.springframework.beans.TypeConverter, org.springframework.beans.PropertyEditorRegistry
Imports
java.beans.PropertyEditor, java.lang.annotation.Annotation, java.lang.reflect.Constructor, .Field, java.util.ArrayList, .Arrays, .Collection, .Collections, .HashMap, .HashSet, .List, .Map, .Optional, .Set, java.util.function.Predicate, org.apache.commons.logging.Log, .LogFactory, org.springframework.beans.BeanInstantiationException, .BeanUtils, .ConfigurablePropertyAccessor, .MutablePropertyValues, .PropertyAccessException, .PropertyAccessorUtils, .PropertyBatchUpdateException, .PropertyEditorRegistrar, .PropertyEditorRegistry, .PropertyValue, .PropertyValues, .SimpleTypeConverter, .TypeConverter, .TypeMismatchException, org.springframework.core.KotlinDetector, .MethodParameter, .ResolvableType, org.springframework.core.convert.ConversionService, .TypeDescriptor, org.springframework.format.Formatter, org.springframework.format.support.FormatterPropertyEditorAdapter, org.springframework.lang.Nullable, org.springframework.util.Assert, .ObjectUtils, .PatternMatchUtils, .StringUtils, org.springframework.validation.annotation.ValidationAnnotationUtils

Binder that allows applying property values to a target object via constructor and setter injection, and also supports validation and binding result analysis.

The binding process can be customized by specifying allowed field patterns, required fields, custom editors, etc.

Warning

Data binding can lead to security issues by exposing parts of the object graph that are not meant to be accessed or modified by external clients. Therefore, the design and use of data binding should be considered carefully with regard to security. For more details, please refer to the dedicated sections on data binding for Spring Web MVC and Spring WebFlux in the reference manual.

The binding results can be examined via the BindingResult interface, extending the Errors interface: see the getBindingResult() method. Missing fields and property access exceptions will be converted to FieldErrors, collected in the Errors instance, using the following error codes:

By default, binding errors get resolved through the BindingErrorProcessor strategy, processing for missing fields and property access exceptions: see the setBindingErrorProcessor method. You can override the default strategy if needed, for example to generate different error codes.

Custom validation errors can be added afterwards. You will typically want to resolve such error codes into proper user-visible error messages; this can be achieved through resolving each error via a org.springframework.context.MessageSource, which is able to resolve an ObjectError/FieldError through its org.springframework.context.MessageSource#getMessage(org.springframework.context.MessageSourceResolvable, java.util.Locale) method. The list of message codes can be customized through the MessageCodesResolver strategy: see the setMessageCodesResolver method. DefaultMessageCodesResolver's javadoc states details on the default resolution rules.

This generic data binder can be used in any kind of environment.

Authors
Rod Johnson, Juergen Hoeller, Rob Harrop, Stephane Nicoll, Kazuki Shimizu, Sam Brannen
See Also
setAllowedFields, setRequiredFields, registerCustomEditor, setMessageCodesResolver, setBindingErrorProcessor, construct, bind, getBindingResult, DefaultMessageCodesResolver, DefaultBindingErrorProcessor, org.springframework.context.MessageSource

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static class
public static interface
DataBinder.NameResolver

Strategy to determine the name of the value to bind to a method parameter.

public static interface
DataBinder.ValueResolver

Strategy for constructor binding to look up the values to bind to a given constructor parameter.

Field Summary

Modifier and TypeField and Description
private String[]
private int
private boolean
private BindingErrorProcessor
private AbstractPropertyBindingResult
private ConversionService
private boolean
public static final int
DEFAULT_AUTO_GROW_COLLECTION_LIMIT

Default limit for array and collection growing: 256.

public static final String
DEFAULT_OBJECT_NAME

Default object name used for binding: "target".

private boolean
private String[]
private Predicate<Validator>
private boolean
private boolean
protected static final Log
logger

We'll create a lot of DataBinder instances: Let's use a static logger.

private MessageCodesResolver
private DataBinder.NameResolver
private final String
private String[]
private Object
pack-priv ResolvableType
private DataBinder.ExtendedTypeConverter
private final List<Validator>

Constructor Summary

AccessConstructor and Description
public
DataBinder(Object
the target object to bind onto (or null if the binder is just used to convert a plain parameter value)
target
)

Create a new DataBinder instance, with default object name.

public
DataBinder(Object
the target object to bind onto (or null if the binder is just used to convert a plain parameter value)
target
,
String
the name of the target object
objectName
)

Create a new DataBinder instance.

Method Summary

Modifier and TypeMethod and Description
public void
addCustomFormatter(Formatter<?>
the formatter to add, generically declared for a specific type
formatter
)

Add a custom formatter, applying it to all fields matching the Formatter-declared type.

public void
addCustomFormatter(Formatter<?>
the formatter to add, generically declared for a specific type
formatter
,
String...
the fields to apply the formatter to, or none if to be applied to all
fields
)

Add a custom formatter for the field type specified in Formatter class, applying it to the specified fields only, if any, or otherwise to all fields.

public void
addCustomFormatter(Formatter<?>
the formatter to add (does not need to generically declare a field type if field types are explicitly specified as parameters)
formatter
,
Class<?>...
the field types to apply the formatter to, or none if to be derived from the given Formatter implementation class
fieldTypes
)

Add a custom formatter, applying it to the specified field types only, if any, or otherwise to all fields matching the Formatter-declared type.

public void
addValidators(Validator... validators)

Add Validators to apply after each binding step.

protected void
applyPropertyValues(MutablePropertyValues
the property values to be bound (can be modified)
mpvs
)

Apply given property values to the target object.

private void
assertValidators(Validator... validators)

public void
bind(PropertyValues
property values to bind
pvs
)

Bind the given property values to this binder's target.

protected void
checkAllowedFields(MutablePropertyValues
the property values to be bound (can be modified)
mpvs
)

Check the given property values against the allowed fields, removing values for fields that are not allowed.

protected void
checkRequiredFields(MutablePropertyValues
the property values to be bound (can be modified)
mpvs
)

Check the given property values against the required fields, generating missing field errors where appropriate.

public Map<?, ?>

Returns:

the model Map, containing target object and Errors instance
close
()

Close this DataBinder, which may result in throwing a BindException if it encountered any errors.

public void
construct(DataBinder.ValueResolver
to resolve constructor argument values with
valueResolver
)

Create the target with constructor injection of values.

public <T> T
convertIfNecessary(Object
the value to convert
value
,
Class<T>
the type we must convert to (or null if not known, for example in case of a collection element)
requiredType
)

Implements org.springframework.beans.TypeConverter.convertIfNecessary.

Convert the value to the required type (if necessary from a String).
public <T> T
convertIfNecessary(Object
the value to convert
value
,
Class<T>
the type we must convert to (or null if not known, for example in case of a collection element)
requiredType
,
MethodParameter
the method parameter that is the target of the conversion (for analysis of generic types; may be null)
methodParam
)

Implements org.springframework.beans.TypeConverter.convertIfNecessary.

Convert the value to the required type (if necessary from a String).
public <T> T
convertIfNecessary(Object
the value to convert
value
,
Class<T>
the type we must convert to (or null if not known, for example in case of a collection element)
requiredType
,
Field
the reflective field that is the target of the conversion (for analysis of generic types; may be null)
field
)

Implements org.springframework.beans.TypeConverter.convertIfNecessary.

Convert the value to the required type (if necessary from a String).
public <T> T
convertIfNecessary(Object
the value to convert
value
,
Class<T>
the type we must convert to (or null if not known, for example in case of a collection element)
requiredType
,
TypeDescriptor
the type descriptor to use (may be null))
typeDescriptor
)

Overrides default org.springframework.beans.TypeConverter.convertIfNecessary.

Convert the value to the required type (if necessary from a String).
protected AbstractPropertyBindingResult
createBeanPropertyBindingResult()

Create the AbstractPropertyBindingResult instance using standard JavaBean property access.

protected AbstractPropertyBindingResult
createDirectFieldBindingResult()

Create the AbstractPropertyBindingResult instance using direct field access.

private Object
createObject(ResolvableType objectType, String nestedPath, DataBinder.ValueResolver valueResolver)

protected void
doBind(MutablePropertyValues
the property values to bind, as MutablePropertyValues instance
mpvs
)

Actual implementation of the binding process, working with the passed-in MutablePropertyValues instance.

public PropertyEditor
findCustomEditor(Class<?>
the type of the property (can be null if a property is given but should be specified in any case for consistency checking)
requiredType
,
String
the path of the property (name or nested path), or null if looking for an editor for all properties of the given type
propertyPath
)

Implements org.springframework.beans.PropertyEditorRegistry.findCustomEditor.

Find a custom property editor for the given type and property.
public String[]

Returns:

array of allowed field patterns
getAllowedFields
()

Return the field patterns that should be allowed for binding.

public int
getAutoGrowCollectionLimit()

Return the current limit for array and collection auto-growing.

public BindingErrorProcessor
getBindingErrorProcessor()

Return the strategy for processing binding errors.

public BindingResult

Returns:

the BindingResult instance, to be treated as BindingResult or as Errors instance (Errors is a super-interface of BindingResult)
getBindingResult
()

Return the BindingResult instance created by this DataBinder.

public ConversionService
getConversionService()

Return the associated ConversionService, if any.

public String[]

Returns:

array of disallowed field patterns
getDisallowedFields
()

Return the field patterns that should not be allowed for binding.

protected AbstractPropertyBindingResult
getInternalBindingResult()

Return the internal BindingResult held by this DataBinder, as an AbstractPropertyBindingResult.

public DataBinder.NameResolver
getNameResolver()

Return the configured name resolver for constructor parameters.

public String
getObjectName()

Return the name of the bound object.

protected ConfigurablePropertyAccessor
getPropertyAccessor()

Return the underlying PropertyAccessor of this binder's BindingResult.

protected PropertyEditorRegistry
getPropertyEditorRegistry()

Return the underlying TypeConverter of this binder's BindingResult.

public String[]

Returns:

array of field names
getRequiredFields
()

Return the fields that are required for each binding process.

protected SimpleTypeConverter
getSimpleTypeConverter()

Return this binder's underlying SimpleTypeConverter.

public Object
getTarget()

Return the wrapped target object.

public ResolvableType
getTargetType()

Return the configured type for the target object.

protected TypeConverter
getTypeConverter()

Return the underlying TypeConverter of this binder's BindingResult.

public Validator
getValidator()

Return the primary Validator to apply after each binding step, if any.

public List<Validator>
getValidators()

Return the Validators to apply after data binding.

public List<Validator>
getValidatorsToApply()

Return the Validators to apply after data binding.

private boolean
public void
initBeanPropertyAccess()

Initialize standard JavaBean property access for this DataBinder.

public void
initDirectFieldAccess()

Initialize direct field access for this DataBinder, as alternative to the default bean property access.

protected boolean

Returns:

true if the field is allowed
isAllowed
(String
the field to check
field
)

Determine if the given field is allowed for binding.

public boolean
isAutoGrowNestedPaths()

Return whether "auto-growing" of nested paths has been activated.

public boolean
isDeclarativeBinding()

Return whether to bind only fields intended for binding.

public boolean
isIgnoreInvalidFields()

Return whether to ignore invalid fields when binding.

public boolean
isIgnoreUnknownFields()

Return whether to ignore unknown fields when binding.

public void
registerCustomEditor(Class<?>
the type of the property
requiredType
,
PropertyEditor
the editor to register
propertyEditor
)

Implements org.springframework.beans.PropertyEditorRegistry.registerCustomEditor.

Register the given custom property editor for all properties of the given type.
public void
registerCustomEditor(Class<?>
the type of the property. This may be null if a property is given but should be specified in any case, in particular in case of a Collection - making clear whether the editor is supposed to apply to the entire Collection itself or to each of its entries. So as a general rule: Do not specify null here in case of a Collection/array!
requiredType
,
String
the path of the property (name or nested path), or null if registering an editor for all properties of the given type
field
,
PropertyEditor
editor to register
propertyEditor
)

Implements org.springframework.beans.PropertyEditorRegistry.registerCustomEditor.

Register the given custom property editor for the given type and property, or for all properties of the given type.
public void
replaceValidators(Validator... validators)

Replace the Validators to apply after each binding step.

public void
setAllowedFields(String...
array of allowed field patterns
allowedFields
)

Register field patterns that should be allowed for binding.

public void
setAutoGrowCollectionLimit(int autoGrowCollectionLimit)

Specify the limit for array and collection auto-growing.

public void
setAutoGrowNestedPaths(boolean autoGrowNestedPaths)

Set whether this binder should attempt to "auto-grow" a nested path that contains a null value.

public void
setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor)

Set the strategy to use for processing binding errors, that is, required field errors and PropertyAccessExceptions.

public void
setConversionService(ConversionService conversionService)

Specify a ConversionService to use for converting property values, as an alternative to JavaBeans PropertyEditors.

public void
setDeclarativeBinding(boolean declarativeBinding)

Set whether to bind only fields explicitly intended for binding including:

public void
setDisallowedFields(String...
array of disallowed field patterns
disallowedFields
)

Register field patterns that should not be allowed for binding.

public void
setExcludedValidators(Predicate<Validator> predicate)

Configure a predicate to exclude validators.

public void
setIgnoreInvalidFields(boolean ignoreInvalidFields)

Set whether to ignore invalid fields, that is, whether to ignore bind parameters that have corresponding fields in the target object which are not accessible (for example because of null values in the nested path).

public void
setIgnoreUnknownFields(boolean ignoreUnknownFields)

Set whether to ignore unknown fields, that is, whether to ignore bind parameters that do not have corresponding fields in the target object.

public void
setMessageCodesResolver(MessageCodesResolver messageCodesResolver)

Set the strategy to use for resolving errors into message codes.

public void
setNameResolver(DataBinder.NameResolver
the resolver to use
nameResolver
)

Configure a resolver to determine the name of the value to bind to a constructor parameter in construct.

public void
setRequiredFields(String...
array of field names
requiredFields
)

Register fields that are required for each binding process.

public void
setTargetType(ResolvableType
the type of the target object
targetType
)

Set the type for the target object.

public void
setValidator(Validator validator)

Set the Validator to apply after each binding step.

protected boolean
shouldConstructArgument(MethodParameter param)

Whether to instantiate the constructor argument of the given type, matching its own constructor arguments to bind values.

protected boolean
shouldNotBindPropertyValues()

Whether to not bind parameters to properties.

public void
validate()

Invoke the specified Validators, if any.

public void
validate(Object...
one or more hint objects to be passed to a SmartValidator
validationHints
)

Invoke the specified Validators, if any, with the given validation hints.

private void
validateConstructorArgument(Class<?> constructorClass, String nestedPath, String name, Object value)

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait