@PostConstruct ,getBean时报空指针异常

  • Post author:
  • Post category:其他


发生场景:

springboot项目启动时读取数据库中的计划任务,加入到定时任务缓存中等待执行,

完成这个功能的方法使用了@PostConstruct 修饰

@Service
public class TaskPlanService
    ...
    ...
    @PostConstruct
    public void initTaskScheduled() {
    //它会在这里调用相应的方法
    }
    
    ...
    ...

}

随后该方法最终调用到了任务执行类:——由于我需要在该类调用已经写好的位于

service

层的方法,所以用到了

SpringUtil

工具类得到该service。

有关该工具类的解释网上有很多,文末我也会将其贴出。


public class ScheduledTask 
{

    private  ApplicationContext app = SpringUtil.getApplicationContext();
    private  taskService = app.getBean(taskService.class);
    

    public void execute(final JobExecutionContext jobexecutioncontext) throws JobExecutionException {
        //在这里调用了taskService内的方法
        taskService.func();
    }
    
  
}

但启动项目后报错:

Error creating bean with name 'taskPlanService': Invocation of init method failed; nested exception is java.lang.NullPointerException

...
...
Caused by: java.lang.NullPointerException: null

...
...
at cn.com.test.scheduled.impl.ScheduledTask.<init>(ScheduledTask.java:5)

...
...

这里我截取了几段,可以看到是

private  taskService = app.getBean(taskService.class);

这条语句报错。这里报错的原因,发生了空指针异常。

这是因为:使用@Postcontrust注解修饰的方法在容器启动时比SpringUtil工具类中的public void setApplicationContext()方法

加载的早,所以在这里

setApplicationContext()方法会返回空指针异常。

解决方法:

在初始化init方法上,也就是文章第一个代码类,加上

@DependsOn(“springUtil”) 注解,

强制初始化SpringUtil工具类即可。

@DependsOn("springUtil")
@Service
public class BackupPlanService
    ...
    ...
    @PostConstruct
    public void initTaskScheduled() {
    //它会在这里调用相应的方法
    }
    
    ...
    ...

}

再次启动项目,空指针异常已消失……

小知识,springboot自动将类名首字母小写并返回bean名称,但是当首字母是两个大写字母开头,比如:SPringUtil,那么则原样返回bean名称,类名是啥返回啥…

附:SpringUtil工具类


https://blog.csdn.net/tuoni123/article/details/80213160

就不当复读机了



版权声明:本文为qq_41924672原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。