SpringBoot使用参数类型转换器Converter
MethodArgumentTypeMismatchException
方法参数类型不匹配,此异常很常见。例如:
@RestController
public class HelloController {
@GetMapping("/hello")
public void hello(Date birth){
System.out.println(birth);
}
}
浏览器访问此接口,http://localhost:8080/hello?birth=2000-01-01,会出现此错误。
参数类型转换器
使用参数转换器(实现Converter接口),可解决此类问题。代码如下:
@Component
public class DataConverter implements Converter<String, Date> {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@Override
public Date convert(String s) {
if(!s.isEmpty()){
try {
return sdf.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}
上述方法实现参数从String到Date类型的转换。再次访问接口,控制台可打印日期对象。