龙空技术网

Springboot配置自定义转换器Converter

三流程序员南宫 201

前言:

现在姐妹们对“xml文件格式转换器”大约比较注重,我们都想要知道一些“xml文件格式转换器”的相关内容。那么小编在网络上搜集了一些有关“xml文件格式转换器””的相关内容,希望我们能喜欢,朋友们快快来了解一下吧!

WebMvcConfigurer配置类其实是Spring内部的一种配置方式,采用JavaBean的形式来代替传统的xml配置文件形式进行针对框架个性化定制,可以自定义一些Handler,Interceptor,ViewResolver,MessageConverter。

自定义转换器类

package com.example.demo.converter;import org.springframework.core.convert.converter.Converter;import org.springframework.stereotype.Component;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class DateConverter implements Converter<String, Date> {    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");    @Override    public Date convert(String source) {        try {            return simpleDateFormat.parse(source);        } catch (ParseException e) {            e.printStackTrace();        }        return new Date();    }}
配置方法一:

使用配置类@Configuration注解,实现WebMvcConfigurer

@Configurationpublic class ResourcesConfig implements WebMvcConfigurer{    @Override    public void addFormatters(FormatterRegistry registry) {        registry.addConverter(new DateConverter());    }}
配置方法二:

直接给转换器类加注解@Component

@Componentpublic class DateConverter implements Converter<String, Date> {    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");    @Override    public Date convert(String source) {        try {            return simpleDateFormat.parse(source);        } catch (ParseException e) {            e.printStackTrace();        }        return new Date();    }}

标签: #xml文件格式转换器