本地環境時覆蓋Apollo配置


如果在本地環境,需要進行某些配置的更改,但是只是為了本地開發方便,例如服務端口的更改,Eureka注冊地址的更改,那么可以使用該組件進行配置覆蓋。
分步指南
  1. 實現原理
  2. 代碼實現
  3. 適用場景
 
一、實現原理
 
 
二、代碼實現
LocalApplicationRecoverConfiguration:
 
@Configuration
@Slf4j
@ConditionalOnProperty(value = "spring.profiles.active",havingValue = "local")
public class LocalApplicationRecoverConfiguration{
 
@Bean
public PropertySourcesProcessor configPropertySourcesProcessor() {
log.info("use local configPropertySourcesProcessor");
return new LocalConfigPropertySourcesProcessor();
}
 
}
 
LocalConfigPropertySourcesProcessor:
 

@Slf4j
public class LocalConfigPropertySourcesProcessor extends PropertySourcesProcessor implements BeanDefinitionRegistryPostProcessor {

private static final String LOCAL_ACTIVE = "local";

private static final String[] LOCAL_APPLICATIONS = new String[]{"applicationConfig: [classpath:/application.yml]","applicationConfig: [classpath:/application-local.yml]","applicationConfig: [classpath:/application-local.yaml]","applicationConfig: [classpath:/application-local.properties]"};

private int order = Integer.MAX_VALUE;

private ConfigurableEnvironment environment;

@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {

}

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
String[] activeProfiles = environment.getActiveProfiles();
if(activeProfiles != null){
for (String activeProfile : activeProfiles) {
if(LOCAL_ACTIVE.equals(activeProfile)){
MutablePropertySources propertySources = environment.getPropertySources();
for (String localApplication : LOCAL_APPLICATIONS) {
PropertySource<?> propertySource = propertySources.get(localApplication);
if(propertySource != null){
propertySources.remove(localApplication);
propertySources.addFirst(propertySource);
}
}
}
}
}
}

@Override
public void setEnvironment(Environment environment) {
this.environment = (ConfigurableEnvironment)environment;
}

@Override
public int getOrder() {
return order;
}
}
 
 
三、適用場景
本地需要更改某些配置,但是不能直接更改Apollo,例如端口號的更改,注冊中心地址的更改,數據庫配置信息的更改等。簡而言之就是,配置更改只對自己可見,不能影響其它開發人員。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM