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

Spring Boot @ConfigurationProperties配置手动实例化后取值为null如何解决

问题根因

你手动在AnimalChooser中通过new AnimalProperties()创建的对象不属于Spring IoC容器的托管范围,只有Spring容器管理的@ConfigurationProperties类才会自动绑定application.yml中的配置值,手动实例化的对象只会使用代码中的默认初始化值,自然拿不到配置的name属性。

解决方案

步骤1:改造AnimalChooser,交给Spring托管并注入配置类

给AnimalChooser添加@Component注解,将其注册为Spring Bean,同时注入Spring已经完成属性绑定的AnimalProperties实例,不要手动new:

@Component
public class AnimalChooser {
    // 注入Spring托管的配置类,已经完成yml属性绑定
    private final AnimalProperties animalProperties;

    // 推荐用构造器注入,更符合Spring最佳实践
    public AnimalChooser(AnimalProperties animalProperties) {
        this.animalProperties = animalProperties;
    }
    
    public Animal getById(int id) {
        if(id == Tiger.ID) {
            return animalProperties.getTiger();
        } else {
            return animalProperties.getLion();
        }
    }
}

步骤2:改造测试类,注入AnimalChooser实例

测试类需要改为Spring Boot测试,注入Spring托管的AnimalChooser,不要自己new对象:

@SpringBootTest
@EnableConfigurationProperties(AnimalProperties.class)    
class AnimalChooserTest {
    // 注入Spring托管的AnimalChooser
    @Autowired
    private AnimalChooser animalChooser;
    
    @Test
    void shouldReturnCorrectNameForTiger() {
        Animal tiger = animalChooser.getById(1);
        assertEquals("Joe", tiger.getName());
    }
}

可选校验项

如果你的AnimalProperties绑定测试已经能正常通过,说明配置扫描是正常的,否则可以在启动类上添加@ConfigurationPropertiesScan注解,确保配置类被Spring正确扫描加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 20:15:01