spring cloud config可以集中管理配置文件,不同的(spring-boot)应用程序,通过简单的配置就可以像使用; 但是普通的spring web application要使用config client却要费一番周折;
参考: https://github.com/spring-cloud/spring-cloud-config/issues/299
重点:
Well the "normal" way is to use Spring Cloud Config as part of a Spring Boot app. You really should consider doing that at some point.
If you want to try and cobble it together yourself you need a ConfigServicePropertySourceLocator
and you need to apply it to the Environment
before the application context is started. How you do that will depend a lot on how you are creating the ApplicationContext
(SpringApplication
from Spring Boot would be much easier than whatever you are doing probably).
我们是一个spring web application,下面的方法也只是对web app有效;
1. maven 加入spring cloud config client:
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-config-client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
2. 配置web.xml, 让spring context loader 使用定制过的context;
<context-param>
<param-name>contextClass</param-name>
<param-value>com.me.MyConfigurableWebApplicationContext</param-value>
</context-param>
3. 实现 MyConfigurableWebApplicationContext, 主要的作用是使用自定义的environment;
public class MyConfigurableWebApplicationContext extends XmlWebApplicationContext {
@Override
protected ConfigurableEnvironment createEnvironment() {
return new CloudEnvironment();
}
}
4. 实现CloundEnvironment
public class CloudEnvironment extends StandardServletEnvironment {
@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
super.customizePropertySources(propertySources);
try {
propertySources.addLast(initConfigServicePropertySourceLocator(this));
} catch (Exception ex) {
logger.warn("failed to initialize cloud config environment", ex);
}
}
private PropertySource<?> initConfigServicePropertySourceLocator(Environment environment) {
ConfigClientProperties configClientProperties = new ConfigClientProperties(environment);
configClientProperties.setUri("http://localhost:8888");
configClientProperties.setName("myapp");
configClientProperties.setLabel("master");
ConfigServicePropertySourceLocator configServicePropertySourceLocator =
new ConfigServicePropertySourceLocator(configClientProperties);
return configServicePropertySourceLocator.locate(environment);
}
}
5. 测试, 在server端配置cloud.config=true, 如果有效,那么这里应该能够得到true;
@Value("${cloud.config: false}")
public void setCloudConfig(boolean cloudConfig) {
this.cloudConfig = cloudConfig;
}