[英]How to override bootstrap.properties OR how to ignore cloud config for local environment in spring boot
[英]Override Spring Cloud Config values with environment
有沒有辦法覆蓋通過Spring Cloud Config Server設置的屬性與另一個屬性源(特別是系統環境)? 我知道我可以通過循環遍歷Environment
對象的PropertySource
手動完成它,但是如果我可以設置它以使bootstrapConfig
源具有最低優先級,那將是理想的。
FWIW,我通過編寫一個自定義的ApplicationListener
來實現這一點, ApplicationListener
的Event在周期的早期觸發,但是在加載Config Service的PropertySource
之后。 我已經在這里附上了代碼,以防有人感興趣。 如果有一個“正式的”Spring方式來做到這一點,我仍然感興趣,但這有效:
package com.example;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ConfigServicePropertyDeprioritizer
implements ApplicationListener<ApplicationPreparedEvent>
{
private static final String CONFIG_SOURCE = "bootstrap";
private static final String PRIORITY_SOURCE = "systemEnvironment";
@Override
public void onApplicationEvent(ApplicationPreparedEvent event)
{
ConfigurableEnvironment environment = event.getApplicationContext()
.getEnvironment();
MutablePropertySources sources = environment.getPropertySources();
PropertySource<?> bootstrap = findSourceToMove(sources);
if (bootstrap != null)
{
sources.addAfter(PRIORITY_SOURCE, bootstrap);
}
}
private PropertySource<?> findSourceToMove(MutablePropertySources sources)
{
boolean foundPrioritySource = false;
for (PropertySource<?> source : sources)
{
if (PRIORITY_SOURCE.equals(source.getName()))
{
foundPrioritySource = true;
continue;
}
if (CONFIG_SOURCE.equals(source.getName()))
{
// during bootstrapping, the "bootstrap" PropertySource
// is a simple MapPropertySource, which we don't want to
// use, as it's eventually removed. The real values will
// be in a CompositePropertySource
if (source instanceof CompositePropertySource)
{
return foundPrioritySource ? null : source;
}
}
}
return null;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.