微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Springboot动态替换Properties配置变量

SpringBoot动态替换Properties配置变量 https://www.jianshu.com/p/70ee32b0b1eb

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;
            }
            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);

    }

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