SpringBoot加载自定义yml文件
2024-10-23 14:09:58 1161
官方推荐使用yml,却不支持自定义的yml,匪夷所思。
package com.xxx.xxx.xxx;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* OpenApiConfig
*
* @author xxx
* @date 2020/08/14 15:15
*/
@Data
@Component
@ConfigurationProperties(prefix = "config")
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:xxx.yml")
public class OpenApiConfig {
private String x;
private Integer xx;
private List<ApplicationConfig> xxx = new ArrayList<>();
@Data
public static class ApplicationConfig {
private String yyy;
private String yyyy;
}
}
package xxx.xxx.xxx.xxx;
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 java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/**
* YamlPropertySourceFactory
*
* @author xxx
* @date 2020/08/14 17:45
*/
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(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) {
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException) {
throw (FileNotFoundException)e.getCause();
}
throw e;
}
}
}