web项目启动时可能需要启动一些定时任务 或者一些其他的方法,这里我使用的是listener, 因为容器启动listener时spring还未完成加载, 所以无法自动注入对象
java代码
package cn.resoft.dmps.plan.task; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import cn.resoft.dmps.plan.service.TaskMain; public class TimerStartTask implements ServletContextListener { private TaskMain taskMain; public void contextInitialized(ServletContextEvent event) { ApplicationContext applicationContext = WebApplicationContextUtils .getWebApplicationContext(event.getServletContext()); taskMain = (TaskMain) applicationContext.getBean("taskMain"); if (null == taskMain) { taskMain = new TaskMain(); } taskMain.startTimer(applicationContext); } public void contextDestroyed(ServletContextEvent sce) { } }
web.xml配置
<listener> <listener-class>cn.resoft.dmps.plan.task.TimerStartTask</listener-class> </listener>