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 @   _Phoenix  阅读(1235)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
历史上的今天:
2021-04-27 expect脚本
2020-04-27 剑指Offer_编程题_从上往下打印二叉树
2020-04-27 剑指Offer_编程题_包含min函数的栈
点击右上角即可分享
微信分享提示