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类的创建过程中引入。

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测试框架
  14. Spring Boot项目中如何定制拦截器
  15. Spring Boot项目中如何定制PropertyEditors
  16. Spring Boot构建的Web项目如何在服务端校验表单输入
  17. Spring Boot应用的健康监控
  18. Spring Boot项目中如何定制servlet-filters
  19. Spring Boot实战之定制URL匹配规则

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

原文地址:https://www.cnblogs.com/javaadu/p/11828288.html

时间: 2024-08-01 09:41:59

Spring Boot实战之定制type Formatters的相关文章

Spring Boot实战之定制URL匹配规则

本文首发于个人网站:Spring Boot实战之定制URL匹配规则 构建web应用程序时,并不是所有的URL请求都遵循默认的规则.有时,我们希望RESTful URL匹配的时候包含定界符".",这种情况在Spring中可以称之为"定界符定义的格式":有时,我们希望识别斜杠的存在.Spring提供了接口供开发人员按照需求定制. 在之前的几篇文章中,可以通过WebConfiguration类来定制程序中的过滤器.格式化工具等等,同样得,也可以在这个类中用类似的办法配置&

《Spring Boot实战》笔记(目录)

目录 目 录第一部分 点睛Spring 4.x第1 章 Spring 基础 ............................................................................................................. 21.1 Spring 概述 .......................................................................................

Spring Boot实战之Filter实现使用JWT进行接口认证

Spring Boot实战之Filter实现使用JWT进行接口认证 jwt(json web token) 用户发送按照约定,向服务端发送 Header.Payload 和 Signature,并包含认证信息(密码),验证通过后服务端返回一个token,之后用户使用该token作为登录凭证,适合于移动端和api jwt使用流程 本文示例接上面几篇文章中的代码进行编写,请阅读本文的同时可以参考前面几篇文章 1.添加依赖库jjwt,本文中构造jwt及解析jwt都使用了jjwt库 <dependenc

spring boot 实战随书源码

spring boot 实战 -汪云飞 随书源码 点击下载

spring boot之session store type is &#39;null&#39;

在网上搜索之后,发现session store type使用来存放session的存储方式,目前Spring boot中只支持Redis方式. 由于本应用暂无需将session放入redis的需求,故这里就可以将session store type设置为none. 这里我们将此配置信息放入application.properites之中: # default-store in spring session. it will be set in redis only outside. spring

《Spring Boot实战》示例代码问题

* Idea环境 * <Java EE开发的颠覆者 Spring Boot实战> 1.2.2 Spring EL 读取文件获取不到: 需把test.txt和test.properties放在resource文件下,将resource文件标记为资源目录,将引用目录换为"classpath:test.txt"就可以. 2. 2.4  Profile 运行报错:GenericApplicationContext does not support multiple refresh

Spring Boot实战系列(7)集成Consul配置中心

本篇主要介绍了 Spring Boot 如何与 Consul 进行集成,Consul 只是服务注册的一种实现,还有其它的例如 Zookeeper.Etcd 等,服务注册发现在微服务架构中扮演这一个重要的角色,伴随着服务的大量出现,服务与服务之间的配置管理.运维管理也变的难以维护,通过 Consul 可以解决这些问题,实现服务治理.服务监控. 关于 Consul 的更多知识点不在这里赘述,但是在学习本节之前还是希望您能先了解下,请移步我之前写的 微服务服务注册发现之 Consul 系列 快速导航

Spring Boot 实战

原文引用https://www.dazhuanlan.com/2019/08/26/5d630071b1ce1/ 打开google 打开springboot资料 Search or jump to- Pull requests Issues Marketplace Explore @shandudu 59 1,084 316 hansonwang99/Spring-Boot-In-Action Code Issues 0 Pull requests 0 Projects 0 Wiki Secur

Spring Boot实战与原理分析

1:Spring Boot概述与课程概要介绍 2:Spring4 快速入门 3:Spring4 扩展分析(一) 4:Spring4 扩展分析(二) 5:Spring Boot 快速入门 6:Spring Boot 配置分析(一) 7:Spring Boot 配置分析(二) 8:Spring Boot 自动配置 9:Spring Boot @Enable*注解的工作原理 10:Spring Boot @EnableAutoConfiguration深入分析 11:Spring Boot 事件监听