zoukankan      html  css  js  c++  java
  • [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; }
  • 相关阅读:
    L2 L3 L4
    C 语言assert使用
    VIM 命令收藏
    C++继承实例
    关于 WinScp 的一点使用经验
    Boa服务器移植
    Android 去掉标题全屏显示
    sys下gpio操作
    linux下 XGCOM串口助手的安装
    linux中inittab文件详解
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14270122.html
Copyright © 2011-2022 走看看