springboot 2.4.0配置项改为spring.config.import

101 阅读1分钟

springboot 2.4.0 支持 spring.config.import 的方式引入 nacos 配置, 不再需要 bootstrap 容器

How to use it

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <!-- 排除 bootstrap, 未来版本 spring-cloud-alibaba 应该在 spring boot >= 2.4.0 时将该依赖设置为 optional -->
    <exclusions>
        <exclusion>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
        </exclusion>
    </exclusions>
</dependency>
# application.yml (不能是bootstrap.yml)
spring:
  cloud:
    nacos:
      config:
        group: DEFAULT_GROUP
        server-addr: localhost:8848
  config:
    import:
      - optional:nacos:test.yml  # 监听 DEFAULT_GROUP:test.yml
      - optional:nacos:test01.yml?group=group_01 # 覆盖默认 group, 监听 group_01:test01.yml
      - optional:nacos:test02.yml?group=group_02&refreshEnabled=false # 不开启动态刷新
      - nacos:test03.yml # 在拉取nacos配置异常时会快速失败, 会导致 spring 容器启动失败

等价于 (springboot 2.4.0 以下版本)

# bootstrap.yml
spring:
  cloud:
    nacos:
      config:
        name: test.yml
        file-extension: yml
        group: DEFAULT_GROUP
        server-addr: localhost:8848
        extension-configs:
          - dataId: test01.yml
            group: group_01
          - dataId: test02.yml
            group: group_02
            refresh: false

Precautions

  1. spring boot >= 2.4.0 默认不会启动 bootstrap 容器, 不要将上述配置写在 bootstrap.yml(properties) 里
  2. dataId 不可缺省, 不要使用相同 dataId