springboot定时任务@Autowired自动注入失败 报空指针异常

springboot定时任务@Autowired自动注入失败 报空指针异常

一、创建一个工具类

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 解决定时任务不能注入mapper和service
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtil.applicationContext = applicationContext;
    }

    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }
}

二、使用

// 获取mapper: 获取mapper还是service自己决定
XcAdminVioCityMapper xcAdminVioCityMapper = (XcAdminVioCityMapper)ApplicationContextUtil.getBean("xcAdminVioCityMapper");
// 执行mapper接口中的方法
xcAdminVioCityMapper.truncateTable();

你可能感兴趣的:(常见问题)