一、自定义类型转换器:
package cn.edu.tju.component;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class MyDateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
return new Date(source.replace("--", "/"));
}
}
二、将自定义类型转换器注册到Spring boot文章来源:https://www.toymoban.com/news/detail-691808.html
package cn.edu.tju.config;
import cn.edu.tju.component.MyDateConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
System.out.println("My converter called......");
registry.addConverter(new MyDateConverter());
}
}
三、请求测试:文章来源地址https://www.toymoban.com/news/detail-691808.html
@RequestMapping("/hi3")
public String hi3(Date date){
System.out.println(date);
return "hi3";
}
http://localhost:9908/hi3?date=2023--09--23
到了这里,关于SpringBoot复习:(59)自定义类型转换器的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!