1、SpringBoot对配置文件集中化进行管理,方便进行管理,也可以使用HttpClient进行对远程的配置文件进行获取。
创建一个类实现EnvironmentPostProcessor 接口,然后可以对配置文件获取或者添加等等操作。
1 package com.bie.springboot;
2
3 import java.io.FileInputStream;
4 import java.io.InputStream;
5 import java.util.Properties;
6
7 import org.springframework.boot.SpringApplication;
8 import org.springframework.boot.env.EnvironmentPostProcessor;
9 import org.springframework.core.env.ConfigurableEnvironment;
10 import org.springframework.core.env.PropertiesPropertySource;
11 import org.springframework.stereotype.Component;
12
13 /**
14 *
15 * @Description TODO
16 * @author biehl
17 * @Date 2018年12月30日 下午3:43:55 1、动态获取到配置文件信息
18 */
19 @Component
20 public class DynamicEnvironmentPostProcessor implements EnvironmentPostProcessor {
21
22 public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
23 try {
24 InputStream is = new FileInputStream("E:\\springboot.properties");
25 Properties properties = new Properties();
26 properties.load(is);
27 PropertiesPropertySource propertySource = new PropertiesPropertySource("dynamic", properties);
28 environment.getPropertySources().addLast(propertySource);
29 } catch (Exception e) {
30 e.printStackTrace();
31 }
32
33
34 }
35
36 }
2、配置文件的名称叫做springboot.properties。然后配置文件的内容如下所示:
1 springboot.name=SpringBoot
需要注意的是,需要创建一个META-INF的文件夹,然后spring.factories文件里面的内容如下所示:
spring.factories是EnvironmentPostProcessor接口的详细路径=自己的实现类的详细路径:
org.springframework.boot.env.EnvironmentPostProcessor=com.bie.springboot.DynamicEnvironmentPostProcessor
3、然后可以使用主类获取到动态配置文件里面的配置信息:
1 package com.bie;
2
3 import org.springframework.beans.BeansException;
4 import org.springframework.boot.SpringApplication;
5 import org.springframework.boot.autoconfigure.SpringBootApplication;
6 import org.springframework.context.ConfigurableApplicationContext;
7
8 import com.bie.springboot.DataSourceProperties;
9 import com.bie.springboot.DynamicEnvironmentPostProcessor;
10 import com.bie.springboot.JdbcConfig;
11 import com.bie.springboot.TomcatProperties;
12 import com.bie.springboot.UserConfig;
13
14 /**
15 *
16 * @Description TODO
17 * @author biehl
18 * @Date 2018年12月30日 上午10:44:35
19 *
20 */
21 @SpringBootApplication
22 public class Application {
23
24 public static void main(String[] args) {
25 ConfigurableApplicationContext run = SpringApplication.run(Application.class, args);
26 try {
27 System.out.println("SpringBoot name is " + run.getEnvironment().getProperty("springboot.name"));
28 } catch (Exception e) {
29 e.printStackTrace();
30 }
31
32 System.out.println("===================================================");
33
34 // 运行结束进行关闭操作
35 run.close();
36 }
37
38 }
运行效果如下所示:
待续......