我正在开发一个Spring Boot应用程序来发送短信通知。这是我上课的目的。
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)中得到一个 nullpointer异常,说明我的 SmsService 对象为null。而且我的主类在软件包org.otp
中,所以这里的两个类都在子软件包下,因此不需要组件扫描。
因此,我很困惑该怎么办。我在这里尝试了许多答案,例如在主类中添加了@Component
批注和@ComponentScan
,但没有任何效果。有人可以在这里指出我的错误。
谢谢。