package com.liuchao; import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplicationRunListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.Ordered; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.env.PropertySource; import java.io.IOException; import java.util.Properties; public class MySpringApplicationRunListener implements SpringApplicationRunListener, Ordered { private SpringApplication application; private String[] args; @Override public void starting() { System.out.println(">>>>starting<<<<"); } public MySpringApplicationRunListener(SpringApplication application, String[] args) { this.application = application; this.args = args; } @Override public void environmentPrepared(ConfigurableEnvironment environment) { // 配置文件讀取到程序中 思路需要自己將本地文件讀取到程序中,讓后在放入到SpringBoot容器 Properties properties = new Properties(); try { // 1. 讀取我們的my.properties文件 properties.load(this.getClass().getClassLoader(). getResourceAsStream("my.properties")); // 2. 讀取名稱名稱為my PropertySource propertySource = new PropertiesPropertySource("my", properties); //3. 將資源添加到SprigBoot項目中 MutablePropertySources propertySources = environment.getPropertySources(); // 4.通過該api接口可以將配置文件讀取 到SpringBoot項目中 propertySources.addLast(propertySource); } catch (IOException e) { e.printStackTrace(); } } @Override public void contextPrepared(ConfigurableApplicationContext context) { } @Override public void contextLoaded(ConfigurableApplicationContext context) { } @Override public void started(ConfigurableApplicationContext context) { } @Override public void running(ConfigurableApplicationContext context) { } @Override public void failed(ConfigurableApplicationContext context, Throwable exception) { } @Override public int getOrder() { return -1; } }
在resource 目錄下面建 META-INF/spring.factories
文件內容為
#org.springframework.boot.SpringApplicationRunListener=\ 這個值是定死的值
#com.liuchao.MySpringApplicationRunListener 這個是自己定義的監聽類
