为了提高程序运行的效率,我们可以在程序初始化运行的时候就加载一些基本不会改变的数据,比如查询出中国的省份和城市等等。
那么,在初始化的方式有哪些呢?
在web工程中,可以用监听器来实现。在普通的java项目中,可以用spring中的事件来实现
下面介绍web 项目中的实现
一、InitListener
<span style="font-size:18px;">package com.seven.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.seven.service.UserService;
/**
* ServletContext的监听器,用于做初始化操作,必须是在web工程下
* @author Administrator
*
*/
public class InitListener implements ServletContextListener {
/**
* 初始化的方法
*/
public void contextInitialized(ServletContextEvent sc) {
//做一些初始化的操作,怎么拿到service对象,一定要从Spring的Ioc容器中拿
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc.getServletContext());
UserService userService = (UserService) ac.getBean("userService");
System.out.println("InitListener.contextInitialized()-->>"+userService);
}
/**
* 销毁的方法
*/
public void contextDestroyed(ServletContextEvent arg0) {
}
}</span>
二、web.xml中的配置
<span style="font-size:18px;"> <!-- 配置我们自己手工添加的用于初始化操作的监听器 -->
<listener>
<listener-class>com.seven.listener.InitListener</listener-class>
</listener></span>
开启web容器,初始化工作就会进行了