本文阅读Spring关于Convert知识的介绍
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#core-convert
     Spring3引入了core.convert包,这个包里提供的就是转换功能。其使用方式是:
- 实现SPI,并注册,完成自定义的转换逻辑
 - 提供一个API去执行具体的Convert类
 

自己实现Convert的方式
用户想要自定义Convert的话,有以下几种方式:
- 实现Convert:针对于从某个特定类型转换成另一个特定类型
 - 实现ConverterFactory:
 - 
1. 实现Convert
 实现
Convert<S,T>public class MyConvert implements Converter<String, Date> {@Overridepublic Date convert(String source) {try {return new SimpleDateFormat("yyyy-MM-dd").parse(source);} catch (ParseException e) {e.printStackTrace();return null;}}}
注册并使用自定义Convert
public static void main(String[] args) {DefaultConversionService defaultConversionService = new DefaultConversionService();defaultConversionService.addConverter(new MyConvert());Date convert = defaultConversionService.convert("2022-01-01", Date.class);System.out.println(convert);}
上面的例子中,我既没有注册任何的Bean,也没有启动容器。
2.实现ConvertFactory
顾名思义,Convert的Factory,返回的就是一个Convert
举个例子
实现ConvertFactory ```java public class MyConvertFactory implements ConverterFactory
{ @Override public
Converter getConverter(Class targetType) { if(targetType.equals(Long.class)){return new Str2LongConvert();}else {return new Str2IntegerConvert();}
}
private final class Str2IntegerConvert
implements Converter { @Overridepublic Integer convert(String source) {return Integer.parseInt(source);}
}
private final class Str2LongConvert
implements Converter { @Overridepublic Long convert(String source) {return Long.parseLong(source);}
}
}
2. 注册并使用自定义的ConvertFactory```javapublic static void main(String[] args) {DefaultConversionService defaultConversionService = new DefaultConversionService();defaultConversionService.addConverterFactory(new MyConvertFactory());Long convert = defaultConversionService.convert("1", Long.class);System.out.println(convert.getClass());}
3.GenericConverter
如何使用自定义Convert
官方文档中说了2种方式
- 注入:这种例子我没用SpringBoot方式演示出来,按照官方要求,结果出现了循环依赖
 - 直接new:就是我上面演示的,直接
new DefaultConversionService(); 
