Spring cloud config can centrally manage configuration files, and different (spring-boot) applications can be used like a simple configuration; but it takes a lot of trouble for ordinary spring web applications to use config client;
Reference: https://github.com/spring-cloud/spring-cloud-config/issues/299
Highlights:
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).
We are a spring web application, and the following methods are only valid for web apps;
1. maven subscription 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. Configure web.xml to let the spring context loader use the customized context;
<context-param>
<param-name>contextClass</param-name>
<param-value>com.me.MyConfigurableWebApplicationContext</param-value>
</context-param>
3. Implement MyConfigurableWebApplicationContext, the main function is to use a custom environment;
public class MyConfigurableWebApplicationContext extends XmlWebApplicationContext {
@Override
protected ConfigurableEnvironment createEnvironment() {
return new CloudEnvironment();
}
}
4. Implementing the 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. Test, configure cloud.config=true on the server side, if it works, then you should be able to get true here;
@Value("${cloud.config: false}")
public void setCloudConfig(boolean cloudConfig) {
this.cloudConfig = cloudConfig;
}