天天看點

spring的scheduled-tasks定時任務,applicationcontextaware擷取spring上下文

<-- 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);