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

Spring中如何用@Value注入非原始对象List?启动报错求助

解决SpringBoot中@Value注入复杂对象列表失败的问题

问题根源

@Value注解仅支持注入简单类型(字符串、数字等)或简单集合(如List<String>),无法直接解析YAML中的复杂对象列表(List<Perm>),这就是你遇到Could not resolve placeholder错误的核心原因。

解决方案:使用@ConfigurationProperties绑定配置

SpringBoot提供的@ConfigurationProperties专门用于处理复杂配置结构的绑定,完美适配YAML中的对象列表场景。

步骤1:调整服务类的注入逻辑

移除@Value注解,改用@ConfigurationProperties指定配置前缀:

@Slf4j
@Getter
@Service
@Accessors(fluent = true)
@ConfigurationProperties(prefix = "myservice.api") // 指定配置层级前缀
public class MyService {

    private List<Perm> perms; // 直接声明属性,无需@Value

    public List<Perm> getListOfPerms() {
        return perms;
    }

    @Getter
    @Setter // 必须添加Setter,Spring需要通过它为对象属性赋值
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Perm {

        @NotBlank
        private String name;

        @NotBlank
        private String guid;

        private int index;
    }
}

步骤2:启用配置属性绑定

确保SpringBoot能识别并处理配置绑定,二选一即可:

  • 方式一:在启动类上添加注解开启支持
@SpringBootApplication
@EnableConfigurationProperties(MyService.class)
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}
  • 方式二:由于MyService已经标记了@Service,Spring会自动扫描并完成绑定,无需额外添加注解

步骤3:保持原YAML配置不变

你的application.yaml结构完全正确,不需要修改:

myservice:
  api:
    perms:
      -
        name: xyz
        guid: abc
        index: 0

关键注意事项

  • Perm类必须包含Setter方法(或添加@Setter注解),否则Spring无法为对象的属性赋值
  • @ConfigurationProperties的prefix要精准匹配YAML中的层级(这里myservice.api对应下属的perms列表)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 04:01:44