[Java Spring] Convertors

If you need to convert a deep nested object struture, you cannot just use @InitBinder, you need to build a custom convertor:

Exp: conver city prop in new Person().getAddress().getCity(). it is deep nested. 

Example of customer convert:

Define an enum for gender:

public enum Gender {
    MALE, FEMALE, OTHER;
}

Define a custom convertor class which implements Convertor interface:

import org.springfreamwork.core.convert.converter.Converter;

public class StringToEnumConvertor implements Converter {
    @Override
    public Gender convert(String s) {
        if(s.equals("Male")) {
             return Gender.MALE;
        } else if(s.equals("Female")) {
            return Gender.FEMALE;
        } else {
            return Gender.OTHER;
        }
}

Register the convertor in the configuration:

ApplicationConfg.java:

 @Configuration
 public class AppConfig {
     ...
     @Override
      protected void addFormatters(FormatterRegistry registry) {
            registry.addConverter(new StringToEnumConvertor());
        }

}

User Entity:

@Entity
public class User {
    ...
// When save into db, we want to save "MALE" as string, instead of 0,1...
@Enumerated(EnumType.STRING)
private Gender gender; }
原文地址:https://www.cnblogs.com/Answer1215/p/14270122.html