Spring Boot项目中如何定制PropertyEditors

本文首发于我的网站:Spring Boot项目中如何定制PropertyEditorsjava

Spring Boot: 定制HTTP消息转换器一文中咱们学习了如何配置消息转换器用于HTTP请求和响应数据,实际上,在一次请求的完成过程当中还发生了其余的转换,咱们此次关注将参数转换成多种类型的对象,如:字符串转换成Date对象或字符串转换成Integer对象。web

在编写控制器中的action方法时,Spring容许咱们使用具体的数据类型定义函数签名,这是经过PropertyEditor实现的。PropertyEditor原本是JDK提供的API,用于将文本值转换成给定的类型,结果Spring的开发人员发现它刚好知足Spring的需求——将URL参数转换成函数的参数类型。面试

针对经常使用的类型(Boolean、Currency和Class),Spring MVC已经提供了不少PropertyEditor实现。假设咱们须要建立一个Isbn类并用它做为函数中的参数。spring

实战

  • 考虑到PropertyEditor属于工具范畴,选择在项目根目录下增长一个包——utils。在这个包下定义Isbn类和IsbnEditor类,各自代码以下: 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;
}
复制代码

运行程序,经过Httpie访问http localhost:8080/books/9781-1234-1111,能够获得正常结果,跟以前用String表示isbn时没什么不一样,说明咱们编写的IsbnEditor已经起做用了。后端

分析

Spring提供了不少默认的editor,咱们也能够经过继承PropertyEditorSupport实现本身定制化的editor。安全

因为ProperteyEditor是非线程安全的。经过@InitBinder注解修饰的initBinder函数,会为每一个web请求初始化一个editor实例,并经过WebDataBinder对象注册。app

Spring Boot 1.x系列

  1. Spring Boot的自动配置、Command-line-Runner
  2. 了解Spring Boot的自动配置
  3. Spring Boot的@PropertySource注解在整合Redis中的使用
  4. Spring Boot项目中如何定制HTTP消息转换器
  5. Spring Boot整合Mongodb提供Restful接口
  6. Spring中bean的scope
  7. Spring Boot项目中使用事件派发器模式
  8. Spring Boot提供RESTful接口时的错误处理实践
  9. Spring Boot实战之定制本身的starter
  10. Spring Boot项目如何同时支持HTTP和HTTPS协议
  11. 自定义的Spring Boot starter如何设置自动配置注解
  12. Spring Boot项目中使用Mockito
  13. 在Spring Boot项目中使用Spock测试框架

本号专一于后端技术、JVM问题排查和优化、Java面试题、我的成长和自我管理等主题,为读者提供一线开发者的工做和成长经验,期待你能在这里有所收获。框架

javaadu
相关文章
相关标签/搜索