Java Spring WEB應用實例化如何實現
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代碼,不過實現的效果都是一樣的。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
