前提
添加maven依赖
<!-- apollo -->
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>0.11.0-panther</version>
</dependency>
方式一 config配置类
1 添加配置类
@Data
@Configuration
@EnableApolloConfig("druid") // 命名空间
public class DruidConfig {
@Value("${druid.size:10000}") // key
private Integer userSize;
}
注意: 官网里提示了:
@EnableApolloConfig
要和@Configuration
一起使用,不然不会生效。
2. 使用
public class xxx{
@Autowired //不可少,少了没法通过aop获取apollo的配置
DruidConfig druidConfig;
public Integer getSize() {
// 方式1,要写个配置类
Integer num1 = druidConfig.getSize();
return num1;
}
}
每次都会新构建一个DruidConfig对象,去读取apollo的配置
方式二 spring boot 集成方式(推荐)
public class xxx{
@ApolloConfig("druid") //namespace
private Config druidConfig2;
public Integer getSize() {
// 方式2 先指定了namespace,再指定key
Integer num2 = druidConfig2.getIntProperty("druid.size", 200000);
return num2;
}
}
@ApolloConfig("nameSpace") 一个注解搞定
每次都会新构建一个对象,去读取apollo的配置