其他分享
首页 > 其他分享> > Spring Doc - Validation, Data Binding, and Type Conversion

Spring Doc - Validation, Data Binding, and Type Conversion

作者:互联网

3.1. Validation by Using Spring’s Validator Interface

Spring features a Validator interface that you can use to validate objects. The Validator interface works by using an Errors object so that, while validating, validators can report validation failures to the Errors object.

public class PersonValidator implements Validator {
    /**
     * This Validator validates only Person instances
     */
    public boolean supports(Class clazz) {
        return Person.class.equals(clazz);
    }

    public void validate(Object obj, Errors e) {
        ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
        Person p = (Person) obj;
        if (p.getAge() < 0) {
            e.rejectValue("age", "negativevalue");
        } else if (p.getAge() > 110) {
            e.rejectValue("age", "too.darn.old");
        }
    }
}

3.2. Resolving Codes to Error Messages

In the example shown in the preceding section, we rejected the name fields. If we want to output the error messages by using a MessageSource.

3.3. Bean Manipulation and the BeanWrapper

One quite important class in the beans package is the BeanWrapper interface. As quoted from the javadoc, the BeanWrapper offers functionality to set and get property values, get property descriptors, and query properties to determine if they are readable or writable.

3.3.1. Setting and Getting Basic and Nested Properties

Setting and getting properties is done through the setPropertyValue and getPropertyValue overloaded method variants of BeanWrapper.

BeanWrapper company = new BeanWrapperImpl(new Company());
company.setPropertyValue("name", "Some Company Inc.");
PropertyValue value = new PropertyValue("name", "Some Company Inc.");
company.setPropertyValue(value);

3.3.2. Built-in PropertyEditor Implementations

Spring uses the concept of a PropertyEditor to effect the conversion between an Object and a String. It can be handy to represent properties in a different way than the object itself.

3.4. Spring Type Conversion

Spring 3 introduced a core.convert package that provides a general type conversion system. The system defines an SPI to implement type conversion logic and an API to perform type conversions at runtime.

3.4.1. Converter SPI

The SPI to implement type conversion logic is simple and strongly typed, as the following interface definition shows:

package org.springframework.core.convert.converter;

public interface Converter<S, T> {
    T convert(S source);
}

The following listing shows the StringToInteger class, which is a typical Converter implementation:

package org.springframework.core.convert.support;

final class StringToInteger implements Converter<String, Integer> {
    public Integer convert(String source) {
        return Integer.valueOf(source);
    }
}

3.4.2. Using ConverterFactory

When you need to centralize the conversion logic for an entire class hierarchy, you can implement ConverterFactory, as the following example shows:

package org.springframework.core.convert.converter;

public interface ConverterFactory<S, R> {
    <T extends R> Converter<S, T> getConverter(Class<T> targetType);
}

Consider the StringToEnumConverterFactory as an example:

package org.springframework.core.convert.support;

final class StringToEnumConverterFactory implements ConverterFactory<String, Enum> {

    public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToEnumConverter(targetType);
    }

    private final class StringToEnumConverter<T extends Enum> implements Converter<String, T> {
        private Class<T> enumType;
        public StringToEnumConverter(Class<T> enumType) {
            this.enumType = enumType;
        }
        public T convert(String source) {
            return (T) Enum.valueOf(this.enumType, source.trim());
        }
    }
}

3.4.3. Using GenericConverter

When you require a sophisticated Converter implementation, consider using the GenericConverter interface. With a more flexible but less strongly typed signature than Converter, a GenericConverter supports converting between multiple source and target types.

3.4.4. The ConversionService API

ConversionService defines a unified API for executing type conversion logic at runtime.

3.4.5. Configuring a ConversionService

A ConversionService is a stateless object designed to be instantiated at application startup and then shared between multiple threads.

3.4.6. Using a ConversionService Programmatically

To work with a ConversionService instance programmatically, you can inject a reference to it like you would for any other bean.

3.5. Spring Field Formatting

Spring 3 introduced a convenient Formatter SPI that provides a simple and robust alternative to PropertyEditor implementations for client environments.

3.5.1. The Formatter SPI

The Formatter SPI to implement field formatting logic is simple and strongly typed.

3.5.2. Annotation-driven Formatting

Field formatting can be configured by field type or annotation.

3.5.3. The FormatterRegistry SPI

The FormatterRegistry is an SPI for registering formatters and converters.

3.5.4. The FormatterRegistrar SPI

FormatterRegistrar is an SPI for registering formatters and converters through the FormatterRegistry.

3.6. Configuring a Global Date and Time Format

By default, date and time fields not annotated with @DateTimeFormat are converted from strings by using the DateFormat.SHORT style. If you prefer, you can change this by defining your own global format.

3.7. Java Bean Validation

3.7.1. Overview of Bean Validation

Bean Validation provides a common way of validation through constraint declaration and metadata for Java applications.

public class PersonForm {

    @NotNull
    @Size(max=64)
    private String name;

    @Min(0)
    private int age;
}

3.7.2. Configuring a Bean Validation Provider

Spring provides full support for the Bean Validation API including the bootstrapping of a Bean Validation provider as a Spring bean.

3.7.3. Configuring a DataBinder

Since Spring 3, you can configure a DataBinder instance with a Validator.

3.7.4. Spring MVC 3 Validation

See Validation in the Spring MVC chapter.

标签:Conversion,Converter,Spring,class,SPI,Validation,Data,public
来源: https://www.cnblogs.com/feiqiangsheng/p/16515997.html