Spring Boot:定制PropertyEditors

简介:

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

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

针对常用的类型(Boolean、Currency和Class),Spring MVC已经提供了很多PropertyEditor实现。假设我们需要创建一个Isbn类并用它作为函数中的参数。

How Do

  • 考虑到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对象注册。



目录
相关文章
|
21天前
|
Java 应用服务中间件 Maven
SpringBoot 项目瘦身指南
SpringBoot 项目瘦身指南
38 0
|
2天前
|
XML Java C++
【Spring系列】Sping VS Sping Boot区别与联系
【4月更文挑战第2天】Spring系列第一课:Spring Boot 能力介绍及简单实践
23 0
【Spring系列】Sping VS Sping Boot区别与联系
|
2月前
|
XML 监控 druid
【Java专题_02】springboot+mybatis+pagehelper分页插件+druid数据源详细教程
【Java专题_02】springboot+mybatis+pagehelper分页插件+druid数据源详细教程
|
3月前
|
Java
springboot项目打包瘦身
springboot项目打包瘦身
|
5月前
|
Java 测试技术
Springboot集成JUnit5优雅进行单元测试
Springboot集成JUnit5优雅进行单元测试
|
安全 Java Maven
Spring Boot资源文件问题总结(Spring Boot的静态资源访问,配置文件外置)
Spring Boot资源文件问题总结(Spring Boot的静态资源访问,配置文件外置)
1295 1
|
9月前
|
Java Maven
【Springboot】创建boot工程spring-boot-maven-plugin报红、出错_解决方案
【Springboot】创建boot工程spring-boot-maven-plugin报红、出错_解决方案
313 0
|
9月前
|
SQL druid 前端开发
让SpringBoot不需要Controller、Service、DAO、Mapper,卧槽!这款工具绝了!
让SpringBoot不需要Controller、Service、DAO、Mapper,卧槽!这款工具绝了!
|
11月前
|
Java C++ Spring
Spring Boot - ConfigDataEnvironmentPostProcessor(Boot 2.4)搞定配置文件加载优先级
Spring Boot - ConfigDataEnvironmentPostProcessor(Boot 2.4)搞定配置文件加载优先级
236 0
|
Java Spring
Spring Cloud版本冲突(java.lang.NoClassDefFoundError:org/springframework/boot/Bootstrapper)
Spring Cloud版本冲突(java.lang.NoClassDefFoundError:org/springframework/boot/Bootstrapper)
92 0
Spring Cloud版本冲突(java.lang.NoClassDefFoundError:org/springframework/boot/Bootstrapper)