有时候我们需要在web工程中定时器类里面获得spring的IOC容器,即WebApplicationContext,用它来获取实现了某接口的所有的bean,因为@Autowired貌似只能注入单个bean。
一开始我是写的一个ServletContextListener,启动服务器的时候就构造定时器并启动,把WebApplicationContext传给定时器的Job,在ServletContextListener中这样得到WebApplicationContext:
- 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();
- }
- }
- }
重点在
- 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>