SpringBoot:自定义类型的属性如何从配置文件中正确加载

19 篇文章 0 订阅
9 篇文章 0 订阅

      使用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<String, URL> {

    @Override
    public 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<String, Codec> {

    @Override
    public 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值