springboot 在1.5版本以后,@ConfigurationProperties去除location参数,因此无法直接导出yml配置文件,
而properties配置文件可以通过@PropertySource或者@ImportResource 来直接导入,因此整理两种导入自定义yml文件
1、使用YamlPropertiesFactoryBean来加载并设置到PropertySourcesPlaceholderConfigurer中
代码:
@Bean
public PropertySourcesPlaceholderConfigurer yaml() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ClassPathResource("myconfig.yml"));
configurer.setProperties(yaml.getObject());
return configurer;
}
2、使用@PropertySource,自定义factory
代码:
import java.io.IOException;
import org.springframework.boot.env.PropertySourcesLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
return name != null ? new PropertySourcesLoader().load(resource.getResource(), name, null) : new PropertySourcesLoader().load(
resource.getResource(), getNameForResource(resource.getResource()), null);
}
private static String getNameForResource(Resource resource) {
String name = resource.getDescription();
if (!org.springframework.util.StringUtils.hasText(name)) {
name = resource.getClass().getSimpleName() + "@" + System.identityHashCode(resource);
}
return name;
}
}