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

Spring Boot中@Value注解读取application.properties返回null如何解决

问题修复方案

根本原因

你手动实例化ApiKey对象的操作没有经过Spring IoC容器管理,@Value、@Autowired这类Spring依赖注入注解只会对被Spring容器托管的Bean生效,自己通过new关键字创建的对象,Spring不会执行任何注入逻辑,所以apiKey字段就是默认的null值。

修复方式

方式1:从Spring启动返回的上下文中获取Bean

SpringApplication.run方法执行完成后会返回Spring的上下文对象,直接从上下文中获取已经被Spring初始化完成的ApiKey实例即可,启动类写法参考:

package com.wook.weather;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
        // 从Spring容器中获取ApiKey实例
        ApiKey apiKeyBean = context.getBean(ApiKey.class);
        // 此处可正常读取到配置的密钥值
        System.out.println(apiKeyBean.getApiKey());
    }
}

方式2:在其他Spring托管的Bean中注入使用

如果是在业务类中需要用到ApiKey,直接给业务类加上Spring Bean注解(比如@Service、@Component、@RestController),然后通过@Autowired注入ApiKey即可,不要手动new:

package com.wook.weather;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WeatherQueryService {
    // 直接注入Spring管理的ApiKey实例
    @Autowired
    private ApiKey apiKey;

    public void queryWeather() {
        String key = apiKey.getApiKey();
        // 后续业务逻辑
    }
}

额外注意事项

  • 你的ApiKey类和启动类都在com.wook.weather包下,Spring默认会扫描启动类所在包及子包下的Bean,无需额外配置扫包规则,如果后续你把Bean放到其他包下,需要在启动类上加@ComponentScan指定扫描路径。
  • 所有需要用到Spring依赖注入能力的类,都必须注册为Spring Bean,并且只能从Spring容器中获取实例,禁止手动new创建。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:24:08