java Spring Boot@Autowired对象空指针异常
我正在开发一个spring启动应用程序来发送sms通知。这是我的课程
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
,但没有任何效果。有人能指出我的错误吗
提前谢谢
# 1 楼答案
在Springboot应用程序的主类中添加以下注释
# 2 楼答案
在使用注释时,我们应该配置@ComponentScan注释,告诉Spring软件包扫描带注释的组件。在您使用spring boot的情况下,应该在mail类(哪个类希望首先加载)中使用此注释,所以您应该在spring boot应用程序的主类中使用此注释。就像下面
# 3 楼答案
如果
@Autowired
注释不起作用并抛出NPE,这意味着spring无法在应用程序上下文中创建组件类的实例。尝试:@Component
,以便在类路径扫描期间能够拾取它们李>@Component
注释李>如需进一步帮助,请与您的项目结构一起分享主应用程序类
由于您使用的是springboot,如果您正在构建标准springboot web应用程序,最好使用sprinboot原型注释,而不是
@Component
注释@Service
:用于服务层李>@Controller
:用于控制器层。此外,DispatcherServlet将在使用@Controller
而不是使用@Component
注释的类上查找@RequestMapping
李>