Spring獲取ApplicationContext的正確方式
前兩天聯華對單系統頻頻出現out of memory的問題,經過層層分析,終于弄明白原來瓶頸出現在Spring獲取Bean那一步上。以前的做法是在delegate層ApplicationContext context = new ClassPathXmlApplicationContext("Compare.xml"); 這樣我把log4j的debug打開后發現,每做1步操作的時候系統都會重新加載這個xml,重新創建Bean的實例,重新獲取url-mapping,這無疑是個及其錯誤的方式。 研究后發現正確的使用方式是: 首先在web.xml里配置ApplicationContext <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> 然后在Action中編寫如下代碼得到Context,(我是覆蓋了Struts Action的setServlet方法,也許還有更好的方法)。 public void setServlet(ActionServlet servlet){
super.setServlet(servlet);
ServletContext servletContext = servlet.getServletContext();
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
// get yours beans } 這樣在啟動服務時已經加載了xml中的配置,而不用每次都重新加載,大大提高了系統的效率