SpringBoot自定义启动前的Environment或ApplicationContext
        
        
          
             
          
          
          
         
        
        <p>SpringBoot自定义启动前的Environment或ApplicationContext:</p><p>每个实现注册在META-INF/spring.factories:</p><pre><code>org.springframework.boot.env.EnvironmentPostProcessor=com.example.YourEnvironmentPostProcessor</code></pre><p>实现代码:</p><pre><code>public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor {<br> <br>    private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();<br> <br>    @Override<br>    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {<br>        Resource path = new ClassPathResource("com/example/myapp/config.yml");<br>        PropertySource<?> propertySource = loadYaml(path);<br>        environment.getPropertySources().addLast(propertySource);<br>    }<br> <br>    private PropertySource<?> loadYaml(Resource path) {<br>        if (!path.exists()) {<br>            throw new IllegalArgumentException("Resource " + path + " does not exist");<br>        }<br>        try {<br>            return this.loader.load("custom-resource", path).get(0);<br>        }<br>        catch (IOException ex) {<br>            throw new IllegalStateException("Failed to load yaml configuration from " + path, ex);<br>        }<br>    }<br> <br>}</code></pre><p><br></p>
        
          收藏(0)
           分享
        
        
          相关标签: