一、加入Apollo 客户端依赖
< dependency>
< groupId> com.ctrip.framework.apollo</ groupId>
< artifactId> apollo-client</ artifactId>
< version> 1.3.0</ version>
</ dependency>
二、添加 @EnableApolloConfig 配置标签
@EnableApolloConfig
@SpringBootApplication
public class DemoApplication {
public static void main ( String [ ] args) {
SpringApplication . run ( DemoApplication . class , args) ;
}
}
三、在application.yml 配置文件中添加Apollo 配置
apollo :
autoUpdateInjectedSpringProperties : true
bootstrap :
eagerLoad :
enabled : true
enabled : true
namespaces : application
cacheDir : ./config
meta : 'http://apollo-host:8180'
app :
id : teams- demo
四、通过 @Value 获取 Apollo 配置属性,根据 Apollo 配置自动更新
package com. example. springbootapollo. demo. web ;
import org. springframework. beans. factory. annotation. Value ;
import org. springframework. web. bind. annotation. GetMapping ;
import org. springframework. web. bind. annotation. RequestMapping ;
import org. springframework. web. bind. annotation. RestController ;
@RequestMapping ( "/public/api" )
@RestController
public class VersionController {
@Value ( "${teams.version}" )
String teamsVersion;
@GetMapping ( "/version" )
public String getVersion ( ) {
return teamsVersion;
}
}
五、结果
[Apollo-Config-1] c.f.a.s.p.AutoUpdateConfigChangeListener : Auto update apollo changed value successfully, new value: 1.1.0, key: teams.version, beanName: versionController, field: com.example.springbootapollo.demo.web.VersionController.teamsVersion