我想在加载时更改application.yaml
的值。
) application.yaml交货
user.name: ${name}
在这里,我想通过调用外部API(如vault)来放置这个值,而不是在使用name value执行jar时使用程序参数。
首先,我认为我需要编写实现EnvironmentPostProcessor
和调用外部API的代码,但我不知道如何注入该值。能帮我一下吗?
public class EnvironmentConfig implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
// API CAll
// how can inject yaml value??
}
}
我不知道该走哪条路。
选项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:
负责解析这些持卡人的类是一个名为PropertySourcesPlaceholderConfigurer
的BeanPostProcessor(见这里)。
所以你可以覆盖它,并提供自定义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);
}
}
使用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);
}
}