在一個基於Spring的web項目中,當我們需要在應用啟動時加載數據字典時,可寫一個監聽實現javax.servlet.ServletContextListener
實現其中的contextInitialized(ServletContextEvent sce) 方法完成,初始化的操作。代碼示例如下
一、監聽程序
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; public class InitDicListener implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) { //spring 上下文 ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()); /* ServiceBean bean1=appContext.getBean("xxx"); ...業務方法,加載數據字典等。 */ } public void contextDestroyed(ServletContextEvent sce) { } }
二、配置文件中加入配置
在web.xml中加入 監聽配置, 但要寫在Spring配置的下面,這樣我們自定義的監聽會在Spring監聽之后啟動,這個時候在我們自定義的監聽程序中能夠得到Spring的上下文。
因為,當web.xml中有多個<listener>配置時,排在前面的先啟動
<!-- Spring 框架 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 加載數據字典 在Spring配置的下面--> <listener> <listener-class>msdemo.listener.InitDicListener</listener-class> </listener>
三、數據字典使用
程序中 通過 ServletContext的getAttribute(name) 方法來獲得 字典數據
jsp頁面中 ${name} 來使用。