简介
从Spring Boot 1.3开始,我们可以在应用程序上下文刷新之前使用EnvironmentPostProcessor
来自定义应用程序的Environment
。Environment
表示当前应用程序运行的环境,它可以统一访问各种属性源中的属性,如属性文件、JVM系统属性、系统环境变量和Servlet上下文参数。使用EnvironmentPostProcessor
可以在bean初始化之前对Environment
进行修改。
示例
在 custom.properties 中定义一些配置,配置如下:
jdbc.root.user=mysql
jdbc.root.password=123456
1.实现EnvironmentPostProcessor
定义MyEnvironmentPostProcessor实现EnvironmentPostProcessor接口
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor { @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { try{ InputStream inputStream = new FileInputStream("/Users/SpringBoot/custom.properties"); Properties properties = new Properties(); properties.load(inputStream); PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource("my",properties); environment.getPropertySources().addLast(propertiesPropertySource); }catch (IOException e){ e.printStackTrace(); } } }
如果你希望EnvironmentPostProcessor按照特定的顺序被调用,可以实现Ordered接口,或者使用@Order注解。
2.注册实现类
想要在Spring Boot启动过程中调用这个实现类,我们还需要在项目的resources目录中定义一个META-INF文件夹,然后在其下面先建spring.factories文件,在其中指定注册这个实现类:
org.springframework.boot.env.EnvironmentPostProcessor=com.test.springboot.processor.MyEnvironmentPostProcessor
3.测试
@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); } }
EnvironmentPostProcessor接口官网说明
官方文档如下
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注解的顺序去被调用。