Java Spring WEB應用例項化如何實現
阿新 • • 發佈:2020-12-04
1.前面講解的都是通過直接讀取配置檔案,進行的例項化ApplicationContext
AbstractApplicationContext app = new ClassPathXmlApplicationContext("beans.xml");
下面講解直接通過配置檔案進行初始化。
2.web.xml
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:beans.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
這樣,ApplicationContext便已經例項化了,預設就直接載入了beans.xml裡面的內容。
來看看底層的程式碼,類ContextLoaderListener中有個初始化方法
public void contextInitialized(ServletContextEvent event) { this.contextLoader = createContextLoader(); if (this.contextLoader == null) { this.contextLoader = this; } this.contextLoader.initWebApplicationContext(event.getServletContext()); }
進入initWebApplicationContext方法 :
ApplicationContext parent = loadParentContext(servletContext); // Store context in local instance variable,to guarantee that // it is available on ServletContext shutdown. this.context = createWebApplicationContext(servletContext,parent);
這句也就是容器載入的結果。
1和2一個是java程式碼一個是xml程式碼,不過實現的效果都是一樣的。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。