如果在本地环境,需要进行某些配置的更改,但是只是为了本地开发方便,例如服务端口的更改,Eureka注册地址的更改,那么可以使用该组件进行配置覆盖。
分步指南
一、实现原理
二、代码实现
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,例如端口号的更改,注册中心地址的更改,数据库配置信息的更改等。简而言之就是,配置更改只对自己可见,不能影响其它开发人员。