upd: 动态变更环境变量测试

This commit is contained in:
骑着蜗牛追导弹 2024-12-06 21:11:01 +08:00
parent fd1e337334
commit 1bbca46b72
1 changed files with 33 additions and 9 deletions

View File

@ -1,19 +1,43 @@
package cn.odboy.rest;
import lombok.RequiredArgsConstructor;
import java.util.HashMap;
import java.util.Map;
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.MapPropertySource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 全局更新配置测试
*
* @author odboy
* @date 2024-12-06
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/demo")
@RequestMapping("/updateConfig")
public class DemoController {
@Value("${kenaito.config-center.demo:123}")
private String demoStr;
@PostMapping("/test")
@Autowired private ConfigurableEnvironment environment;
/** 配置变化了 */
@GetMapping("/test")
public ResponseEntity<Object> test() {
String key = "kenaito.config-center.demo";
String property = environment.getProperty(key);
System.err.println("property=" + property);
Map<String, Object> properties = new HashMap<>();
properties.put(key, "Hello World!");
MapPropertySource propertySource = new MapPropertySource("dynamicProperties", properties);
// 将新的属性源添加到 ConfigurableEnvironment
environment.getPropertySources().addFirst(propertySource);
String property1 = environment.getProperty(key);
System.err.println("property1=" + property1);
return ResponseEntity.ok("success");
}
}