我想application.yaml在加載時更改值。
例如)application.yaml
user.name: ${name}
在這里,當使用名稱值執行 jar 時,我想通過呼叫外部 API(例如 vault)而不是程式引數來放置此值。
首先,我認為我需要撰寫實作EnvironmentPostProcessor和呼叫外部 API 的代碼,但我不知道如何注入該值。我能得到幫助嗎?
public class EnvironmentConfig implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
// API CAll
// how can inject yaml value??
}
}
我不知道該以哪種方式定位自己。
uj5u.com熱心網友回復:
選項 1:通過 EnvironmentPostProcessor 執行此操作:
假設您已經在/resources/META-INF/spring.factories檔案中注冊了 EnvironmentPostProcessor:
org.springframework.boot.env.EnvironmentPostProcessor=package.to.environment.config.EnvironmentConfig
您只需要添加您的自定義 PropertySource:
public class EnvironmentConfig implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
environment.getPropertySources()
.addFirst(new CustomPropertySource("customPropertySource"));
}
}
public class CustomPropertySource extends PropertySource<String> {
public CustomPropertySource(String name) {
super(name);
}
@Override
public Object getProperty(String name) {
if (name.equals("name")) {
return "MY CUSTOM RUNTIME VALUE";
}
return null;
}
}
選項 2:通過 PropertySourcesPlaceholderConfigurer 進行:
負責決議這些占位符的類是一個名為 BeanPostProcessor 的類PropertySourcesPlaceholderConfigurer(參見此處)。
所以你可以重寫它并為你提供自定義PropertySource來解決你需要的屬性,如下所示:
@Component
public class CustomConfigurer extends PropertySourcesPlaceholderConfigurer {
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, ConfigurablePropertyResolver propertyResolver) throws BeansException {
((ConfigurableEnvironment) beanFactoryToProcess.getBean("environment"))
.getPropertySources()
.addFirst(new CustomPropertySource("customPropertySource"));
super.processProperties(beanFactoryToProcess, propertyResolver);
}
}
uj5u.com熱心網友回復:
用于ConfigurationProperties您的屬性并通過這樣的 api 更改它:
@Component
@ConfigurationProperties(prefix = "user")
public class AppProperties {
private String name;
//getter and setter
}
@RestController
public class AppPropertiesController {
@Autowire
AppProperties prop;
@PostMapping("/changeProp/{name}")
public void change(@PathVariable String name){
prop.setName(name);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/536398.html
標籤:春天弹簧靴金库
上一篇:完成后如何殺死Java執行緒?
下一篇:Spring自定義配置注解
