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; }