动态管理配置文件扩展接口EnvironmentPostProcessor
SpringBoot支持動態的讀取文件,留下的擴展接口org.springframework.boot.env.EnvironmentPostProcessor。這個接口是spring包下的,使用這個進行配置文件的集中管理,而不需要每個項目都去配置配置文件。這種方法也是springboot框架留下的一個擴展(可以自己去擴展)
demo
在/Users/naeshihiroshi/study/studySummarize/SpringBoot/(自己測試也可以隨機在一個目錄下建立一文件),目錄下建立一個名為springboot.properties文件,
springboot.properties中定義一些配置,配置如下:
jdbc.root.user=zhihao.miao jdbc.root.password=242312321定義MyEnvironmentPostProcessor實現EnvironmentPostProcessor接口
@Component public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {@Overridepublic void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {try{InputStream inputStream = new FileInputStream("/Users/naeshihiroshi/study/studySummarize/SpringBoot/springboot.properties");Properties properties = new Properties();properties.load(inputStream);PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource("my",properties);environment.getPropertySources().addLast(propertiesPropertySource);}catch (IOException e){e.printStackTrace();}} }在classpath定義一個META-INF文件夾然后在其下面先建spring.factories文件,在其中指定:
?
org.springframework.boot.env.EnvironmentPostProcessor=com.zhihao.miao.processor.MyEnvironmentPostProcessor‘啟動類測試:
@SpringBootApplication public class Application {public static void main(String[] args) {ConfigurableApplicationContext context = SpringApplication.run(Application.class,args);String username = context.getEnvironment().getProperty("jdbc.root.user");String password = context.getEnvironment().getProperty("jdbc.root.password");System.out.println("username==="+username);System.out.println("password==="+password);context.close();} }打印結果:
username===zhihao.miao password===242312321EnvironmentPostProcessor接口官網說明
官方文檔如下
Allows for customization of the application's {@link Environment} prior to the application context being refreshed.
允許定制應用的上下文的應用環境優于應用的上下文之前被刷新。(意思就是在spring上下文構建之前可以設置一些系統配置)
EnvironmentPostProcessor implementations have to be registered in
META-INF/spring.factories, using the fully qualified name of this class as the key.
EnvironmentPostProcessor的實現類必須要在META-INF/spring.factories文件中去注冊,并且注冊的是全類名。
EnvironmentPostProcessor processors are encouraged to detect whether Spring's
org.springframework.core.Ordered Ordered interface has been implemented or if the @org.springframework.core.annotation.Order Order annotation is present and to sort instances accordingly if so prior to invocation.
鼓勵EnvironmentPostProcessor處理器檢測Org.springframework.core.Ordered注解,這樣相應的實例也會按照@Order注解的順序去被調用。
?
作者:二月_春風
鏈接:https://www.jianshu.com/p/be6c818fe6ff
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
?
總結
以上是生活随笔為你收集整理的动态管理配置文件扩展接口EnvironmentPostProcessor的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大家好,我是区块链本人。今天,我要给你们
- 下一篇: 搭建consul 集群