spring boot用spring新的 Enviroment 类来管理属性配置。Super diamond (https://github.com/melin/super-diamond) 默认给的是用 以下配置
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="properties" ref="propertiesConfiguration" />
</bean>
<bean id="propertiesConfiguration" class="com.github.diamond.client.PropertiesConfigurationFactoryBean">
<constructor-arg index="0" value="localhost" />
<constructor-arg index="1" value="5001" />
<constructor-arg index="2" value="test" />
<constructor-arg index="3" value="development" />
</bean>
这样的配置导致superdiamond的配置信息是优先级最低,不能起到集中管理,覆盖打包到jar中的application.properties的目的。如果设置PropertySourcesPlaceHoderConfigurer 的 localOverride = true 的话,那么superdiamond的优先级又太高。总之我希望superdiamond的配置优先级要低于环境变量和jvm properties,但是要高于application properties。那就不要用PropertySourcesPlaceHoderConfigurer了,直接把propertie插入到Enviroment里面就好了。
SpringApplication app = new SpringApplication(Application.class);
app.addInitializers((ApplicationContextInitializer<ConfigurableApplicationContext>) applicationContext -> {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
if (Arrays.stream(environment.getActiveProfiles())
.filter(x -> "superdiamond".equals(x)).findAny().isPresent()) {
try {
loadSuperDiamond(environment);
} catch (Exception e) {
e.printStackTrace();
}
}
});
app.run(args);
}
static void loadSuperDiamond(ConfigurableEnvironment enviroment) throws Exception {
PropertiesConfigurationFactoryBean propertiesConfigurationFactoryBean = new PropertiesConfigurationFactoryBean(
enviroment.getProperty("superdiamond.host"),
Integer.parseInt(enviroment.getProperty("superdiamond.port")),
enviroment.getProperty("superdiamond.proj", "superdiamond.proj"),
enviroment.getProperty("superdiamond.profile", "superdiamond.profile"),
enviroment.getProperty("superdiamond.modules", "superdiamond.modules")
);
Properties properties = propertiesConfigurationFactoryBean.getObject();
enviroment.getPropertySources().addAfter("random", new PropertiesPropertySource("superdiamond", properties));
}