新⼈踩坑的⼀天——springboot注⼊mapper时出现
java.lang.NullP。。。
来公司的第⼆周接到了定时任务的开发需求:每天早上⼗点发送⽤户报表邮件。校招新⼈菜鸟没做过这玩意有些懵(尴尬)于是决定分步写,从excel导出->邮件发送->定时器实现->mapper层返回集接收,前⼏步都没啥问题,都在service层,可以⽤main⽅法单独测试下,可以发送邮件,但是通过service调⽤mapper时问题就来了——菜鸟踩坑了,抛出java.lang.NullPointerException,下图是代码:
@Component
@EnableScheduling
@Service("cronTaskService")
public class CronTaskServiceImpl implements CronTaskService {
@Resource
private ExportExcelServiceImpl exportExcelService;
@Resource
private MailSendServiceImpl mailSendService;
private final static Logger log = Logger(CronTaskServiceImpl.class);
private static int  Count = 0;
@Scheduled(cron = "*/10 * * * * ?")
@Override
public void out(){
new ExportExcelServiceImpl().exportExcel("zhoubaobiao1");
//String filePath = portExcel("周报表" + Count++ + ".xls");
//mailSendService.sendEmail(filePath);
log.info("-----------success-------\n");
}
}
问了组内的前辈(应该也是没做⼏年),问题解决不了,定位不对。后⾯⼜在⽹上了许久,在⼀位博主博⽂中到了原因,链接:blog.csdn/itguangit/article/details/78305278
我的想法是通过new()⽅法创建ExportExcelServiceImpl对象调⽤exportExcel()⽅法,exportExcel()⽅法中调⽤mapper层连接云上库,然后实现导出excel数据表到本地,结果就出现了空指针异常
[] 2019-12-19 13:22:20.003 [pool-1-thread-1] ERROR o.s.s.support.TaskUtils$LoggingErrorHandler - Unexpected error occurred in scheduled task.
java.lang.NullPointerException: null
at job.service.portExcel(ExportExcelServiceImpl.java:116)
at job.service.impl.CronTaskServiceImpl.out(CronTaskServiceImpl.java:36)
flect.NativeMethodAccessorImpl.invoke0(Native Method)
flect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
flect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at flect.Method.invoke(Method.java:498)
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at org.urrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at urrent.Executors$RunnableAdapter.call(Executors.java:511)
nullpointerexception为什么异常
at urrent.FutureTask.run$$$capture(FutureTask.java:266)
at urrent.FutureTask.run(FutureTask.java)
at urrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at urrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at urrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at urrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
想法⽐较美好,但是初接触springboot不知道⼀个关键问题,new()出来的对象,⽆论是在对象或是在对象内部通过注解@Resource或者是@Autowired实现⾃动装配,或者是对⽅法进⾏@PostConstruct标记(⼜挖坑坑⾃⼰,引发其他⼀系列问题),期望spring扫描到其中的mapper对象,都做不到;spring不会对其进⾏⾃动装配bean,注⼊mapper失败,导致mapper层映射⽆法完成,写好的XML中的SQL⽆法执⾏。后来在上博⽂中到了原因,重新通过@Resource注解注册上⾯⼏个Service层对象,让spring⾃⼰完成创建和装配,才解决了问题。不复杂,但是⽹上很多地⽅的答案不是需要的,问题定位由于缺乏
经验还是花了些时间(哈哈 )如有不对请指教,程序猿学习

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。