首页 > 解决方案 > Spring Boot @Autowired 对象 - Nullpointer 异常

问题描述

我正在开发一个弹簧启动应用程序来发送短信通知。这是我的课程。

package org.otp.services;

import org.otp.Configurations;
import com.mashape.unirest.http.HttpResponse;
import org.springframework.stereotype.Component;

import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;

@Component
public class SmsService
{
    private static final Logger LOG = LoggerFactory.getLogger(SmsService.class);

    public String send(String mobile, String msg)
    {
        //Code 
    }
}

这是使用上述类发送通知的类。

package org.otp.controllers;

import org.otp.Constants;
import org.otp.services.EmailService;
import org.otp.services.SmsService;
import org.otp.dto.MessageRequest;
import org.otp.dto.MessageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

@Component
public class MessageController {

    private static final Logger LOG = LoggerFactory.getLogger(MessageController.class);

    @Autowired
    SmsService smsService;

    public void sendMessageToAlert(@RequestBody MessageRequest messageRequest)
    {
        String smsStatus = "FAIL";
        MessageResponse messageResponse = new MessageResponse();

         //1. Nullpointer
        smsStatus = smsService.send(messageRequest.getMobileNo(),messageRequest.getMessage());

    }
}

主班

package org.otp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
public class OtpServiceApplication implements ApplicationRunner
{
    public static void main(String[] args) {
        SpringApplication.run(OtpServiceApplication.class, args);
    }
}

问题是,我在 (1) 中得到一个空指针异常,指出我的SmsService对象为空。而且我的主类在包中org.otp,所以这里的两个类属于子包,所以不需要组件扫描。

因此,我很困惑如何解决这个问题。我在这里尝试了很多答案,例如在主类中添加@Component注释,但没有任何效果。@ComponentScan有人可以在这里指出我的错误。

提前致谢。

标签: javaspringspring-bootnullpointerexceptionautowired

解决方案


如果您的@Autowired注解不起作用并抛出 NPE,则意味着 spring 无法在应用程序上下文中创建组件类的实例。尝试:

  • 验证类是否在类路径中以进行扫描,并检查以确保所有自动连接的类都具有注释@Component以使它们能够在类路径扫描期间被拾取。
  • 检查 spring boot 启动日志以验证 bean 创建过程中是否有任何错误。
  • 检查以确保服务层中使用的所有相关类都已正确自动连接,并且注入的类使用@Component.

如需进一步帮助,请与您的项目结构一起分享主要应用程序类。


由于您使用的是 springboot ,因此@Component如果您正在构建标准 springboot Web 应用程序,最好使用 sprinboot 原型注解而不是注解。

  • @Service: 服务层。
  • @Controller:对于控制器层。此外,DispatcherServlet 将查找使用注释但不使用@RequestMapping注释的类。@Controller@Component

推荐阅读