1.spring-listener:
a)
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;public class ServletImpl implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) { // TODO Auto-generated method stubSystem.out.println("web启动的时候调用此类********************************************************");
}@Override
public void contextDestroyed(ServletContextEvent sce) { // TODO Auto-generated method stub System.out.println("webdestroy的时候调用此类********************************************************");}
}
b)web.xml配置
<!-- 自定义监听器 -->
<listener> <listener-class>com.servlet.impl.ServletImpl</listener-class> </listener>经过上边简单的两部操作,即可实现web容器启动时候执行某个动作。
2.spring-task
a)task.class,红色标记都是必须的。
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@EnableScheduling
@Componentpublic class FooTask {@Scheduled(cron="0 0/1 8-23 * * ?")
public void run(){ System.out.println("start run..........................................................."); }}b)spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd"> <!-- auto scan task --><task:annotation-driven/> <context:annotation-config/> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <context:component-scan base-package="com.task"/>参考:http://blog.csdn.net/wumingqian_137229/article/details/52846261 感谢分享!