一、概述
ContextLoaderListener(以下簡稱CLL)是一個在web.xml中定義的監聽器,用於在應用啟動時加載Spring上下文。當web應用程序啟動時,ServletContext監聽器會接收到ServletContext初始化事件,該監聽器是Servlet環境中的一個標準類,用於在Web應用程序的生命周期中加載Spring ApplicationContext。在Servlet容器啟動時,Servlet容器會加載web.xml文件,其中包含註冊的ServletContext監聽器,此時會自動實例化CLL並運行其contextInitialized()方法。
二、使用
開發人員只需要在web.xml文件中配置CLL即可。在web.xml文件中,CLL應在其他Servlet之前配置。同樣,可以配置多個CLL,它們可以加載不同的ApplicationContext文件。例如:
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/applicationContext.xml</param-value> </context-param>
其中,listener-class為CLL的全限定名,contextConfigLocation參數告訴Spring要去哪裡加載Application Context文件。這裡演示的例子中,是從classpath路徑下加載文件。
三、繼承
對於需要自定義ApplicationContext的項目,可以繼承CLL並覆寫其中的contextInitialized方法。例如:
public class CustomContextLoaderListener extends ContextLoaderListener { protected void customizeContext(ServletContext servletContext, ConfigurableWebApplicationContext applicationContext) { // 執行自定義的操作 } @Override public void contextInitialized(ServletContextEvent event) { super.contextInitialized(event); customizeContext(event.getServletContext(), (ConfigurableWebApplicationContext) event.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)); } }
通過繼承CLL,可以在ApplicationContext加載之前或之後執行一些自定義的操作。在customizeContext方法中,可以添加或修改ApplicationContext中的Bean。
四、上下文環境
使用CLL可以預加載ApplicationContext,使其在請求到達Servlet或Filter時可用,以避免延遲加載。ApplicationContext預加載也可提高web應用程序的性能。CLL在ServletContext初始化後加載ApplicationContext,並將其設置為ServletContext屬性。在使用ApplicationContext時,可以使用ServletContext中的屬性獲取ApplicationContext。例如:
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext); MyBean myBean = wac.getBean(MyBean.class);
在該示例中,WebApplicationContextUtils是Spring提供的一個輔助類,用於獲取WebApplicationContext。可以通過WebApplicationContextUtils獲取ServletContext中存儲的ApplicationContext,並從中獲取Bean。
五、優化
使用CLL並不是完美的解決方案。對於大型應用程序,ApplicationContext可以相當複雜,且包含大量Bean。如果所有的Bean都是在應用程序啟動時加載,將會消耗大量的內存。為此,應該使用懶加載機制避免在加載Application Context時加載所有Bean。例如:
<bean id="myBean" class="com.example.MyBean" lazy-init="true" />
lazy-init=”true”將Bean設置為懶加載,只有當被引用時才會實例化。在應用程序啟動時,只有核心Bean會被加載,而其他Bean將在需要時才會加載。
六、總結
ContextLoaderListener是一個非常有用的類,它使Spring ApplicationContext在web應用程序啟動時預加載。通過定製自己的實現,可以擴展CLL的功能。使用懶加載機制可以避免在啟動時加載所有Bean,提高了性能。雖然ContextLoaderListener在大多數情況下都是非常有用的,但是需要注意不要濫用它。
原創文章,作者:NPASN,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/351591.html