在spring boot项目中读取apollo配置常用的方式一般有以下几种:
方法一
在业务类中增加私有成员变量,并在变量上增加注解@Value,这个注解由spring框架提供,这种配置方式默认开启热更新,可以通过在配置文件中配置apollo.autoUpdateInjectedSpringProperties调整是否支持热更新。
public class BusinessDemo {
@Value("${demo.property}")
private String demoProperty;
public void handleBusiness() {
System.out.println(demoProperty);
}
}
方法二
在业务类中增加私有成员变量,并在变量上增加注解@ApolloJsonValue,这个注解由Apollo客户端提供,可以将配置的json字符串转为对象,这种配置方式默认开启热更新。
@RestController
public class TestController {
private final static Gson GSON = new Gson();
@ApolloJsonValue("${demo.json}")
private User user;
@GetMapping("handle")
public String handleBusiness() {
return GSON.toJson(user);
}
}
方法三
在配置类上使用注解@ConfigurationProperties,这个注解由SpringBoot提供。这种配置方式默认不支持热更新。如果需要支持热更新,那么需要配合使用@ApolloConfigChangeListener注解监听配置变更,然后再更新配置对象的属性,这个注解由Apollo提供。
@Component
@ConfigurationProperties("demo")
@Data
public class BusinessConfig {
private String propertyA;
private String propertyB;
}
@RestController
@RequiredArgsConstructor
public class TestController {
private final static Gson GSON = new Gson();
private final BusinessConfig businessConfig;
@GetMapping("handle")
public String handleBusiness() {
return GSON.toJson(businessConfig);
}
}
@Component
@RequiredArgsConstructor
@Slf4j
public class SpringBootApolloRefreshConfig {
private final SampleRedisConfig sampleRedisConfig;
private final RefreshScope refreshScope;
@ApolloConfigChangeListener
public void onChange(ConfigChangeEvent changeEvent) {
//更新配置对象的属性值,可以通过spring cloud的refreshScope.refresh方法更新属性
refreshScope.refresh("businessConfig");
}
}
方法四
使用@ApolloConfig注解注入Config,然后通过Config的API获取配置,这个注解由Apollo提供,这种方式默认支持热更新。
@RestController
public class TestController {
@ApolloConfig
private Config config;
@GetMapping("handle")
public String handleBusiness() {
String value = config.getProperty("test.string.data", "123");
return value;
}
}
其它
Apollo还有个注解@EnableApolloConfig,这个注解需要配合@Configuration一起使用。不过不是用于业务层获取配置值的,而是用于开启Apollo并注入namespace(默认application)的配置到Spring环境中。
@Configuration
@EnableApolloConfig
public class BusinessConfig {}
springboot项目建议使用另一种方式配置,即在配置文件中增加apollo.bootstrap.enabled = true,能使配置在更早的阶段注入。