当我们在controller方法的入参为一个javabean类型并且没有使用任何注解进行标注,springboot将会使用ServletModelAttributeMethodProcessor方法处理器对请求参数和javaBean对象的属性进行绑定,在ServletModelAttributeMethodProcessor内部会调用参数转换器将请求参数与javaBean的属性对象进行类型转换再使用反射进行参数绑定,例如 请求参数时string类型,属性值为int类型,当然我们也可以自己定义类型转换器。
要实现自定义的类型转换器有两种实现模式:
一种是实现Formatter接口(这种方式默认时String类型转其他类型)
一种是实现Converter(自定义某种类型转换到某种类型)
实现Formatter接口
public class MyDateFormatter implements Formatter{ @Override public LocalDateTime parse(String text, Locale locale) throws ParseException { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); return LocalDateTime.parse(text,dateTimeFormatter); } @Override public String print(LocalDateTime object, Locale locale) { return null; } }
实现Converter接口
public class MyDateConverter implements Converter{ @Override public LocalDateTime convert(String source) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); return LocalDateTime.parse(source, dateTimeFormatter); } }
添加转换器:
@Configuration
public class WebConfigure implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(new MyDateFormatter());
//registry.addConverter(new MyDateConverter());
}
}



