在quartz的Job中獲得Spring的WebApplicationContext或ServletContext
阿新 • • 發佈:2017-08-03
listen package load str tcl imp attribute utf ger
有時候我們需要在web工程中定時器類裏面獲得spring的IOC容器,即WebApplicationContext,用它來獲取實現了某接口的所有的bean,[email protected]
一開始我是寫的一個ServletContextListener,啟動服務器的時候就構造定時器並啟動,把WebApplicationContext傳給定時器的Job,在ServletContextListener中這樣得到WebApplicationContext:
[java] view plain copy- WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
然後在Job中調用webApplicationContext.getBeansOfType(InfoService.class) 得到實現接口的所有bean。
其實,可以更簡單,廢話少說,這是一個POJO的Job:
- package com.gxjy.job;
- import java.util.Map;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.context.ContextLoader;
- import org.springframework.web.context.WebApplicationContext;
- import com.gxjy.dao.InfoDao;
- import com.gxjy.service.InfoService;
- import com.gxjy.service.runnable.DudeRunner;
- public class ScrawlerJob{
- @Autowired
- private InfoDao infoDao;
- public void execute() {
- WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
- Map<String, InfoService> map = wac.getBeansOfType(InfoService.class);
- for (InfoService infoService : map.values()) {
- System.out.println("啟動:"+infoService.getClass().getName());
- new Thread(new DudeRunner(infoService, infoDao)).start();
- }
- }
- }
重點在
[java] view plain copy- ContextLoader.getCurrentWebApplicationContext();
這個可以直接獲取WebApplicationContext,當然還可以進一步調用getServletContext()就獲取到ServletContext了。
這是spring中關於quartz的配置:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
- <bean id="job" class="com.gxjy.job.ScrawlerJob"></bean>
- <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
- <property name="targetObject">
- <ref bean="job"/>
- </property>
- <property name="targetMethod">
- <value>execute</value>
- </property>
- </bean>
- <bean id="trigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
- <property name="jobDetail">
- <ref bean="jobDetail"/>
- </property>
- <property name="cronExpression">
- <value>0 0 3 * * ?</value>
- </property>
- </bean>
- <bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
- <property name="triggers">
- <list>
- <ref bean="trigger"/>
- </list>
- </property>
- <property name="autoStartup" value="true"></property>
- </bean>
- </beans>
maven依賴除了基本的spring和quartz之外還需要加入spring-context-support的依賴(包含對quartz的支持):
- <pre name="code" class="html"> <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
- <version>4.2.2.RELEASE</version>
- </dependency>
在quartz的Job中獲得Spring的WebApplicationContext或ServletContext