SpringBoot中Formatter和Converter用法和區(qū)別小結(jié)
功能區(qū)別:
兩者的作用一樣,都是類型轉(zhuǎn)換。
- org.springframework.format.Formatter只能做String類型到其他類型的轉(zhuǎn)換。
- org.springframework.core.convert.converter.Converter可以做任意類型的轉(zhuǎn)換。
Converter是一般工具,可以將一種類型轉(zhuǎn)換成另一種類型。例如,將String轉(zhuǎn)換成Date,或者將Long轉(zhuǎn)換成Date。Converter既可以用在web層,也可以用在其它層中。Formatter只能將String轉(zhuǎn)成成另一種java類型。例如,將String轉(zhuǎn)換成Date,但它不能將Long轉(zhuǎn)換成Date。
Formatter
Formatter使用示例:
1.定義Formatter類:
需要實(shí)現(xiàn)Formatter接口, 并在pase方法中進(jìn)行轉(zhuǎn)換的邏輯。通過(guò)@Component自動(dòng)將其添加到SpringBoot容器,這樣就會(huì)自動(dòng)生效。
@Component
public class StudentFormatter implements Formatter<Student> {
/**
* 校驗(yàn)不太嚴(yán)密,僅作演示
*/
@Override
public Student parse(String text, Locale locale) {
if (NumberUtils.isParsable(text)) {
Student s = new Student();
s.setAge(Integer.parseInt(text));
return s;
}
return null;
}
@Override
public String print(Student money, Locale locale) {
if (money == null) {
return null;
}
return money.getAge()+"";
}
}2.Controller中的代碼:
@PostMapping(path = "/stu")
@ResponseBody
public String sst(NewRequest newCoffee) {
return newCoffee.getStudent().getAge()+"";
}數(shù)據(jù)實(shí)體:
@Getter
@Setter
@ToString
public class NewRequest {
private String name;
private Student student;
}3.訪問(wèn):http://localhost:8080/stu
采用application/x-www-form-urlencoded 參數(shù)類型傳遞參數(shù)。
這樣服務(wù)端收到參數(shù),就會(huì)自動(dòng)將字符串轉(zhuǎn)換成一個(gè)Student對(duì)象。

注意點(diǎn):這里采用了application/x-www-form-urlencoded提交參數(shù),所以在Controller中不能加@RequestBody,并且參數(shù)名稱要和數(shù)據(jù)對(duì)象的屬性保持一致。如果采用json格式數(shù)據(jù)交互,測(cè)試發(fā)現(xiàn)解析報(bào)錯(cuò)。
{
"timestamp": "2019-09-05T07:42:00.809+0000",
"status": 400,
"error": "Bad Request",
"message": "JSON parse error: Current token (VALUE_STRING) not numeric, can not use numeric value accessors; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Current token (VALUE_STRING) not numeric, can not use numeric value accessors\n at [Source: (PushbackInputStream); line: 1, column: 29] (through reference chain: geektime.spring.springbucks.waiter.controller.request.NewCoffeeRequest[\"price\"])",
"path": "/coffee/addJson"
}說(shuō)明在轉(zhuǎn)換成自定義的對(duì)象時(shí),必須通過(guò)form格式進(jìn)行傳參。
但奇怪的是Date類型的轉(zhuǎn)換,通過(guò)json格式傳遞參數(shù),可以正常轉(zhuǎn)換。 如下:
@Component
public class DateFormatter implements Formatter<Date> {
@Override
public Date parse(String text, Locale locale) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
System.out.println("parse input text: " + text);
System.out.println("parse date: " + dateFormat.parse(text));
return dateFormat.parse(text);
}
@Override
public String print(Date object, Locale locale) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
System.out.println("print method." + object);
return dateFormat.format(object);
}
}Controller中:
@ResponseBody
@PostMapping(path = "/date")
public String formatterStringToDate(@RequestBody ZXRequest date) {
System.out.println("action method: " + date.getDate().getTime());
return date.getDate().getTime()+"";
}數(shù)據(jù)類:
@Getter
@Setter
@ToString
public class ZXRequest {
private Date date;
}訪問(wèn):

可以正常返回。說(shuō)明轉(zhuǎn)換正確。關(guān)于原因,目前尚不清楚,有知道的,希望留言。
Converter使用示例:
1.創(chuàng)建轉(zhuǎn)換類:其他步驟和Formatter完全一樣。
@Component
public class StudentConvert implements Converter<String ,Student> {
@Override
public Student convert(String text) {
if (NumberUtils.isParsable(text)) {
Student s = new Student();
s.setAge(Integer.parseInt(text));
return s;
}
return new Student();
}
}如果同時(shí)定義了Converter和Formatter,并且轉(zhuǎn)換同一個(gè)類型,會(huì)采用哪個(gè)進(jìn)行轉(zhuǎn)換?
測(cè)試證明,同時(shí)定義Student的轉(zhuǎn)換類,會(huì)采用Formatter。
到此這篇關(guān)于SpringBoot中Formatter和Converter用法和區(qū)別小結(jié)的文章就介紹到這了,更多相關(guān)SpringBoot Formatter Converter 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JDK17前后寫(xiě)法超詳細(xì)對(duì)比(差點(diǎn)沒(méi)認(rèn)出是Java)
在實(shí)際應(yīng)用中,開(kāi)發(fā)人員可以根據(jù)項(xiàng)目需求選擇合適的JDK版本,例如,對(duì)于需要高運(yùn)行效率和低延遲的應(yīng)用,可以選擇最新版本的JDK,以便獲得更好的性能和特性支持,這篇文章主要介紹了JDK17前后寫(xiě)法超詳細(xì)對(duì)比的相關(guān)資料,需要的朋友可以參考下2026-04-04
mybatis-flex實(shí)現(xiàn)多數(shù)據(jù)源操作
MyBaits-Flex內(nèi)置了功能完善的多數(shù)據(jù)源支持,本文主要介紹了mybatis-flex實(shí)現(xiàn)多數(shù)據(jù)源操作,具有一定的參考價(jià)值,感興趣的可以了解一下2024-06-06
Java 字符串截取及常見(jiàn)場(chǎng)景與方法詳解
在 Java 開(kāi)發(fā)中,截取字符串是一個(gè)非常常見(jiàn)的操作,無(wú)論是獲取文件名還是提取某些特定內(nèi)容,本文詳細(xì)介紹了截取字符串最后一位及其他常見(jiàn)截取操作的多種方法,幫助開(kāi)發(fā)者快速上手,感興趣的朋友跟隨小編一起看看吧2024-12-12

