Spring Boot 2.0 配置属性自定义转换的方法
作者:paderlol 发布时间:2021-10-18 12:07:44
引言
当我们通过@ConfigurationProperties注解实现配置 bean的时候,如果默认的配置属性转换无法满足我们的需求的时候,我们可以根据自己的需求通过以下扩展方式对配置属性进行转换
PropertyEditorSupport实现
下面的例子是把属性中定义的字符串转换成Movie,并且把name的值大写
继承PropertyEditorSupport并且实现PropertyEditorRegistrar接口
package com.paderlol.spring.practice.properties.editor;
import com.paderlol.spring.practice.properties.pojo.Movie;
import java.beans.PropertyEditorSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
/**
* @author pader PropertyEditor 在不同的包下面
*/
@Slf4j
public class CustomMovieEditor extends PropertyEditorSupport
implements PropertyEditorRegistrar {
@Override
public String getAsText() {
Movie movie = (Movie) getValue();
return movie == null ? "" : movie.getName();
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
log.info("继承[PropertyEditorSupport]类,转换数据={}", text);
String[] data = text.split("-");
Movie movie = Movie.builder().name(data[0]
.toUpperCase()).seat(Integer.parseInt(data[1]))
.build();
setValue(movie);
}
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Movie.class,this);
}
}
注册自定义的PropertyEditor
@Bean
public CustomEditorConfigurer customEditorConfigurer() {
CustomEditorConfigurer customEditorConfigurer = new CustomEditorConfigurer();
// 有两种注册方式 这是第一种
customEditorConfigurer.setPropertyEditorRegistrars(
new PropertyEditorRegistrar[]{ new CustomMovieEditor() });
// 第二 种
Map<Class<?>,Class<? extends PropertyEditor>> maps = new HashMap<>();
maps.put(Movie.class,CustomMovieEditor.class);
return customEditorConfigurer;
}
Converter接口+@ConfigurationPropertiesBinding注解
//注意
@Component
@ConfigurationPropertiesBinding
public class StringToPersonConverter implements Converter<String, Person> {
@Override
public Person convert(String from) {
log.info("使用[Converter]接口,转换数据={}", from);
String[] data = from.split(",");
return Person.builder().name(data[0]).age(Integer.parseInt(data[1])).build();
}
}
总结
以上两种实现方式结果,但是Converter接口相比PropertyEditor接口更加灵活一些,PropertyEditor接口仅限于String转换,Converter可以自定义别的,并且PropertyEditor接口通常用于Controller中的接收参数的转换。
@ConfigurationPropertiesBinding是限定符注解@Qualifier的派生类而已,参考org.springframework.boot.context.properties.ConversionServiceDeducer,以下是源代码片段
@Autowired(required = false)
@ConfigurationPropertiesBinding
public void setConverters(List<Converter<?, ?>> converters) {
this.converters = converters;
}
/**
* A list of custom converters (in addition to the defaults) to use when
* converting properties for binding.
* @param converters the converters to set
*/
@Autowired(required = false)
@ConfigurationPropertiesBinding
public void setGenericConverters(List<GenericConverter> converters) {
this.genericConverters = converters;
}
Formatter接口是不能对属性完成转换的,因为ConversionServiceDeducer初始化的时候只获取GenericConverter和Converter接口
官方文档上还介绍了可以使用实现org.springframework.core.convert.ConversionService并且Bean名称也必须叫conversionService,不过大部分情况不推荐自己通过这种方式去实现这个接口,因为自己实现的ConversionService会替代默认的。具体参考ConversionServiceDeducer源码:
public ConversionService getConversionService() {
try {
//默认首先寻找Bean名称叫conversionService的ConversionService的Bean类
return this.applicationContext.getBean(
ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME,
ConversionService.class);
}
catch (NoSuchBeanDefinitionException ex) {
//找不到就默认生成ApplicationConversionService类
return this.applicationContext.getAutowireCapableBeanFactory()
.createBean(Factory.class).create();
}
}
来源:https://segmentfault.com/a/1190000016941868


猜你喜欢
- 数组概述 C# 数组从零开始建立索引,即数组索引从零开始。C# 中数组的工作方式与在大多数其他流行语言中的工作方式类似。但还有一些差异应引起
- 这里给一个样例树:代码:#include <stdio.h> #include <string.h>#include
- 前段时间,有个同事说“30000000000000000000000000000000000000000000000000000000000
- 如图,左图是效果,右图是原理,右图X轴代表图像一个像素点的灰度,Y轴代表RGB三个颜色对应的伪彩色图颜色。代码如下:for (int y =
- 本文实例为大家分享了Spring MVC接口防数据篡改和重复提交的具体代码,供大家参考,具体内容如下一、自定义一个注解,此注解可以使用在方法
- 项目初始流程:首先说一下pom.xml文件的依赖: <dependencies><!-- junit 测试 -->
- 本文实例为大家分享了ManualResetEvent的使用方法,供大家参考,具体内容如下1. 源码下载:下载地址:ManualResetEv
- 1 二叉排序树的概述本文没有介绍一些基础知识。对于常见查找算法,比如顺序查找、二分查找、插入查找、斐波那契查找还不清楚的,可以看这篇文章:常
- 刚开始我以为熔断和降级是一体的,以为他们必须配合使用; 只不过名字不一样而已,但是当我经过思考过后,发现他们其实不是一个东西;降级什么是服务
- 写在前面:今天用保存QQ账号和密码的实战演练,带大家掌握Android存储中最基本的文件存储方式文件存储是Android中最基本的一种数据存
- 使用 Spring 时,XML 和注解是使用得最多的两种配置方式,虽然是两种完全不同的配置方式,但对于 IOC 容器来说,两种方式的不同主要
- spring容器初始化Bean操作在某些情况下,Spring容器在初始化Bean的时候,希望在初始化bean前和销毁bean前进行一些资源的
- 前言本文将实现一个MyBatis的Springboot的Starter包,引用这个Starter包后,仅需要提供少量配置信息,就能够完成My
- Java * 。具体有如下四步骤:通过实现 InvocationHandler 接口创建自己的调用处理器;通过为 Proxy 类指定 C
- 前言总结java常见的锁区分各个锁机制以及如何使用使用方法锁名考察线程是否要锁住同步资源乐观锁和悲观锁锁住同步资源后,要不要阻塞不阻塞可以使
- Xamarin写Android程序时,通常要使用按中文首字母分组显示(如通讯录) 。于是需要被迫包含CJK,不过包含后包肯定是会变大的,于是
- 最近正在学习使用Android Studio,发现默认的Hello World程序界面和我们
- 本文给大家分享Android里应用版本更新功能这一块的实现。一个好的应用软件都是需要好的维护,从初出版本到最后精品,这个过程需要版本不停的更
- 如何快速构建一个Spring Boot的项目工具 ideaJDK版本 1.8Spring Boot 版本 1.5.9环境搭建实现:最基础前端
- 简介OCSP在线证书状态协议是为了替换CRL而提出来的。对于现代web服务器来说一般都是支持OCSP的,OCSP也是现代web服务器的标配。