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

Spring Boot @ConfigurationProperties注入空指针问题求助

问题分析与解决方案

核心问题在于:你手动new了NameConfiguration实例,这个对象不在Spring容器的管理范围内,Spring无法对其内部的@Autowired注入逻辑生效,导致property字段为null,触发空指针异常。

另外你之前代码里还有一个不规范的写法:@Autowired注解和手动new对象同时使用,这会破坏Spring的依赖注入机制,虽然之前Controller里看似正常,但属于错误用法。


步骤1:修正依赖注入的错误写法

所有Spring管理的Bean,内部的依赖必须由Spring容器注入,禁止手动new对象。

修正NameConfiguration类

@Component
public class NameConfiguration {
    // 仅保留@Autowired,移除手动new的代码
    @Autowired
    private NameProperties property;
    
    public void getName(int index) {
        // 增加非空判断,避免索引越界或空指针
        if (property != null && property.getName() != null && !property.getName().isEmpty()) {
            System.out.println(property.getName().get(index));
        }
    }
}

修正测试用的Controller

@RestController
@CrossOrigin
@RequestMapping("/tes/**")
public class NameController {
    // 用@Autowired注入Spring容器管理的NameConfiguration实例,禁止手动new
    @Autowired
    private NameConfiguration conf;
    
    @GetMapping
    public String tes() {
        conf.getName(0);
        return "操作完成";
    }
}

步骤2:优化配置属性类的规范写法(可选但推荐)

NameProperties类用@ConfigurationProperties绑定配置时,更规范的做法是配合@EnableConfigurationProperties或@ConfigurationPropertiesScan,而非@Configuration(后者是用来定义配置类的,和配置属性绑定的职责分开更清晰)。

修改NameProperties类

@ConfigurationProperties(prefix = "example")
// 移除@Configuration注解
public class NameProperties {
    private List<String> name;
    
    public List<String> getName() {
        return name;
    }
    public void setName(List<String> name) {
        this.name = name;
    }
}

在启动类添加启用注解

@SpringBootApplication
@EnableConfigurationProperties(NameProperties.class) // 启用配置属性绑定
// 或者用@ConfigurationPropertiesScan("你的配置类所在包路径"),批量扫描配置属性类
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

关键注意点

  1. Spring仅对容器内的Bean执行依赖注入,手动new的对象不受容器管理,内部的@Autowired不会生效。
  2. @Autowired注解和手动new绝对不能同时使用,这会覆盖Spring的注入逻辑。
  3. 配置属性类的职责是绑定配置文件,用@ConfigurationProperties配合启用注解是官方推荐的规范写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:10:27