1.pom
<dependency> <groupId>com.ctrip.framework.apollo</groupId> <artifactId>apollo-client</artifactId> <version>1.7.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.6.6</version> </dependency>
2.配置文件
META-INF/app.properties
app.id=SampleApp
3.代码
package com.vince.xq; import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.ConfigChangeListener; import com.ctrip.framework.apollo.ConfigService; import com.ctrip.framework.apollo.model.ConfigChange; import com.ctrip.framework.apollo.model.ConfigChangeEvent; public class MavenTest { private static String value = null; public static void init() { System.setProperty("apollo.meta", "http://localhost:8080"); Config config = ConfigService.getAppConfig(); //config instance is singleton for each namespace and is never null String someKey = "timeout"; String someDefaultValue = "someDefaultValueForTheKey"; value = config.getProperty(someKey, someDefaultValue); config.addChangeListener(new ConfigChangeListener() { @Override public void onChange(ConfigChangeEvent changeEvent) { System.out.println("Changes for namespace " + changeEvent.getNamespace()); for (String key : changeEvent.changedKeys()) { ConfigChange change = changeEvent.getChange(key); if (key.equals(someKey)) { value = change.getNewValue(); System.out.println(String.format("Found change - key: %s, oldValue: %s, newValue: %s, changeType: %s", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType())); } } } }); } public static void main(String[] args) throws InterruptedException { init(); while (true) { Thread.sleep(1000); System.out.println(value); } } }
4.打印结果