spring mvc自定义类型转换器

参考spring boot 配置全局日期类型转换器

1 定义转换器

@Component
public class DateConvert implements Converter<String,Date> {

    @Override
    public Date convert(String source) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return simpleDateFormat.parse(source);
        }catch (ParseException e){
            e.printStackTrace();
        }
        return null;
    }
}

2 在配置文件中注册转换器

@ComponentScan(value = "com.cc")
@Configuration
public class ApplicationConfig extends WebMvcConfigurationSupport{
    @Autowired
    private ConfigurableConversionService conversionService;

    @Autowired
    private DateConvert dateConvert;

    public ApplicationConfig() {
        System.out.println("应用启动……");
    }

    @PostConstruct
    public void initEditableAvlidation(){
        if (conversionService!=null){
            conversionService.addConverter(dateConvert);
        }
    }

3 说明

ConfigurableConversionService

用于注册convert

@PostConstruct

被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。

@PreDestroy

@PreDestroy修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前。(详见下面的程序实践)

猜你喜欢

转载自blog.csdn.net/ccoran/article/details/85124918