SpringBoot自定义启动前的Environment或ApplicationContext

讨论 0 306
vom09
vom09 LV1 2021年5月18日 22:46 发表
点击群号免费加入社区交流群:367346704
<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&lt;?&gt; propertySource = loadYaml(path);<br> environment.getPropertySources().addLast(propertySource);<br> }<br> <br> private PropertySource&lt;?&gt; 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)  分享
相关标签: SpringBoot
0个回复
  • 消灭零回复