第十章 自定义转换器

基本介绍#

  1. SpringBoot 在响应客户端请求时,将提交的数据封装成对象时,使用了内置的转换器。
  2. SpringBoot 也支持自定义转换器,内置124个转换器。GenericConverter-ConvertiblePair。

应用实例#

演示自定义转换器使用。

修改 save.html#

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加妖怪</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="500"/> <br/>
    婚否: <input name="isMarried" value="true"/> <br/>
    生日: <input name="birth" value="2000/11/11"/> <br/>
    <!-- 使用自定义转换器关联car, 字符串整体提交, 使用,号间隔  -->
    坐骑:<input name="car" value="避水金晶兽,666.6"><br/>
    <!--    坐骑名称:<input name="car.name" value="法拉利"/><br/>-->
    <!--    坐骑价格:<input name="car.price" value="9999.9"/>-->
    <input type="submit" value="保存"/>
</form>
</body>
</html>

创建 src/main/java/com/lzw/springboot/config/WebConfig.java#

package com.lzw.springboot.config;

import com.lzw.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 LiAng
 * @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 方法中,增加一个自定义的转换器
                 * 2. 增加自定义转换器 String -> Car
                 * 3. 增加的自定义转换器会注册到 converters 容器中
                 * 4. converters 底层结构是 ConcurrentHashMap 内置有124转换器
                 */

                registry.addConverter(new Converter<String, Car>() {

                    @Override
                    public Car convert(String source) {//source就是 传入的字符串 避水金晶兽,666.6
                        //这里就加入你的自定义的转换业务代码
                        if(!ObjectUtils.isEmpty(source)){
                            String[] split = source.split(",");
                            Car car = new Car();
                            car.setName(split[0]);
                            car.setPrice(Double.parseDouble(split[1]));
                            return car;
                        }
                        return null;
                    }
                });

            }
        };
    }
}

image-20220803090145142
点击保存,看后台输出。

别的写法#

修改 WebConfig.java

	//注入bean WebMvcConfigurer
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addFormatters(FormatterRegistry registry) {
                
                //换种写法来注册自定义转换器-方便理解
                //1.先创建自定义转换器
                Converter<String, Car> lzwConverter = new Converter<String, Car>() {

                    @Override
                    public Car convert(String source) {//source就是 传入的字符串 避水金晶兽,666.6
                        //这里就加入你的自定义的转换业务代码
                        if (!ObjectUtils.isEmpty(source)) {
                            String[] split = source.split(",");
                            Car car = new Car();
                            car.setName(split[0]);
                            car.setPrice(Double.parseDouble(split[1]));
                            return car;
                        }
                        return null;
                    }
                };

                //还可以增加更多的转换器
                //第2个转换器
                Converter<String, Monster> lzwConverter2 = new Converter<String, Monster>() {

                    @Override
                    public Monster convert(String source) {//source就是 传入的字符串 避水金晶兽,666.6

                        return null;
                    }
                };

                //2.添加转换器到converters key-[源类型->目标类型]
                registry.addConverter(lzwConverter);
                registry.addConverter(lzwConverter2);

            }
        };
    }

测试完,恢复第一种写法。

posted @   LiAng88  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
主题色彩
点击右上角即可分享
微信分享提示
主题色彩