如果在本地环境,需要进行某些配置的更改,但是只是为了本地开发方便,例如服务端口的更改,Eureka注册地址的更改,那么可以使用该组件进行配置覆盖。
分步指南
- 实现原理
- 代码实现
- 适用场景
一、实现原理
二、代码实现
LocalApplicationContextInitializer:
public class LocalApplicationContextInitializer implements
org.springframework.context.ApplicationContextInitializer<ConfigurableApplicationContext>, EnvironmentPostProcessor, Ordered {
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;
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
}
/**
* 将本地local配置优先级设置为最高
* @param context
*/
@Override
public void initialize(ConfigurableApplicationContext context) {
ConfigurableEnvironment environment = context.getEnvironment();
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 int getOrder() {
return order;
}
}
|
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 {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
}
@Override
public void setEnvironment(Environment environment) {
}
@Override
public int getOrder() {
return 0;
}
}
|
三、适用场景
本地需要更改某些配置,但是不能直接更改Apollo,例如端口号的更改,注册中心地址的更改,数据库配置信息的更改等。简而言之就是,配置更改只对自己可见,不能影响其它开发人员。