Quartz中无法@Autowired注入mapper和service的最优解决方案

一、问题现象

@Component
public class SecKillGoodsToRedisTask extends QuartzJobBean {
    @Autowired
    TbSeckillGoodsMapper tbSeckillGoodsMapper;
	
	// 具体定制任务内容
	 @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException 
    {
     	QueryWrapper queryWrapper = new QueryWrapper<>();
    	tbSeckillGoodsMapper.selectList(queryWrapper);
    	// TODO
	}


 }   

以上代码在启动定时任务开始执行的时候就会报空指针异常,原因是任务类是反射创建的,没有交给Spring容器管理。

二、解决方案

修改成这样就行,类似不在容器管理类中需要用到ico中bean的都可以这么写

@Component
public class SecKillGoodsToRedisTask extends QuartzJobBean {
    @Autowired
    TbSeckillGoodsMapper tbSeckillGoodsMapper;
    private static SecKillGoodsToRedisTask secKillGoodsToRedisTask;
    @PostConstruct
    public void init(){
        secKillGoodsToRedisTask = this;
        secKillGoodsToRedisTask.tbSeckillGoodsMapper = this.tbSeckillGoodsMapper;
    }
	
	// 具体定制任务内容
	 @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException 
    {
     	QueryWrapper queryWrapper = new QueryWrapper<>();
    	secKillGoodsToRedisTask.tbSeckillGoodsMapper.selectList(queryWrapper);
    	// TODO
	}


 }   

你可能感兴趣的:(java,java,spring,前端)