SpringBoot:自定义类型的属性如何从配置文件中正确加载
创始人
2025-05-30 09:06:03

      使用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(历届)威海机关... 按照政策规定为进一步完善威海生育保险制度切实保障全市机关事业单位工作人员的合法权益威海决定自1月1日...
最新或2023(历届)带薪休假... 关于进一步落实机关事业单位工作人员带薪休假制度的通知各乡、镇人民政府界湖街道办事处沂南经济开发区管委...
最新或2023(历届)解读职工... 【朽导语】职工带薪休假条例是为了维护职工休息休假权利调动职工工作积极性根据劳动法和公务员法制定的条例...
最新或2023(历届)青海省取... 青海省 取暖费补助 平均每人上调1000元 有网友向大青海网发来爆料称, 取暖费补助 平均每人上调...
最新或2023(历届)最新或2... 【编者导语】中共中央总书记、国家主席、中央军委主席习近平3日在纪念中国人民抗日战争暨世界反法西斯战争...