我们在JAVA开发的过程中,往往需要在程序一启动时就执行一些操作,例如载入基本数据或初始化系统什么的。
这是用了监听器(Listener)实现的,参考书籍《轻量级Java EE》企业应用实战(第4版) 李刚编著
package com.cn.bwq.init;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class Startup implements ServletContextListener{
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
System.out.println("程序销毁了");
}
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
System.out.println("程序启动了(首先执行)");
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
以下代码在程序启动时同样也会被执行,不过是先执行上面的,再执行下面的
package com.cn.bwq.init;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
public class StartupBySpringMvc implements ApplicationListener<ContextRefreshedEvent> {
public void onApplicationEvent(ContextRefreshedEvent evt) {
// TODO Auto-generated method stub
if(evt.getApplicationContext().getParent() != null){
System.out.println("系统启动了(然后执行)");
}
}
}