You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Spring Boot中如何结合配置中心使用@ConfigurationProperties?

切换到配置中心+解决@ConfigurationProperties失效问题

我来帮你梳理下怎么把本地配置切换到配置中心,以及解决@ConfigurationProperties不生效的问题——毕竟我之前也踩过类似的坑😉

一、先搞定配置中心的基础改造

不管你用的是Nacos、Spring Cloud Config还是其他主流配置中心,基础步骤大差不差:

  1. 添加配置中心依赖
    比如用Nacos的话,把这个Maven依赖加到你的pom.xml里:

    <!-- Nacos配置中心依赖示例 -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    </dependency>
    

    如果是Spring Cloud Config,就换成spring-cloud-starter-config依赖就行。

  2. 删掉本地的@PropertySource注解
    配置中心的配置会被Spring优先加载,不需要再用@PropertySource指定本地文件了,直接删掉就行。

  3. 配置配置中心连接信息
    注意!这个配置要写在bootstrap.propertiesbootstrap.yml里(不是application开头的文件),因为配置中心的连接信息需要在应用启动初期就加载。以Nacos为例:

    spring:
      cloud:
        nacos:
          config:
            server-addr: 你的配置中心地址:端口 # 比如localhost:8848
            namespace: 可选,填你的命名空间ID
            group: 可选,填配置分组名
            file-extension: yaml # 配置中心里的配置文件后缀,yml或properties都行
      application:
        name: 你的服务名 # 配置中心里的配置文件名要和这个服务名对应,比如服务名是demo-service,配置文件就叫demo-service.yaml
    

二、解决@ConfigurationProperties不生效的核心问题

你说@Value能用但@ConfigurationProperties不行?这大概率是几个容易忽略的小细节没做好,逐个排查:

1. 确保配置类被Spring管理

@ConfigurationProperties本身不会把类纳入Spring容器,你得手动加:

  • 要么给配置类加@Component注解:
    @Component
    @ConfigurationProperties(prefix = "your.config.prefix")
    public class YourConfigProps {
        private String prop1;
        private Integer prop2;
        // 下面的getter和setter必须要有!
        // ...
    }
    
  • 要么在主启动类/配置类上加@EnableConfigurationProperties(YourConfigProps.class),显式告诉Spring要启用这个配置类:
    @SpringBootApplication
    @EnableConfigurationProperties(YourConfigProps.class)
    public class YourApp {
        public static void main(String[] args) {
            SpringApplication.run(YourApp.class, args);
        }
    }
    
    这一步是最容易忘的,很多人就是因为没加这个导致配置绑定失败。

2. 必须写getter和setter方法

@ConfigurationProperties是通过setter方法注入属性的,不像@Value是直接给字段赋值。所以你的配置类里每个属性都要有对应的getter和setter,少一个都不行!

3. 检查配置前缀是否完全匹配

比如你配置中心里的配置是:

your:
  config:
    prefix:
      prop1: hello-world
      prop2: 2024

那@ConfigurationProperties的prefix必须是"your.config.prefix",大小写、层级都不能错,差一个字符都绑定不上。

4. 验证配置是否被正确加载

可以用Spring Boot Actuator来检查配置加载情况:

  • 先加Actuator依赖:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    
  • 然后在application.yml里开启configprops端点:
    management:
      endpoints:
        web:
          exposure:
            include: configprops
    
  • 启动服务后访问/actuator/configprops,找你的配置类对应的条目,看看属性值是不是配置中心里的内容,这样就能确认配置有没有被拉取到。

5. 检查配置中心的文件格式

如果配置中心用的是properties格式,键名要和prefix对应,比如:

your.config.prefix.prop1=hello-world
your.config.prefix.prop2=2024

别把格式写错了,不然绑定肯定失败。

三、完整示例(Nacos版本)

给你一个能直接跑的完整示例,方便你对照:

  1. Maven依赖
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
</dependencies>
  1. bootstrap.yml
spring:
  cloud:
    nacos:
      config:
        server-addr: localhost:8848
        file-extension: yaml
  application:
    name: demo-service
  1. 配置类
@Component
@ConfigurationProperties(prefix = "demo.config")
public class DemoConfig {
    private String appName;
    private Integer maxRequestCount;

    // getter和setter必须齐全
    public String getAppName() {
        return appName;
    }

    public void setAppName(String appName) {
        this.appName = appName;
    }

    public Integer getMaxRequestCount() {
        return maxRequestCount;
    }

    public void setMaxRequestCount(Integer maxRequestCount) {
        this.maxRequestCount = maxRequestCount;
    }
}
  1. 配置中心的配置文件(demo-service.yaml)
    在Nacos控制台创建这个配置,内容:
demo:
  config:
    appName: my-demo-app
    maxRequestCount: 1000
  1. 使用配置的Controller
@RestController
public class DemoController {
    private final DemoConfig demoConfig;

    // 推荐用构造注入,避免空指针
    public DemoController(DemoConfig demoConfig) {
        this.demoConfig = demoConfig;
    }

    @GetMapping("/show-config")
    public String showConfig() {
        return String.format("App名称:%s,最大请求数:%d", demoConfig.getAppName(), demoConfig.getMaxRequestCount());
    }
}

启动服务后访问/show-config,就能看到配置中心里的属性值啦!

内容的提问来源于stack exchange,提问作者Thien Nguyen

火山引擎 最新活动