当前位置:网站首页>11. Custom Converter
11. Custom Converter
2022-08-10 23:48:00 【If you want to learn, learn Big Wolf】
文章目录
11.1 基本介绍
- SpringBoot 在响应客户端请求时,Encapsulate the submitted data into objects时,使用了内置的转换器
- SpringBoot Custom converters are also supported,This built-in converter is in debug 的时候,可以看到
- 提供了 124 a built-in converter
- 看下源码 GenericConverter-ConvertiblePair


11.2 自定义转换器-应用实例
11.2.1 需求说明:Demonstrate custom converter usage

11.2.2 代码实现
- 修改 save.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add little monsters</title>
</head>
<body>
<h1>添加妖怪-坐骑[测试封装 POJO]</h1>
<form action="/saveMonster" method="post">
编号: <input name="id" value="100"><br/>
姓名: <input name="name" value="牛魔王"/> <br/>
年龄: <input name="age" value="120"/> <br/>
婚否: <input name="isMarried" value="true"/> <br/>
生日: <input name="birth" value="2000/11/11"/> <br/>
<!--坐骑: <input name="car.name" value="法拉利"/><br/>-->
<!--价格: <input name="car.price" value="99999.9"/>-->
<!--Use custom converter associationsCar, The string as a whole is submitted 使用 ,号 间隔-->
坐骑: <input name="car" value="避水金睛兽,888.8"/><br/>
<input type="submit" value="保存"/>
</form>
</body>
</html>
- 创建自定义转换器 D:\xjs_springboot\springbootweb\src\main\java\com\xjs\springboot\config\WebConfig.java
package com.xjs.springboot.config;
import com.xjs.springboot.bean.Car;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/** * @Author: 谢家升 * @Version: 1.0 */
/** * 解读:@Configuration(proxyBeanMethods = false) * 1. WebConfig 是一个配置类 * 2. proxyBeanMethods = false 表示使用了 lite模式 */
@Configuration(proxyBeanMethods = false)
public class WebConfig {
//注入一个Bean WebMvcConfigurer
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addFormatters(FormatterRegistry registry) {
/** * 解读: * 1. 在 addFormatters 方法中,Add a custom converter * 2. Add custom converters String -> Car * 3. Added custom converters will be registered to converters 容器中 * 4. converters 底层结构是 ConcurrentHashMap 内置有124个转换器[The number of different versions may vary] * 5. 一会儿 Debug */
registry.addConverter(new Converter<String, Car>() {
@Override
public Car convert(String source) {
//source 就是传入的字符串 => 避水金睛兽,888.8
//Add your custom conversion business code here
if (!ObjectUtils.isEmpty(source)) {
Car car = new Car();
String[] split = source.split(",");
car.setName(split[0]);
car.setPrice(Double.parseDouble(split[1]));
return car;
}
return null;
}
});
}
};
}
}
- 完成测试,浏览器 http://localhost:8080/save.html

monster-Monster(id=100, name=牛魔王, age=120, isMarried=true, birth=Sat Nov 11 00:00:00 CST 2000, car=Car(name=避水金睛兽, price=888.8))
- Debug 可以看到我们新增的 Converter




