SpringBoot自定义启动前的Environment或ApplicationContext。
MSCode微服务平台框架 mscodecloud.com 代码示例
每个实现注册在META-INF/spring.factories:
org.springframework.boot.env.EnvironmentPostProcessor=com.example.YourEnvironmentPostProcessor
实现代码:
public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor {
private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
Resource path = new ClassPathResource("com/example/myapp/config.yml");
PropertySource<?> propertySource = loadYaml(path);
environment.getPropertySources().addLast(propertySource);
}
private PropertySource<?> loadYaml(Resource path) {
if (!path.exists()) {
throw new IllegalArgumentException("Resource " + path + " does not exist");
}
try {
return this.loader.load("custom-resource", path).get(0);
}
catch (IOException ex) {
throw new IllegalStateException("Failed to load yaml configuration from " + path, ex);
}
}
}
MSCode微服务平台框架 mscodecloud.com 是基于Spring Cloud、Spring Boot、Activiti7工作流和阿里巴巴组件,提供所有源码和详尽文档的企业级快速开发平台。