SpringBoot自定義啓動前的Environment或ApplicationContext | MSCode微服務平臺框架代碼源碼

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工作流和阿里巴巴組件,提供所有源碼和詳盡文檔的企業級快速開發平臺。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章