gpt4 book ai didi

spring - 在 Spring 中添加新属性源的最佳方法是什么?

转载 作者:行者123 更新时间:2023-12-01 15:27:32 26 4
gpt4 key购买 nike

我想添加一个新的属性源,可用于读取应用程序中的属性值。我想使用 Spring 来做到这一点。我在@Configuration 类中有一段这样的代码:

@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
MutablePropertySources sources = new MutablePropertySources();
MyCustomPropertySource propertySource = new MyCustomPropertySource("my custom property source");
sources.addFirst(propertySource);
properties.setPropertySources(sources);
return properties;
}

这似乎工作得很好。但是,它也在做的是覆盖我不想覆盖的其他属性值(例如,spring boot 使用的 application.properties 文件中的 server.port 属性)。因此,基本问题是添加此属性源但不使其覆盖其他属性的最佳方法是什么。有什么方法可以获取现有的属性源并简单地添加它?

最佳答案

我通过向 Spring Boot 应用程序添加自定义初始化程序来实现此目的:

@SpringBootApplication
public class MyApp {

public static void main(String[] args) {
new SpringApplicationBuilder(MyApp.class)
.initializers(new MyContextInitializer()) // <---- here
.run(args);
}

}
哪里 MyContextInitializer包含: -
public class MyContextInitializer implements
ApplicationContextInitializer<ConfigurableApplicationContext> {

public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
ConfigurableEnvironment environment = configurableApplicationContext.getEnvironment();

// Create map for properites and add first (important)
Map<String, Object> myProperties = new HashMap<>();
myProperties.put("some-prop", "custom-value");
environment.getPropertySources().addFirst(
new MapPropertySource("my-props", myProperties));
}

}
请注意,如果您的 application.yaml包含: -
some-prop: some-value
another-prop: this is ${some-prop} property
然后是 initialize方法将更新 some-propcustom-value当应用程序加载时,它将在运行时具有以下值:
some-prop: custom-value
another-prop: this is custom-value property
注意,如果 initialize方法做了一个简单的 System.setProperty调用即
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
ConfigurableEnvironment environment = configurableApplicationContext.getEnvironment();
System.setProperty("some-prop", "custom-value");
}
... 然后是 another-prop将等于 this is some-value property这不是我们通常想要的(并且我们失去了 Spring 配置属性解析的能力)。

关于spring - 在 Spring 中添加新属性源的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33714491/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com