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

Spring注入配置报错:this.rabbit为null,请求协助排查

问题根源

你遇到的this.rabbit null错误,核心原因是类成员变量的初始化顺序问题:

  • TRON_TRANSACTION_URL和TRON_ACC_URL是final修饰的成员变量,会在类实例创建阶段(构造器执行前后)完成初始化
  • Spring的@Autowired注入是在类实例创建完成后才执行的,所以初始化这两个URL时,rabbit还未被注入,处于null状态,调用rabbit.getTRON_WALLET()自然会报空指针。

解决方案1:使用@PostConstruct延迟初始化URL

去掉final修饰符,通过@PostConstruct注解在Spring注入完成后再初始化URL:

@Service
public class PaymentServiceImpl implements PaymentService {

    private final PaymentRepositoryImpl paymentRepository;
    private final RestTemplate restTemplate;
    private final CryptoWalletsRabbit rabbit;

    // 构造器注入所有依赖(Spring官方推荐方式)
    public PaymentServiceImpl(PaymentRepositoryImpl paymentRepository, RestTemplate restTemplate, CryptoWalletsRabbit rabbit) {
        this.paymentRepository = paymentRepository;
        this.restTemplate = restTemplate;
        this.rabbit = rabbit;
    }

    private String TRON_TRANSACTION_URL;
    private String TRON_ACC_URL;

    @PostConstruct
    public void initUrls() {
        String tronWallet = rabbit.getTRON_WALLET();
        TRON_TRANSACTION_URL = "https://api.trongrid.io/v1/accounts/" + tronWallet + "/transactions?only_to=true&limit=1";
        TRON_ACC_URL = "https://api.trongrid.io/v1/accounts/" + tronWallet + "/transactions?only_to=true&limit=1";
    }
}

解决方案2:构造器注入所有依赖后直接初始化URL

将rabbit加入构造器注入,同时在构造器内完成URL初始化:

@Service
public class PaymentServiceImpl implements PaymentService {

    private final PaymentRepositoryImpl paymentRepository;
    private final RestTemplate restTemplate;
    private final CryptoWalletsRabbit rabbit;
    private final String TRON_TRANSACTION_URL;
    private final String TRON_ACC_URL;

    // 构造器注入所有依赖,同步初始化URL
    public PaymentServiceImpl(PaymentRepositoryImpl paymentRepository, RestTemplate restTemplate, CryptoWalletsRabbit rabbit) {
        this.paymentRepository = paymentRepository;
        this.restTemplate = restTemplate;
        this.rabbit = rabbit;
        String tronWallet = rabbit.getTRON_WALLET();
        this.TRON_TRANSACTION_URL = "https://api.trongrid.io/v1/accounts/" + tronWallet + "/transactions?only_to=true&limit=1";
        this.TRON_ACC_URL = "https://api.trongrid.io/v1/accounts/" + tronWallet + "/transactions?only_to=true&limit=1";
    }
}

注意事项

  • 优先使用构造器注入,这是Spring官方推荐的依赖注入方式,能保证依赖不可变,从根源避免空指针问题
  • 禁止在final成员变量的初始化表达式中调用依赖对象的方法,因为此时依赖还未完成注入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:00:29