AdSense

網頁

2019/12/19

Spring Boot 動態修改properties的內容 update Environment properties

Spring Boot 動態修改properties的內容。


如果要在Spring程式中動態修改Environment中properties的內容,可透過ConfigurableEnvironment來新增或修改Environment中原本的properties內容。

例如下面是message.properties檔。

message.properties

demo.system.name=demo

在SpringBootApplication類別設定@PropertySourcemessage.properties配置檔的屬性注入。

DemoApplication

package com.abc.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;

@SpringBootApplication
@PropertySource(value = {"classpath:message.properties"}) // <--
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

下面建立一個DemoController來測試利用ConfigurableEnvironment動態修改properties的效果。

DemoController

 package com.abc.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.Map;

@RestController
public class DemoController {

    @Autowired
    private ConfigurableEnvironment configEnv;

    @Autowired
    private Environment env;

    @GetMapping("/system/name")
    public String getSystemName() {
        String oldSystemName = env.getProperty("demo.system.name");
        System.out.println(oldSystemName);
        return oldSystemName;
    }

    @GetMapping("/system/name/update/{systemName}")
    public String updateSystemName(@PathVariable String systemName) {

        MutablePropertySources propertySources = configEnv.getPropertySources();
        Map<String, Object> map = Collections.singletonMap("demo.system.name", systemName);
        propertySources.addFirst(new MapPropertySource("new", map));

        String newSystemName = env.getProperty("demo.system.name");
        System.out.println(newSystemName);
        return newSystemName;

    }

}

啟動系統進行下面測試。本範例程式的本機路徑為http://localhost:8080/demo

在瀏覽器網址列輸入http://localhost:8080/demo/system/name會呼叫DemoController.getSystemName()並印出message.propertiesdemo.system.name=demo內容如下。

demo

接著再瀏覽器網址列輸入http://localhost:8080/demo/system/name/update/sample會呼叫DemoController.updateSystemName()更新(覆蓋)原有的demo.system.name=demo並印出以下。

sample

參考:

沒有留言:

AdSense