怎么在SpringBoot中定制PropertyEditors方法

這篇文章給大家介紹怎么在Spring Boot中定制PropertyEditors方法,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

創(chuàng)新互聯(lián)公司是一家從事企業(yè)網(wǎng)站建設(shè)、網(wǎng)站建設(shè)、成都網(wǎng)站制作、行業(yè)門戶網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)制作的專業(yè)網(wǎng)絡(luò)公司,擁有經(jīng)驗(yàn)豐富的網(wǎng)站建設(shè)工程師和網(wǎng)頁設(shè)計(jì)人員,具備各種規(guī)模與類型網(wǎng)站建設(shè)的實(shí)力,在網(wǎng)站建設(shè)領(lǐng)域樹立了自己獨(dú)特的設(shè)計(jì)風(fēng)格。自公司成立以來曾獨(dú)立設(shè)計(jì)制作的站點(diǎn)超過千家。

Isbn類:

package com.test.bookpub.utils;

public class Isbn {
  private String isbn;

  public Isbn(String isbn) {
    this.isbn = isbn;
  }
  public String getIsbn() {
    return isbn;
  }
}

IsbnEditor類,繼承PropertyEditorSupport類,setAsText完成字符串到具體對象類型的轉(zhuǎn)換,getAsText完成具體對象類型到字符串的轉(zhuǎn)換。

package com.test.bookpub.utils;
import org.springframework.util.StringUtils;
import java.beans.PropertyEditorSupport;

public class IsbnEditor extends PropertyEditorSupport {
  @Override
  public void setAsText(String text) throws IllegalArgumentException {
    if (StringUtils.hasText(text)) {
      setValue(new Isbn(text.trim()));
    } else {
      setValue(null);
    }
  }
  @Override  public String getAsText() {
    Isbn isbn = (Isbn) getValue();
    if (isbn != null) {
      return isbn.getIsbn();
    } else {
      return "";
    }
  }
}

在BookController中增加initBinder函數(shù),通過@InitBinder注解修飾,則可以針對每個(gè)web請求創(chuàng)建一個(gè)editor實(shí)例。

@InitBinderpublic 
void initBinder(WebDataBinder binder) {
  binder.registerCustomEditor(Isbn.class, new IsbnEditor());
}

修改BookController中對應(yīng)的函數(shù)

@RequestMapping(value = "/{isbn}", method = RequestMethod.GET)
public Map<String, Object> getBook(@PathVariable Isbn isbn) {
  Book book = bookRepository.findBookByIsbn(isbn.getIsbn());
  Map<String, Object> response = new LinkedHashMap<>();
  response.put("message", "get book with isbn(" + isbn.getIsbn() +")");
  response.put("book", book);  return response;
}

springboot是什么

springboot一種全新的編程規(guī)范,其設(shè)計(jì)目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程,SpringBoot也是一個(gè)服務(wù)于框架的框架,服務(wù)范圍是簡化配置文件。

關(guān)于怎么在Spring Boot中定制PropertyEditors方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

分享文章:怎么在SpringBoot中定制PropertyEditors方法
轉(zhuǎn)載來源:http://bm7419.com/article26/pschjg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站制作、網(wǎng)站改版網(wǎng)站排名、搜索引擎優(yōu)化、網(wǎng)站策劃、動(dòng)態(tài)網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都做網(wǎng)站