版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36255237/article/details/88842252
使用场景: Spring boot在启动时, 配置文件里的属性值需要根据指定配置文件的属性值进行修改。
1.获取指定配置文件的属性KEY和值。(Map )
2.获取Spring boot 配置文件(Properties)
prop.load(new InputStreamReader(new ClassPathResource("application2.properties").getInputStream(), "utf-8"));
注意: 一定不要用默认配置文件的名字。
因为Spring boot如果遇见了application.properties,就会默认使用这个配置文件。
3.prop.setProperty("spring.datasource.url", Map.get(key)); //修改对应的值。
4.SpringApplication context = new SpringApplication(DemoApplication.class); Properties properties = getProperties(propertiesMap); // 第二步获取的Properties context.setDefaultProperties(properties); // 设置默认配置属性 context.run(args);
// 如果配置文件还是用的application.properties, 设置默认配置属性启动后会失效,因为Spring boot会默认使用application.properties