需求
定时任务中注册task
这里如果直接使用
@Autowired
DynamicPrintTask task;
这个task的话 因为设置的是单例的 所以 不管你加多少 task 他永远只会以最后一个task 来执行所有的任务
所以这里需要用 new的形式来创建 task
但是这个task 里面 用到了 很多 mapper 如果直接 用 new 的话 这些mapper 则会报 null
所以我们需要通过 ApplicationContext 来获取上下文
解决方案
public class SpringContextUtil {
private static ApplicationContext applicationContext;
//获取上下文
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//设置上下文
public static void setApplicationContext(ApplicationContext applicationContext) {
SpringContextUtil.applicationContext = applicationContext;
}
//通过名字获取上下文中的bean
public static Object getBean(String name){
return applicationContext.getBean(name);
}
//通过类型获取上下文中的bean
public static Object getBean(Class<?> requiredType){
return applicationContext.getBean(requiredType);
}
}
public class WebApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(WebApplication.class, args);
SpringContextUtil.setApplicationContext(context);
}
}
错误使用springbean
// @Autowired
// SpringScheduledCronMapper springScheduledCronRepository;
//
// @Autowired
// ReportModulMapper reportModulMapper;
//
// @Autowired
// TemplateAssemblyMapper templateAssemblyMapper;
//
// @Autowired
// VulnerabilityDataAnalysisService vulnerabilityDataAnalysisService;
//
// @Autowired
// ReportAssemblyMapper reportAssemblyMapper;
//
// @Autowired
// SafetyIncidentHandlingService safetyIncidentHandlingService;
//
// @Autowired
// ReportRecordMapper reportRecordMapper;
//
正确使用
ReportModulMapper reportModulMapper = (ReportModulMapper) SpringContextUtil.getBean(ReportModulMapper.class);
TemplateAssemblyMapper templateAssemblyMapper = (TemplateAssemblyMapper)SpringContextUtil.getBean(TemplateAssemblyMapper.class);
VulnerabilityDataAnalysisService vulnerabilityDataAnalysisService = (VulnerabilityDataAnalysisService)SpringContextUtil.getBean(VulnerabilityDataAnalysisService.class);
ReportAssemblyMapper reportAssemblyMapper= (ReportAssemblyMapper)SpringContextUtil.getBean(ReportAssemblyMapper.class);
SafetyIncidentHandlingService safetyIncidentHandlingService = (SafetyIncidentHandlingService)SpringContextUtil.getBean(SafetyIncidentHandlingService.class);
ReportRecordMapper reportRecordMapper =(ReportRecordMapper)SpringContextUtil.getBean(ReportRecordMapper.class);
原因
@Autowired 是获取springioc容器里面的对象 而 通过 new 的形式 是 不能 获取到的 所以 需要通过ApplicationContext 获取上下午 获取到 bean对象