使用SpringBoot的@ConfigurationProperties机制加载.properties或.yaml文件时,对于java类型为primitive type、String、日期或时间以及它们对应的数组和集合等类型,SpringBoot会自动将配置文件中的属性值,根据java属性的类型正确解析。
处理过程中会使用转换器(org.springframework.core.convert.converter.Converter),
SpringBoot默认要加载的转换器都配置在如下类中:
org.springframework.boot.convert.ApplicationConversionService
但对于一些自定义类型,如果需要SpringBoot能正解析并能正确的创建这此类型的对象,则需要自己实现org.springframework.core.convert.converter.Converter接口,并实现类上使用注解@ConfigurationPropertiesBinding
下面举例说明:
application.yaml
server:
testUrl: http://127.0.0.1:8080
codec: org.redisson.codec.Kryo5Codec
存放属性的java类
@Configuration
@ConfigurationProperties(prefix = "server")
public class ConfigProperties {private URL testUrl;private Codec codec;public URL getTestUrl() {return testUrl;}public void setTestUrl(URL testUrl) {this.testUrl = testUrl;}public Codec getCodec() {return codec;}public void setCodec(Codec codec) {this.codec = codec;}
}
转换器类
import java.net.URL;import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;@Component
@ConfigurationPropertiesBinding
public class URLConverter implements Converter {@Overridepublic URL convert(String source) {try {if (StringUtils.hasLength(source)) {return new URL(source);}} catch (Exception e) {e.printStackTrace();}return null;}
}
import org.redisson.client.codec.Codec;
import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;@Component
@ConfigurationPropertiesBinding
public class CodecConverter implements Converter {@Overridepublic Codec convert(String source) {try {if (StringUtils.hasLength(source)) {return (Codec) Class.forName(source.trim()).newInstance();}} catch (Exception e) {e.printStackTrace();}return null;}
}
通过以上转换器,SpringBoot就能自动根据配置中的字符串,正常创建实例,并赋值给对应属性。
参考文档
https://docs.spring.io/spring-framework/docs/5.3.25/reference/html/core.html#core-convert
上一篇:最新或2023(历届)5年级上册英语手抄报图片_小学生英语手抄报版面设计资料 小学生英语手抄报图片四年级上册 英语手抄报关于食物的手抄报
下一篇:最新或2023(历届)关于英语的手抄报图片_英语的手抄报版面设计 三年级手抄报一等奖英语手抄报 英语手抄报a4纸简单红色经典图文