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;
                    }
                });
            }
        };
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM