我知道spring属性源的默认顺序:http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html 如何添加具有特定优先级的属性源?
@PropertySource
是不够的,因为它添加了具有极低优先级的新属性
答案 0 :(得分:0)
有很多方法可以做到这一点; I'll just quote the official documentation:
SpringApplication
具有ApplicationListener
和ApplicationContextInitializer
s,用于将自定义应用于上下文或环境。 Spring Boot加载了许多此类自定义项,以便在META-INF/spring.factories
内部使用。注册其他方法的方法不止一种:
- 在运行之前,通过调用
addListeners
上的addInitializers
和SpringApplication
方法,以编程方式为每个应用程序。- 通过设置
来声明每个应用程序context.initializer.classes
或context.listener.classes
- 通过添加
META-INF/spring.factories
并打包应用程序全部用作库的jar文件,为所有应用程序声明。
SpringApplication
向侦听器发送一些特殊的ApplicationEvents
(甚至在创建上下文之前的一些侦听器),然后为ApplicationContext发布的事件注册侦听器。有关完整列表,请参阅“Spring Boot功能”部分中的Section 23.4, “Application events and listeners”。也可以在使用
中注册Environment
刷新应用程序上下文之前自定义EnvironmentPostProcessor
。每个实施都应在META-INF/spring.factories
:org.springframework.boot.env.EnvironmentPostProcessor=com.example.YourEnvironmentPostProcessor
我的方法总是添加一个ApplicationEnvironmentPreparedEvent侦听器:
public class IntegrationTestBootstrapApplicationListener implements
ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {
public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 4;
public static final String PROPERTY_SOURCE_NAME = "integrationTestProps";
private int order = DEFAULT_ORDER;
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return this.order;
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment environment = event.getEnvironment();
if (!environment.getPropertySources().contains(PROPERTY_SOURCE_NAME)) {
Map<String, Object> properties = ...; // generate the values
// use whatever precedence you want - first, last, before, after
environment.getPropertySources().addLast(
new MapPropertySource(PROPERTY_SOURCE_NAME, properties));
}
}
}
但您可以轻松使用初始化程序:
public class IntegrationTestBootstrapApplicationListener implements
ApplicationContextInitializer<ConfigurableApplicationContext> {
private static final String PROPERTY_SOURCE_NAME = "integrationTestProps";
@Override
public void initialize(final ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
Map<String, Object> properties = ...; // generate the values
// use whatever precedence you want - first, last, before, after
environment.getPropertySources().addLast(
new MapPropertySource(PROPERTY_SOURCE_NAME, properties));
}
}