Spring Boot實戰之訂製type Formatters
- 2019 年 11 月 10 日
- 筆記
本文首發於個人網站:Spring Boot實戰之訂製type Formatters
前面我們有篇文章介紹了PropertyEditors,是用來將文本類型轉換成指定的Java類型,不過,考慮到PropertyEditor的無狀態和非執行緒安全特性,Spring 3增加了一個Formatter介面來替代它。Formatters提供和PropertyEditor類似的功能,但是提供執行緒安全特性,也可以實現字元串和對象類型的互相轉換。
假設在我們的程式中,需要根據一本書的ISBN字元串得到對應的book對象。通過這個類型格式化工具,我們可以在控制器的方法簽名中定義Book參數,而URL參數只需要包含ISBN號和資料庫ID。
實戰
- 首先在項目根目錄下創建formatters包
- 然後創建BookFormatter,它實現了Formatter介面,實現兩個函數:parse用於將字元串ISBN轉換成book對象;print用於將book對象轉換成該book對應的ISBN字元串。
package com.test.bookpub.formatters; import com.test.bookpub.domain.Book; import com.test.bookpub.repository.BookRepository; import org.springframework.format.Formatter; import java.text.ParseException; import java.util.Locale; public class BookFormatter implements Formatter<Book> { private BookRepository repository; public BookFormatter(BookRepository repository) { this.repository = repository; } @Override public Book parse(String bookIdentifier, Locale locale) throws ParseException { Book book = repository.findBookByIsbn(bookIdentifier); return book != null ? book : repository.findOne(Long.valueOf(bookIdentifier)); } @Override public String print(Book book, Locale locale) { return book.getIsbn(); } }
- 在WebConfiguration中添加我們定義的formatter,重寫(@Override修飾)addFormatter(FormatterRegistry registry)函數。
@Autowired private BookRepository bookRepository; @Override public void addFormatters(FormatterRegistry registry) { registry.addFormatter(new BookFormatter(bookRepository)); }
- 最後,需要在BookController中新加一個函數getReviewers,根據一本書的ISBN號獲取該書的審閱人。
@RequestMapping(value = "/{isbn}/reviewers", method = RequestMethod.GET) public List<Reviewer> getReviewers(@PathVariable("isbn") Book book) { return book.getReviewers(); }
- 通過
mvn spring-boot:run
運行程式 - 通過httpie訪問URL——http://localhost:8080/books/9781-1234-1111/reviewers,得到的結果如下:
HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Date: Tue, 08 Dec 2015 08:15:31 GMT Server: Apache-Coyote/1.1 Transfer-Encoding: chunked []
分析
Formatter工具的目標是提供跟PropertyEditor類似的功能。通過FormatterRegistry將我們自己的formtter註冊到系統中,然後Spring會自動完成文本表示的book和book實體對象之間的互相轉換。由於Formatter是無狀態的,因此不需要為每個請求都執行註冊formatter的動作。
使用建議:如果需要通用類型的轉換——例如String或Boolean,最好使用PropertyEditor完成,因為這種需求可能不是全局需要的,只是某個Controller的訂製功能需求。
我們在WebConfiguration中引入(@Autowired)了BookRepository(需要用它創建BookFormatter實例),Spring給配置文件提供了使用其他bean對象的能力。Spring本身會確保BookRepository先創建,然後在WebConfiguration類的創建過程中引入。
Spring Boot 1.x系列
- Spring Boot的自動配置、Command-line-Runner
- 了解Spring Boot的自動配置
- Spring Boot的@PropertySource註解在整合Redis中的使用
- Spring Boot項目中如何訂製HTTP消息轉換器
- Spring Boot整合Mongodb提供Restful介面
- Spring中bean的scope
- Spring Boot項目中使用事件派發器模式
- Spring Boot提供RESTful介面時的錯誤處理實踐
- Spring Boot實戰之訂製自己的starter
- Spring Boot項目如何同時支援HTTP和HTTPS協議
- 自定義的Spring Boot starter如何設置自動配置註解
- Spring Boot項目中使用Mockito
- 在Spring Boot項目中使用Spock測試框架
- Spring Boot項目中如何訂製攔截器
- Spring Boot項目中如何訂製PropertyEditors
- Spring Boot構建的Web項目如何在服務端校驗表單輸入
- Spring Boot應用的健康監控
- Spring Boot項目中如何訂製servlet-filters
- Spring Boot實戰之訂製URL匹配規則
本號專註於後端技術、JVM問題排查和優化、Java面試題、個人成長和自我管理等主題,為讀者提供一線開發者的工作和成長經驗,期待你能在這裡有所收穫。