QuartzServletContextListener 代码如下(用于监听quartz,生成ServletContext):
public class QuartzServletContextListener extends QuartzInitializerListener {
public static final String MY_CONTEXT_NAME = "servletContext";
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
super.contextDestroyed(sce);
}
@Override
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
super.contextInitialized(sce);
ServletContext servletContext = sce.getServletContext();
StdSchedulerFactory factory = (StdSchedulerFactory) servletContext
.getAttribute(QuartzInitializerListener.QUARTZ_FACTORY_KEY);
try {
factory.getScheduler().getContext()
.put(QuartzServletContextListener.MY_CONTEXT_NAME, servletContext);
} catch (SchedulerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
将QuartzServletContextListener 配置到web.xml中去:
<listener>
<listener-class>cn.bdqn.beans.QuartzServletContextListener</listener-class>
</listener>
Job代码如下:
public class QuartzTask implements Job{
@Override
public void execute(JobExecutionContext jobContext) throws JobExecutionException {
// TODO Auto-generated method stub
System.out.println("我是定时任务~~");
try {
ServletContext context = null;
try {
context = (ServletContext) jobContext.getScheduler().getContext()
.get(QuartzServletContextListener.MY_CONTEXT_NAME);
} catch (SchedulerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(context);
System.out.println("我得到的cxt是:============"+cxt);
EmpService empService = (EmpService)cxt.getBean("empService");
empService.insertData();
}catch(Exception e2) {
e2.printStackTrace();
}
}
}
WebApplicationContext有可能得到为null还需在web.xml如下配置:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
如果报Could not open ServletContext resource [/WEB-INF/applicationContext.xml]错误,需要在web.xml做如下配置
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
添加了监听org.springframework.web.context.ContextLoaderListener,导致quartz任务报错:Unable to store Job : 'FH_JOBGROUP_NAME.job1', because one already exists with this identification.
原因是ContextLoaderListener 和 DispatcherServlet 对应用上下文重复加载,applicationContext.xml被实例化2次,导致问题出现。
解决办法如下:(去掉init-param里面的param-value)
<servlet>
<servlet-name>seckill-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置springMVC需要加载的配置文件
spring-dao.xml,spring-service.xml,spring-web.xml
Mybatis - > spring -> springmvc
-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value><!-- classpath:applicationContext.xml --></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>