springboot 定时任务使用service
首先定义一个utils工具类: ApplicationContextUtil ,并注册为 Component
package xin.qust.platform.utils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; public static ApplicationContext getApplicationContext() { return applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ApplicationContextUtil.applicationContext = applicationContext; } public static Object getBean(String beanName) { return applicationContext.getBean(beanName); } }
2. 给与要使用的service定义名字便于引用:
@Service("YuqingReportService") public class YuqingReportService {}
3. 在定时任务中实例化该service对象:
YuqingReportService reportService = (YuqingReportService) ApplicationContextUtil.getBean("YuqingReportService");
reportService.getReport();
心有远方 何惧苟且