You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在其他类中获取Spring @ConfigurationProperties配置类的属性对象?

问题根源

你目前的代码存在3处核心错误,是导致其他类调用拿不到配置值的原因:

  • @Bean注解误用:@Bean用于向Spring容器注册可管理的Bean实例,不能标注在无返回值的普通方法上。你在display方法上加的@Bean会在Spring初始化PhoneProps实例、且配置属性已注入完成时被自动执行,所以内部调用能输出正确值,和你主动调用的逻辑完全无关。
  • 配置类使用不规范:@ConfigurationProperties类是纯配置承载类,无需加@Service注解,也不推荐在内部写业务方法。
  • 调用方式错误:你在其他类调用时大概率是手动new PhoneProps()创建的实例,手动创建的对象不会被Spring自动注入配置属性,所以testNumber是空数组。

正确改造步骤

  1. 修正PhoneProps类的注解和写法:
@ConfigurationProperties(prefix = "spring.phone")
@Data
@Component // 若你习惯在启动类开启绑定,可删除这个注解,参考步骤3
public class PhoneProps {
   private List<String> testNumber = new ArrayList<>();

    // 移除错误的@Bean注解
    public void display() {
        System.out.println(testNumber);
    }
}
  1. 确认YAML配置格式符合Spring宽松绑定规则:
spring:
  phone:
    test-number: # 驼峰属性自动转为短横线格式,缩进不能出错
      - 998976460010
      - 998939378668
  1. (可选)若你不想给配置类加@Component,可以在项目启动类上开启配置绑定扫描:
@SpringBootApplication
@EnableConfigurationProperties(PhoneProps.class)
public class YourProjectApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourProjectApplication.class, args);
    }
}
  1. 其他类必须通过Spring注入的方式获取PhoneProps实例,禁止手动new:
@Service
public class YourBusinessService {
    // 推荐用构造注入,也可以用@Autowired注入
    private final PhoneProps phoneProps;

    public YourBusinessService(PhoneProps phoneProps) {
        this.phoneProps = phoneProps;
    }

    public void testInvoke() {
        // 此时调用display会输出正确的配置值
        phoneProps.display();
    }
}

内容的提问来源于stack exchange,提问作者Umaralikhon Kayumov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 09:15:02