spring cloud config能夠集中管理配置文件,不一樣的(spring-boot)應用程序,經過簡單的配置就能夠像使用; 可是普通的spring web application要使用config client卻要費一番周折;java
參考: https://github.com/spring-cloud/spring-cloud-config/issues/299git
重點:github
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.web
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
咱們是一個spring web application,下面的方法也只是對web app有效;app
1. maven 加入spring cloud config client:maven
<!-- 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;ide
<context-param> <param-name>contextClass</param-name> <param-value>com.me.MyConfigurableWebApplicationContext</param-value> </context-param>
3. 實現 MyConfigurableWebApplicationContext, 主要的做用是使用自定義的environment;spring-boot
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; }