1. 程式人生 > 程式設計 >Spring Boot定製type Formatters例項詳解

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類的建立過程中引入。

以上就是本次介紹的全部相關知識點內容,感謝大家的學習和對我們的支援。