首先定义一个YamlPropertySourceFactory,参考https://mdeinum.github.io/2018-07-04-PropertySource-with-yaml-files/
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.lang.Nullable;
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
// for ignoreResourceNotFound
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException)
throw (FileNotFoundException) e.getCause();
throw e;
}
}
}
然后定义配置类,如下(PropertySource默认支持properties文件,若加载properties文件则不需要定义YamlPropertySourceFactory)
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:config/xxx.yml")
@Data
public class XxxConfig {
/**
* xxx.yml放在resources/config目录下
* fieldName是yml文件中的key值
*/
@Value("${fieldName}")
private String fieldName;
}
yml文件中key值的冒号后面要留一个空格,包含特殊字符的value值要用单引号括起来。例
fieldName: '[xxx]'