spring的scheduled-tasks定时任务,applicationcontextaware获取spring上下文

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_17079071/article/details/79769469
<-- application.xml中添加下面的代码-->
<!-- 定时任务 -->
	<task:annotation-driven/>
	<!-- applicationcontextaware,获取service -->
	<bean id="applicationContextUtis" class="com.infotrust.common.utils.commutils.ApplicationContextUtis" />
	<!-- 定时任务所在的类 -->
	 <bean id="monitorTask" class="com.infotrust.creditreport.reportmonitor.task.MonitorTask" /> 
	<!-- 监控定时任务配置时间 -->
	<task:scheduled-tasks>   
        <task:scheduled ref="monitorTask" method="monitorinfo" cron="0 58 14 * * ?"/> 
    </task:scheduled-tasks>
package com.infotrust.common.utils.commutils;

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

/**
 * 定时任务类用到:获取ApplicationContext获取spring上下文,获取service
 * @date 2018年3月30日上午11:17:07
 */
public class ApplicationContextUtis implements ApplicationContextAware{
	private static ApplicationContext applicationContext;

	public static ApplicationContext getApplicationContext()
			throws BeansException {
		return applicationContext;
	}
	
	public void setApplicationContext(ApplicationContext apc)
			throws BeansException {
		applicationContext = apc;
		
	}

	/**
	 * 获取service的方法
	 * @param beanName service的名称
	 * @return
	 */
	public static Object getBean(String beanName){
		return applicationContext.getBean(beanName);
	}
}
<--springmvc.xml中添加需要用service的扫描的包-->
<context:component-scan base-package="com.infotrust.creditreport.reportmonitor.task">
</context:component-scan>
package com.infotrust.creditreport.reportmonitor.task;

import java.util.List;

import org.springframework.stereotype.Component;

import com.infotrust.common.utils.commutils.ApplicationContextUtis;
import com.infotrust.creditreport.reportmonitor.po.ReportMonitor;
import com.infotrust.creditreport.reportmonitor.service.IReportmonitorService;

/**
 * 定时任务的执行的类和方法
 * @date 2018年3月30日上午10:24:26
 */
@Component
public class MonitorTask{
	
	public void monitorinfo(){
//使用ApplicationContextUtis工具类获取service
IReportmonitorService reportmonitorService=(IReportmonitorService)ApplicationContextUtis.getBean("reportmonitorService");
		List<ReportMonitor> relist= reportmonitorService.getReportmonitorList(null, null, null, null, null);
		for (ReportMonitor reportMonitor : relist) {
			System.out.println(reportMonitor.getEnterprisename());
		}
	}

}
@Service("reportmonitorService")//service别名
//实现类方法
public class ReportmonitorServiceImpl implements IReportmonitorService {}
//注解获取service,需要application.xml配置service的bean
 @Autowired
 private IReportmonitorService reportmonitorService;
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

猜你喜欢

转载自blog.csdn.net/qq_17079071/article/details/79769469