怎么在Spring Boot中定制PropertyEditors方法
更新:HHH   时间:2023-1-8


这篇文章给大家介绍怎么在Spring Boot中定制PropertyEditors方法,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

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完成字符串到具体对象类型的转换,getAsText完成具体对象类型到字符串的转换。

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函数,通过@InitBinder注解修饰,则可以针对每个web请求创建一个editor实例。

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

修改BookController中对应的函数

@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一种全新的编程规范,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,SpringBoot也是一个服务于框架的框架,服务范围是简化配置文件。

关于怎么在Spring Boot中定制PropertyEditors方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

返回编程语言教程...