青羊区建设局网站,邯郸百度推广公司,福州正规网站建设公司推荐,wordpress博客在Spring中经常需要各种数据类型之间进行转换#xff0c;比如配置文件中的数据转换为代码所需要的数据类型#xff0c;在使用SpringMvc的时候#xff0c;将前台传来的参数自动转换为我们接收参数时定义的类型。
Spring中的ConversionService就是提供这种服务的
1.DefaultC…在Spring中经常需要各种数据类型之间进行转换比如配置文件中的数据转换为代码所需要的数据类型在使用SpringMvc的时候将前台传来的参数自动转换为我们接收参数时定义的类型。
Spring中的ConversionService就是提供这种服务的
1.DefaultConversionService
DefaultConversionService是一种默认的实现如果我们不定义就是使用默认的
Test
public void defaultConversionService(){ConversionService conversionService new DefaultConversionService();//这里是校验这个DefaultConversionService是否支持将String转换为Integerboolean b conversionService.canConvert(String.class, Integer.class);System.out.println(b);Long convert conversionService.convert(123, Long.class);System.out.println(convert);String convert1 conversionService.convert(new Date() , String.class);System.out.println(convert1);Date convert2 conversionService.convert(Mon Nov 04 23:32:14 CST 2024 , Date.class);System.out.println(convert2);}运行结果
true
123
Tue Nov 05 11:02:17 CST 2024
Tue Nov 05 13:32:14 CST 2024
我们可以看到这里DefaultConversionService 可以成功的将 String转换为Long将Date转换为String将String转换为Date
为什么DefaultConversionService能支持这么多数据类型之间的相互转换呢我们看看他的源码就知道了原来在DefaultConversionService构造方法中就调用addDefaultConverters()方法注册了我们常用的数据类型转换器Converter如果我们需要转换的时候它就会找一个能够完成转换的Converter进行转换
public class DefaultConversionService extends GenericConversionService {Nullableprivate static volatile DefaultConversionService sharedInstance;/*** Create a new {code DefaultConversionService} with the set of* {linkplain DefaultConversionService#addDefaultConverters(ConverterRegistry) default converters}.*/public DefaultConversionService() {addDefaultConverters(this);}/*** Return a shared default {code ConversionService} instance,* lazily building it once needed.* pbNOTE:/b We highly recommend constructing individual* {code ConversionService} instances for customization purposes.* This accessor is only meant as a fallback for code paths which* need simple type coercion but cannot access a longer-lived* {code ConversionService} instance any other way.* return the shared {code ConversionService} instance (never {code null})* since 4.3.5*/public static ConversionService getSharedInstance() {DefaultConversionService cs sharedInstance;if (cs null) {synchronized (DefaultConversionService.class) {cs sharedInstance;if (cs null) {cs new DefaultConversionService();sharedInstance cs;}}}return cs;}/*** Add converters appropriate for most environments.* param converterRegistry the registry of converters to add to* (must also be castable to ConversionService, e.g. being a {link ConfigurableConversionService})* throws ClassCastException if the given ConverterRegistry could not be cast to a ConversionService*/public static void addDefaultConverters(ConverterRegistry converterRegistry) {addScalarConverters(converterRegistry);addCollectionConverters(converterRegistry);converterRegistry.addConverter(new ByteBufferConverter((ConversionService) converterRegistry));converterRegistry.addConverter(new StringToTimeZoneConverter());converterRegistry.addConverter(new ZoneIdToTimeZoneConverter());converterRegistry.addConverter(new ZonedDateTimeToCalendarConverter());converterRegistry.addConverter(new ObjectToObjectConverter());converterRegistry.addConverter(new IdToEntityConverter((ConversionService) converterRegistry));converterRegistry.addConverter(new FallbackObjectToStringConverter());converterRegistry.addConverter(new ObjectToOptionalConverter((ConversionService) converterRegistry));}/*** Add common collection converters.* param converterRegistry the registry of converters to add to* (must also be castable to ConversionService, e.g. being a {link ConfigurableConversionService})* throws ClassCastException if the given ConverterRegistry could not be cast to a ConversionService* since 4.2.3*/public static void addCollectionConverters(ConverterRegistry converterRegistry) {ConversionService conversionService (ConversionService) converterRegistry;converterRegistry.addConverter(new ArrayToCollectionConverter(conversionService));converterRegistry.addConverter(new CollectionToArrayConverter(conversionService));converterRegistry.addConverter(new ArrayToArrayConverter(conversionService));converterRegistry.addConverter(new CollectionToCollectionConverter(conversionService));converterRegistry.addConverter(new MapToMapConverter(conversionService));converterRegistry.addConverter(new ArrayToStringConverter(conversionService));converterRegistry.addConverter(new StringToArrayConverter(conversionService));converterRegistry.addConverter(new ArrayToObjectConverter(conversionService));converterRegistry.addConverter(new ObjectToArrayConverter(conversionService));converterRegistry.addConverter(new CollectionToStringConverter(conversionService));converterRegistry.addConverter(new StringToCollectionConverter(conversionService));converterRegistry.addConverter(new CollectionToObjectConverter(conversionService));converterRegistry.addConverter(new ObjectToCollectionConverter(conversionService));converterRegistry.addConverter(new StreamConverter(conversionService));}private static void addScalarConverters(ConverterRegistry converterRegistry) {converterRegistry.addConverterFactory(new NumberToNumberConverterFactory());converterRegistry.addConverterFactory(new StringToNumberConverterFactory());converterRegistry.addConverter(Number.class, String.class, new ObjectToStringConverter());converterRegistry.addConverter(new StringToCharacterConverter());converterRegistry.addConverter(Character.class, String.class, new ObjectToStringConverter());converterRegistry.addConverter(new NumberToCharacterConverter());converterRegistry.addConverterFactory(new CharacterToNumberFactory());converterRegistry.addConverter(new StringToBooleanConverter());converterRegistry.addConverter(Boolean.class, String.class, new ObjectToStringConverter());converterRegistry.addConverterFactory(new StringToEnumConverterFactory());converterRegistry.addConverter(new EnumToStringConverter((ConversionService) converterRegistry));converterRegistry.addConverterFactory(new IntegerToEnumConverterFactory());converterRegistry.addConverter(new EnumToIntegerConverter((ConversionService) converterRegistry));converterRegistry.addConverter(new StringToLocaleConverter());converterRegistry.addConverter(Locale.class, String.class, new ObjectToStringConverter());converterRegistry.addConverter(new StringToCharsetConverter());converterRegistry.addConverter(Charset.class, String.class, new ObjectToStringConverter());converterRegistry.addConverter(new StringToCurrencyConverter());converterRegistry.addConverter(Currency.class, String.class, new ObjectToStringConverter());converterRegistry.addConverter(new StringToPropertiesConverter());converterRegistry.addConverter(new PropertiesToStringConverter());converterRegistry.addConverter(new StringToUUIDConverter());converterRegistry.addConverter(UUID.class, String.class, new ObjectToStringConverter());}}
2.DefaultFormattingConversionService
有的时候我们需要将某一种数据类型转换为指定的字符串格式也需要将指定格式的字符串转换为某一种数据类型比如我们需要将Date转为为yyyy-MM-dd格式的字符串。我们在配置文件配置yyyy-MM-dd 格式的字符串需要将其转换为Date类型的数据。在SpringMvc将数据返回给前端之前我们可能需要将Person类型的数据转换为JSON格式的字符串
这个时候我们就需要DefaultFormattingConversionService它在完成数据类型转换的同时还支持将某种数据类型转换为指定格式的字符串而且我们还可以自定义格式转换器来支持我们自定义的数据类型。
2.1 自定义Date和String之间转换的Formatter
Test
public void defaultFormattingConversionService(){DefaultFormattingConversionService conversionService new DefaultFormattingConversionService();conversionService.addFormatter(new FormatterDate() {Overridepublic String print(Date object, Locale locale) {return new SimpleDateFormat(yyyy-MM-dd HH:mm:ss).format(object);}Overridepublic Date parse(String text, Locale locale) throws ParseException {return new SimpleDateFormat(yyyy-MM-dd HH:mm:ss).parse(text);}});String convert1 conversionService.convert(new Date() , String.class);System.out.println(convert1);Date convert2 conversionService.convert(2024-11-04 23:52:36 , Date.class);System.out.println(convert2);}运行结果
2024-11-05 11:48:33
Mon Nov 04 23:52:36 CST 2024
上面的代码我们自定义了一个Date和String的Formatter那么DefaultFormattingConversionService在进行Date和String之间的相互转换时就会用我们自定义的Formatter 进行格式化和解析
Test
public void defaultFormattingConversionService(){DefaultFormattingConversionService conversionService new DefaultFormattingConversionService();conversionService.addFormatter(new FormatterDate() {Overridepublic String print(Date object, Locale locale) {return new SimpleDateFormat(yyyy-MM-dd HH:mm:ss).format(object);}Overridepublic Date parse(String text, Locale locale) throws ParseException {return new SimpleDateFormat(yyyy-MM-dd HH:mm:ss).parse(text);}});String convert1 conversionService.convert(new Date() , String.class);System.out.println(convert1);Date convert2 conversionService.convert(Mon Nov 04 23:32:14 CST 2024 , Date.class);System.out.println(convert2);}运行结果
org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value Mon Nov 04 23:32:14 CST 2024; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [Mon Nov 04 23:32:14 CST 2024]
这里报错了说明了我们添加了自定义的Formatter之后不支持将Mon Nov 04 23:32:14 CST 2024格式的字符串转换为Date类型了支持支将yyyy-MM-dd HH:mm:ss格式的字符串转换为Date类型说明之前默认的支持Mon Nov 04 23:32:14 CST 2024格式的Formatter被我们自定义Formatter给覆盖了
2.2 自定义Person和String之间转换的Formatter
Test
public void defaultFormattingConversionService1(){DefaultFormattingConversionService conversionService new DefaultFormattingConversionService();conversionService.addFormatter(new FormatterPerson() {Overridepublic String print(Person object, Locale locale) {return JSON.toJSONString(object);}Overridepublic Person parse(String text, Locale locale) throws ParseException {return JSON.parseObject(text , Person.class);}});Person person new Person();person.setName(孙悟空);person.setAge(20);String convert1 conversionService.convert(person , String.class);System.out.println(convert1);Person convert2 conversionService.convert(convert1 , Person.class);System.out.println(convert2);}运行结果:
{age:20,name:孙悟空}
Person{name孙悟空, age20}
我们看到成功将Person对象转换为我们自定义的JSON格式也可以成功将JSON格式的字符串转换为Person对象 文章转载自: http://www.morning.kqxng.cn.gov.cn.kqxng.cn http://www.morning.mwmtk.cn.gov.cn.mwmtk.cn http://www.morning.taipinghl.cn.gov.cn.taipinghl.cn http://www.morning.wrlxy.cn.gov.cn.wrlxy.cn http://www.morning.zhengdaotang.cn.gov.cn.zhengdaotang.cn http://www.morning.gbqgr.cn.gov.cn.gbqgr.cn http://www.morning.xctdn.cn.gov.cn.xctdn.cn http://www.morning.glnmm.cn.gov.cn.glnmm.cn http://www.morning.qnrpj.cn.gov.cn.qnrpj.cn http://www.morning.dmtbs.cn.gov.cn.dmtbs.cn http://www.morning.kydrb.cn.gov.cn.kydrb.cn http://www.morning.xprq.cn.gov.cn.xprq.cn http://www.morning.lzbut.cn.gov.cn.lzbut.cn http://www.morning.wyrkp.cn.gov.cn.wyrkp.cn http://www.morning.rkyw.cn.gov.cn.rkyw.cn http://www.morning.cprls.cn.gov.cn.cprls.cn http://www.morning.xxhc.cn.gov.cn.xxhc.cn http://www.morning.21r000.cn.gov.cn.21r000.cn http://www.morning.rfdqr.cn.gov.cn.rfdqr.cn http://www.morning.kqhlm.cn.gov.cn.kqhlm.cn http://www.morning.rnzwh.cn.gov.cn.rnzwh.cn http://www.morning.qcymf.cn.gov.cn.qcymf.cn http://www.morning.xglgm.cn.gov.cn.xglgm.cn http://www.morning.bzlfw.cn.gov.cn.bzlfw.cn http://www.morning.mjbnp.cn.gov.cn.mjbnp.cn http://www.morning.pjzcp.cn.gov.cn.pjzcp.cn http://www.morning.zxybw.cn.gov.cn.zxybw.cn http://www.morning.rbjth.cn.gov.cn.rbjth.cn http://www.morning.brwei.com.gov.cn.brwei.com http://www.morning.rdlong.com.gov.cn.rdlong.com http://www.morning.sskhm.cn.gov.cn.sskhm.cn http://www.morning.ey3h2d.cn.gov.cn.ey3h2d.cn http://www.morning.rbbzn.cn.gov.cn.rbbzn.cn http://www.morning.xfxqj.cn.gov.cn.xfxqj.cn http://www.morning.jyzqn.cn.gov.cn.jyzqn.cn http://www.morning.qnjcx.cn.gov.cn.qnjcx.cn http://www.morning.nnwpz.cn.gov.cn.nnwpz.cn http://www.morning.qrhh.cn.gov.cn.qrhh.cn http://www.morning.sryyt.cn.gov.cn.sryyt.cn http://www.morning.tkrpt.cn.gov.cn.tkrpt.cn http://www.morning.tlzbt.cn.gov.cn.tlzbt.cn http://www.morning.ttrdr.cn.gov.cn.ttrdr.cn http://www.morning.fgwzl.cn.gov.cn.fgwzl.cn http://www.morning.wjrtg.cn.gov.cn.wjrtg.cn http://www.morning.gcthj.cn.gov.cn.gcthj.cn http://www.morning.dfbeer.com.gov.cn.dfbeer.com http://www.morning.wwznd.cn.gov.cn.wwznd.cn http://www.morning.rwlns.cn.gov.cn.rwlns.cn http://www.morning.rnjgh.cn.gov.cn.rnjgh.cn http://www.morning.ttcmdsg.cn.gov.cn.ttcmdsg.cn http://www.morning.bmyrl.cn.gov.cn.bmyrl.cn http://www.morning.wfzdh.cn.gov.cn.wfzdh.cn http://www.morning.qmncj.cn.gov.cn.qmncj.cn http://www.morning.tbhlc.cn.gov.cn.tbhlc.cn http://www.morning.nnrqg.cn.gov.cn.nnrqg.cn http://www.morning.kgnnc.cn.gov.cn.kgnnc.cn http://www.morning.sjqml.cn.gov.cn.sjqml.cn http://www.morning.zmyzt.cn.gov.cn.zmyzt.cn http://www.morning.smsjx.cn.gov.cn.smsjx.cn http://www.morning.mxlmn.cn.gov.cn.mxlmn.cn http://www.morning.jhkzl.cn.gov.cn.jhkzl.cn http://www.morning.qdrhf.cn.gov.cn.qdrhf.cn http://www.morning.plwfx.cn.gov.cn.plwfx.cn http://www.morning.xxknq.cn.gov.cn.xxknq.cn http://www.morning.ffhlh.cn.gov.cn.ffhlh.cn http://www.morning.rynqh.cn.gov.cn.rynqh.cn http://www.morning.kwhrq.cn.gov.cn.kwhrq.cn http://www.morning.wrtpk.cn.gov.cn.wrtpk.cn http://www.morning.dqrhz.cn.gov.cn.dqrhz.cn http://www.morning.ymhzd.cn.gov.cn.ymhzd.cn http://www.morning.nlkhr.cn.gov.cn.nlkhr.cn http://www.morning.wjxyg.cn.gov.cn.wjxyg.cn http://www.morning.tjsxx.cn.gov.cn.tjsxx.cn http://www.morning.rrqgf.cn.gov.cn.rrqgf.cn http://www.morning.rdlfk.cn.gov.cn.rdlfk.cn http://www.morning.wwwghs.com.gov.cn.wwwghs.com http://www.morning.tqsgt.cn.gov.cn.tqsgt.cn http://www.morning.dmzmy.cn.gov.cn.dmzmy.cn http://www.morning.mdtfh.cn.gov.cn.mdtfh.cn http://www.morning.byxs.cn.gov.cn.byxs.cn