我有一个应用程序(使用注释的 Spring 4 MVC+ JPA + MySQL+Maven 集成示例),使用基于注释的配置将 Spring 与 Hibernate 集成;我想创建一个任务以便在 Controller 中使用它
有这个任务:
@Configurable
public class SMSSenderTask implements Runnable {
protected static final Logger LOGGER = LoggerFactory.getLogger(SMSSenderTask.class);
@Autowired
SMSSender smsService;
private String msg;
private String to;
public SMSSenderTask(String msg, String to) {
super();
this.msg = msg;
this.to = to;
}
@Override
public void run() {
try {
smsService.sendSMS(msg, to);
} catch (UnsupportedEncodingException e) {
LOGGER.error(e.getMessage());
} catch (ClientProtocolException e) {
LOGGER.error(e.getMessage());
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
}
}
还有这个
public class SMSSenderTaskExecutor {
private TaskExecutor taskExecutor;
@Autowired
SMSSender smsService;
@Autowired
public SMSSenderTaskExecutor(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
public void sendSMS(String msg, String to) {
taskExecutor.execute(new SMSSenderTask (msg, to));
}
}
--
我将这段代码放入 Controller 中,但出现 NullpointerException
SMSSenderTask smsSenderTask = new SMSSenderTask ("ddd", "33473664038");
smsSenderTask.run();
最佳答案
当你使用new语句构造一个任务对象时,你的 Autowiring 服务smsService还没有初始化。所以当你调用run方法时,当执行到smsService.sendSMS(msg, to);时,程序抛出空指针异常。
您可以将 SmsService 作为构造函数参数放入您的代码中以避免这种情况发生。
关于java - Spring 任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34824330/