Springboot动态替换Properties配置变量

SpringBoot动态替换Properties配置变量

package tk.mybatis.springboot.conf;

import cn.hutool.core.io.FileUtil;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.origin.OriginTrackedValue;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LocalEnvironmentPrepareEventListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        MutablePropertySources propertySources = event.getEnvironment().getPropertySources();
        Map<String,String> pp=new HashMap<>();
        List<String> strings1 = FileUtil.readLines("d:/conf.properties", StandardCharsets.UTF_8);
        for (String s : strings1) {
            String[] split = s.split("=");
            String put = pp.put(split[0], split[1]);
        }

        for (PropertySource<?> propertySource : propertySources) {
            boolean applicationConfig = propertySource.getName().contains("application.properties");
            if (!applicationConfig) {
                continue;
            }
// 注意这里 springboot 2.3修改了不能是application.properties了,要放在不是unmodifiedMap的数据里面 Map
<String, OriginTrackedValue> source = (Map<String, OriginTrackedValue>) propertySource.getSource(); source.put("test.file", OriginTrackedValue.of("/usr/d")); } } }

application

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.addListeners(new LocalEnvironmentPrepareEventListener());
        app.run(args);

    }

 

posted @ 2022-04-27 19:21  _Phoenix  阅读(1205)  评论(0编辑  收藏  举报