系統載入時執行的類,也是我們將需要載入的參數配置的地方 。必須實現 ServletContextListener
package com.chain.store.mutual;</p><p>import javax.servlet.ServletContext;<br />import javax.servlet.ServletContextEvent;<br />import javax.servlet.ServletContextListener;</p><p>import org.springframework.context.ApplicationContext;<br />import org.springframework.web.context.WebApplicationContext;<br />import org.springframework.web.context.support.WebApplicationContextUtils;</p><p>import com.chain.store.bean.SystemParamBean;<br />import com.chain.store.service.impl.SystemParamServicesImpl;</p><p>public class LoadConfiguration implements ServletContextListener {<br />private static final long serialVersionUID = 1L;<br />//private SystemParamServicesImpl sysParamService;<br />private static WebApplicationContext springContext;<br />private SystemParamBean sysBean ;<br />private ServletContext context;</p><p>public LoadConfiguration(){<br />super();<br />}</p><p>public void contextDestroyed(ServletContextEvent sce) {<br />System.out.println("系統停止......");</p><p>}</p><p>@SuppressWarnings("unchecked")<br />public void contextInitialized(ServletContextEvent sce) {<br />// TODO Auto-generated method stub<br />System.out.println("系統啟動載入......");</p><p>springContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());<br />SystemParamServicesImpl sysServices = (SystemParamServicesImpl)springContext.getBean("sysParamService");<br />sysBean = sysServices.listAllParams();</p><p>context = sce.getServletContext();</p><p>context.setAttribute("sysParams", sysBean);<br />}</p><p> public static ApplicationContext getApplicationContext() {<br /> return springContext;<br /> } </p><p>}<br />
說明 :
SystemParamBean 放置我需要載入的系統參數
sysParamService 是我在 applicationContext.xml 中配置的從資料庫中得到參數值的bean
當然不要忘記在 web.xml 中添加
<listener><br /> <listener-class><br /> com.chain.store.mutual.LoadConfiguration<br /> </listener-class><br /> </listener>
在Action 中得到系統參數:
ServletContext context = ServletActionContext.getServletContext();<br />SystemParamBean sysBean = (SystemParamBean)context.getAttribute("sysParams");</p><p>System.out.println("----------系統參數----------");<br />System.out.println("NEWS_SHOWIMG " + sysBean.getNEWS_SHOWIMG());<br />System.out.println("---------------------------");
參考文章 :
http://hi.baidu.com/29163077/blog/item/b3b77bdd5c1a94ea76c638f7.html
http://lichengyezi.javaeye.com/blog/508128