11.2.3 Register the converter in a different way-方便理解
package com.xjs.springboot.config;
import com.xjs.springboot.bean.Car;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/** * @Author: 谢家升 * @Version: 1.0 */
/** * 解读:@Configuration(proxyBeanMethods = false) * 1. WebConfig 是一个配置类 * 2. proxyBeanMethods = false 表示使用了 lite模式 */
@Configuration(proxyBeanMethods = false)
public class WebConfig {
//注入一个Bean WebMvcConfigurer
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addFormatters(FormatterRegistry registry) {
/** * 解读: * 1. 在 addFormatters 方法中,Add a custom converter * 2. Add custom converters String -> Car * 3. Added custom converters will be registered to converters 容器中 * 4. converters 底层结构是 ConcurrentHashMap 内置有124个转换器[The number of different versions may vary] * 5. 一会儿 Debug */
//registry.addConverter(new Converter<String, Car>() {
// @Override
// public Car convert(String source) { //source 就是传入的字符串 => 避水金睛兽,888.8
// //Add your custom conversion business code here
// if (!ObjectUtils.isEmpty(source)) {
//
// Car car = new Car();
// String[] split = source.split(",");
// car.setName(split[0]);
// car.setPrice(Double.parseDouble(split[1]));
// return car;
//
// }
// return null;
// }
//});
//Write another way to register custom converters-方便理解
//1. Create a custom converter first
Converter<String, Car> xjsConverter = new Converter<String, Car>() {
@Override
public Car convert(String source) {
//source 就是传入的字符串 => 避水金睛兽,888.8
//Add your custom conversion business code here
if (!ObjectUtils.isEmpty(source)) {
Car car = new Car();
String[] split = source.split(",");
car.setName(split[0]);
car.setPrice(Double.parseDouble(split[1]));
return car;
}
return null;
}
};
//More converters can also be added
//2. Add converter to converters
registry.addConverter(xjsConverter);
}
};
}
}
----- 细节说明 -----
- Add converter to converters
key=>[源类型->目标类型]- converters 底层是 ConcurrentHashMap
- 其中key是 [源类型->目标类型]
- So when two converters are 源类型 和 目标类型 相同,则会覆盖
- 这里添加的 第3a custom converter 会覆盖 第1a custom converter [都是 String -> Car]
package com.xjs.springboot.config;
import com.xjs.springboot.bean.Car;
import com.xjs.springboot.bean.Monster;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/** * @Author: 谢家升 * @Version: 1.0 */
/** * 解读:@Configuration(proxyBeanMethods = false) * 1. WebConfig 是一个配置类 * 2. proxyBeanMethods = false 表示使用了 lite模式 */
@Configuration(proxyBeanMethods = false)
public class WebConfig {
//注入一个Bean WebMvcConfigurer
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addFormatters(FormatterRegistry registry) {
/** * 解读: * 1. 在 addFormatters 方法中,Add a custom converter * 2. Add custom converters String -> Car * 3. Added custom converters will be registered to converters 容器中 * 4. converters 底层结构是 ConcurrentHashMap 内置有124个转换器[The number of different versions may vary] * 5. 一会儿 Debug */
//registry.addConverter(new Converter<String, Car>() {
// @Override
// public Car convert(String source) { //source 就是传入的字符串 => 避水金睛兽,888.8
// //Add your custom conversion business code here
// if (!ObjectUtils.isEmpty(source)) {
//
// Car car = new Car();
// String[] split = source.split(",");
// car.setName(split[0]);
// car.setPrice(Double.parseDouble(split[1]));
// return car;
//
// }
// return null;
// }
//});
//Write another way to register custom converters-方便理解
//1. Create a custom converter first
Converter<String, Car> xjsConverter = new Converter<String, Car>() {
@Override
public Car convert(String source) {
//source 就是传入的字符串 => 避水金睛兽,888.8
//Add your custom conversion business code here
if (!ObjectUtils.isEmpty(source)) {
Car car = new Car();
String[] split = source.split(",");
car.setName(split[0]);
car.setPrice(Double.parseDouble(split[1]));
return car;
}
return null;
}
};
//More converters can also be added
//第2a custom converter
Converter<String, Monster> xjsConverter2 = new Converter<String, Monster>() {
@Override
public Monster convert(String source) {
//source 就是传入的字符串 => 避水金睛兽,888.8
//Add your custom conversion business code here
return null;
}
};
//第3a custom converter
Converter<String, Car> xjsConverter3 = new Converter<String, Car>() {
@Override
public Car convert(String source) {
//source 就是传入的字符串 => 避水金睛兽,888.8
System.out.println("source= " + source);
return null;
}
};
//2. Add converter to converters key-[源类型->目标类型]
// (1) converters 底层是 ConcurrentHashMap
// (2) 其中key是 [源类型->目标类型]
// (3) So when two converters the source type and 目标类型 相同,则会覆盖
// (4) 这里添加的 第3a custom converter 会覆盖 第1a custom converter
registry.addConverter(xjsConverter);
registry.addConverter(xjsConverter2);
registry.addConverter(xjsConverter3);
}
};
}
}
边栏推荐
- Excel English automatic translation into Chinese tutorial
- 祥云杯 2021 PackageManager writeup
- 2022牛客多校(七)K. Great Party博弈方法证明
- Kubernetes 选举机制HA
- Android面试冲刺:2022全新面试题——剑指Offer(备战金九银十)
- There is no recycle bin for deleted files on the computer desktop, what should I do if the deleted files on the desktop cannot be found in the recycle bin?
- 正交基(线性代数)
- 2. 依赖管理和自动配置
- Mathematical modeling preparation knowledge
- Promote the high-quality development of denim clothing
猜你喜欢
随机推荐
性能不够,机器来凑;jvm调优实战操作详解
小程序平台工具如何选择和使用?
CW617N锡青铜 CuZn40Pb2对应牌号
Google Chrome73~81版本浏览器的跨域问题解决方案
逮到一个阿里 10 年老 测试开发,聊过之后收益良多...
Kubernetes 维护技术分享
开源一夏|OpenHarmony如何选择图片在Image组件上显示(eTS)
sqlmap结合dnslog快速注入
[C Language Chapter] Detailed explanation of bitwise operators (“<<”, “>>”, “&”, “|”, “^”, “~”)
Kubernetes你不知道的事
How to determine how many bases a number is?
Which translation software is more accurate [Free]
Rust从入门到精通05-语句和表达式
12. 处理 JSON
基于SSM实现手机销售商城系统
Geogebra 教程之 01 什么是Geogebra,真的可以提高我们数学水平么?
promise详解
Unity--URP渲染管线实战教程系列之URP摄像机核心机制剖析
proxy代理服务_2
三栏布局实现




![[C language] binary search (half search)](/img/24/4e7b54963ac9df4a3244232c32c435.png)
![[C language] Detailed explanation of data storage](/img/3f/3799a3ba0f2642272e15bd7a3e511f.png)


