Spring 中的任务

Tasks in Spring

我有一个应用程序(Spring 4 MVC+ JPA + MySQL+使用注释的 Maven 集成示例),使用基于注释的配置将 Spring 与 Hibernate 集成;我想创建一个任务以便在控制器中使用它

有这个任务:

@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));
     }

}

--

我将这段代码放在控制器中,但出现了 NullpointerException

SMSSenderTask smsSenderTask = new SMSSenderTask ("ddd", "33473664038");
smsSenderTask.run();

当你使用new 语句构建任务时object.U 自动装配服务smsService 尚未初始化。所以当你调用 运行 方法时,当执行到 smsService.sendSMS(msg, to); ,程序抛出空指针异常。

您可以将 SmsService 作为您的代码的构造函数参数来避免这种情况发生。