使用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