Spring Boot定制type Formatters實例詳解
前面我們有篇文章介紹了PropertyEditors,是用來將文本類型轉換成指定的Java類型,不過,考慮到PropertyEditor的無狀態(tài)和非線程安全特性,Spring 3增加了一個Formatter接口來替代它。Formatters提供和PropertyEditor類似的功能,但是提供線程安全特性,也可以實現(xiàn)字符串和對象類型的互相轉換。
假設在我們的程序中,需要根據(jù)一本書的ISBN字符串得到對應的book對象。通過這個類型格式化工具,我們可以在控制器的方法簽名中定義Book參數(shù),而URL參數(shù)只需要包含ISBN號和數(shù)據(jù)庫ID。
實戰(zhàn)
- 首先在項目根目錄下創(chuàng)建formatters包
- 然后創(chuàng)建BookFormatter,它實現(xiàn)了Formatter接口,實現(xiàn)兩個函數(shù):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)函數(shù)。
@Autowired
private BookRepository bookRepository;
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(new BookFormatter(bookRepository));
}
最后,需要在BookController中新加一個函數(shù)getReviewers,根據(jù)一本書的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注冊到系統(tǒng)中,然后Spring會自動完成文本表示的book和book實體對象之間的互相轉換。由于Formatter是無狀態(tài)的,因此不需要為每個請求都執(zhí)行注冊formatter的動作。
使用建議:如果需要通用類型的轉換——例如String或Boolean,最好使用PropertyEditor完成,因為這種需求可能不是全局需要的,只是某個Controller的定制功能需求。
我們在WebConfiguration中引入(@Autowired)了BookRepository(需要用它創(chuàng)建BookFormatter實例),Spring給配置文件提供了使用其他bean對象的能力。Spring本身會確保BookRepository先創(chuàng)建,然后在WebConfiguration類的創(chuàng)建過程中引入。
以上就是本次介紹的全部相關知識點內容,感謝大家的學習和對腳本之家的支持。
相關文章
SpringBoot實現(xiàn)excel生成并且通過郵件發(fā)送的步驟詳解
實際開發(fā)中,特別是在B端產(chǎn)品的開發(fā)中,我們經(jīng)常會遇到導出excel的功能,更進階一點的需要我們定期生成統(tǒng)計報表,然后通過郵箱發(fā)送給指定的人員,?今天要帶大家來實現(xiàn)的就是excel生成并通過郵件發(fā)送,需要的朋友可以參考下2023-10-10
Java多線程連續(xù)打印abc實現(xiàn)方法詳解
這篇文章主要介紹了Java多線程連續(xù)打印abc實現(xiàn)方法詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-03-03

