Apollo通过注解获取配置的几种方式

在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,能使配置在更早的阶段注入。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值