SpringBoot - Converter(转换器)

自定义转换器

@Configuration(proxyBeanMethods=false)
public class AppConfig {

    @Bean
    public WebMvcConfigurer getWebMvcConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addFormatters(FormatterRegistry registry) {
                //1.自定义类转换器 /test?reUser=levi.19
                registry.addConverter(new Converter<String, ReUser>() {
                    @Override
                    public ReUser convert(String source) {
                        if (!StringUtils.isEmpty(source)) {
                            String[] split = source.split(",");
                            ReUser reUser = new ReUser( split[0],Integer.parseInt(split[1]) );
                            return reUser;
                        }
                        return null;
                    }
                });
                //2.自定义时间转换器 /test?date=2019.12.01
                registry.addConverter(new Converter<String, LocalDate>() {
                    @Override
                    public LocalDate convert(String source) {
                        if (!StringUtils.isEmpty(source)) {
                            DateTimeFormatter dt = DateTimeFormatter.ofPattern("yyyy.MM.dd");
                            LocalDate localDate = LocalDate.parse(source, dt);
                            return localDate;
                        }
                        return null;
                    }
                });
            }
        };
    }
}

 

posted on 2021-12-12 21:42  每天积极向上  阅读(766)  评论(0编辑  收藏  举报

导航