最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

啟動Spring項目詳細過程(小結)

 更新時間:2019年11月08日 09:48:01   作者:君寞傲  
這篇文章主要介紹了啟動Spring項目詳細過程(小結),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

1、Spring 項目放到web項目容器中(Tomcat、Jetty、JBoss)

本文以通用的Tomcat為例

2、項目容器啟動時需要加載讀取web.xml配置文件

如下圖:

3、容器首先會去讀取web.xml配置文件中的兩個節(jié)點:<listener> </listener>和<context-param> </context-param>

說明:

tomcat在啟動web容器的時候會啟動一個叫ServletContextListener的監(jiān)聽器,每當在web容器中有ServletContextListener這個接口被實例化的時候,web容器會通知ServletContextListener被實例的對象去執(zhí)行其contextInitialized()的方法進行相應的業(yè)務處理;

而spring框架在設計的過程中ContextLoadListener這個類實現了ServletContextListener這個接口,因此每當有ContextLoadListener這個類被實例化的時候,web容器會通知Spring執(zhí)行contextInitialized()這個方法,從而進行spring容器的啟動與創(chuàng)建的過程中;

4、ContextLoaderListener中的contextInitialized()進行了spring容器的啟動配置,調用initWebApplicationContext初始化spring容器;

@Override
public void contextInitialized(ServletContextEvent event) {
  initWebApplicationContext(event.getServletContext());
}
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
  //Spring 啟動的句柄,spring容器開始啟動的根目錄
  if(servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
    throw new IllegalStateException("Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!");
  } else {
    Log logger = LogFactory.getLog(ContextLoader.class);
    servletContext.log("Initializing Spring root WebApplicationContext");
    if(logger.isInfoEnabled()) {
      logger.info("Root WebApplicationContext: initialization started");
    }
 
    long startTime = System.currentTimeMillis();
 
    try {
      //處理spring容器是否已經創(chuàng)建(只創(chuàng)建沒有創(chuàng)建spring的各個bean)
      if(this.context == null) {
        this.context = this.createWebApplicationContext(servletContext);
      }
 
      if(this.context instanceof ConfigurableWebApplicationContext) {
        ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext)this.context;
        if(!cwac.isActive()) {
          if(cwac.getParent() == null) {
            ApplicationContext parent = this.loadParentContext(servletContext);
            cwac.setParent(parent);
          }
 
          //Spring容器創(chuàng)建完成后,加載spring容器的各個組件
          this.configureAndRefreshWebApplicationContext(cwac, servletContext);
        }
      }
 
      servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
      ClassLoader ccl = Thread.currentThread().getContextClassLoader();
      if(ccl == ContextLoader.class.getClassLoader()) {
        currentContext = this.context;
      } else if(ccl != null) {
        currentContextPerThread.put(ccl, this.context);
      }
 
      if(logger.isDebugEnabled()) {
        logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
      }
 
      if(logger.isInfoEnabled()) {
        long elapsedTime = System.currentTimeMillis() - startTime;
        logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
      }
 
      return this.context;
    } catch (RuntimeException var8) {
      logger.error("Context initialization failed", var8);
      servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, var8);
      throw var8;
    } catch (Error var9) {
      logger.error("Context initialization failed", var9);
      servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, var9);
      throw var9;
    }
  }
}

5、spring容器創(chuàng)建完成后,準備開始實例化加載bean,Spring容器創(chuàng)建完成后,準備向spring容器中加載bean 使用configureAndRefreshWebApplicationContext(cwac, servletContext); 完成bean的加載;

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
		if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
			// The application context id is still set to its original default value
			// -> assign a more useful id based on available information
			String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
			if (idParam != null) {
				wac.setId(idParam);
			}
			else {
				// Generate default id...
				wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
						ObjectUtils.getDisplayString(sc.getContextPath()));
			}
		}
 
		wac.setServletContext(sc);
		String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
		if (configLocationParam != null) {
			wac.setConfigLocation(configLocationParam);
		}
 
		// The wac environment's #initPropertySources will be called in any case when the context
		// is refreshed; do it eagerly here to ensure servlet property sources are in place for
		// use in any post-processing or initialization that occurs below prior to #refresh
		ConfigurableEnvironment env = wac.getEnvironment();
		if (env instanceof ConfigurableWebEnvironment) {
			((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
		}
 
		customizeContext(sc, wac);
		wac.refresh();
	}

說明:

configureAndRefreshWebApplicationContext中加載spring的配置文件,即web.xml中讀取<context-param></context-param>中加載到Spring的配置文件,即:classpath:/config/applicationContext.xml;

通過以下代碼加載spring配置

public class Application{
 public static void main(String[] args) {
  ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/context.xml");
  ctx.start();
 }
}

此處略過如何調用DefaultResourceLoader

頂級接口ResourceLoader僅提供了一個getResource(String location)方法,可以根據一個資源地址加載資源文件,資源地址的表達式可以是以下幾種:

--1. classpath:前綴開頭的表達式,例如: classpath:smart-context.xml

--2.“/”開頭的表達式,例如:/WEB-INF/classes/smart-context.xml

--3. 非“/”開頭的表達,例如:WEB-INF/classes/smart-context.xml

--4. url協(xié)議,例如:file:/D:/ALANWANG-AIA/Horse-workspace/chapter3/target/classes/smart-context.xml

Spring提供了實現類DefaultResourceLoader,DefaultResourceLoader在實現了以上列舉的功能基礎上,還為開發(fā)者提供了自定義擴展接口ProtocolResolver,開發(fā)者可實現該接口定制個性化資源表達式,代碼如下:

@Override
	public Resource getResource(String location) {
		Assert.notNull(location, "Location must not be null");
		for (ProtocolResolver protocolResolver : this.protocolResolvers) {    // 1
			Resource resource = protocolResolver.resolve(location, this);
			if (resource != null) {return resource;}
		}
 
		if (location.startsWith("/")) {return getResourceByPath(location);}    //2
		else if (location.startsWith(CLASSPATH_URL_PREFIX)) {           //3
			return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
		}
		else {
			try {
				// Try to parse the location as a URL...
				URL url = new URL(location);               //4
				return new UrlResource(url);
			}
			catch (MalformedURLException ex) {
				// No URL -> resolve as resource path.
				return getResourceByPath(location);           //5
			}
		}
	}

步驟1,先用擴展協(xié)議解析器解析資源地址并返回。舉個例子,咱們可以自定義資源解析器來完成帶前綴“classpath:”的解析:

首先實現ProtocolResolver接口:

class ClasspathPreProtocolResolver implements ProtocolResolver{
           private static String CLASS_PATH_PRE="classpath:";        
        public Resource resolve(String location, ResourceLoader resourceLoader) {
           if( location.startsWith(CLASS_PATH_PRE)) {
                return new ClassPathResource(location.substring(CLASS_PATH_PRE.length()));
           }       
           return null;
        }        
    }

步驟2,假設location以斜杠開頭,則調用該類中 getResourceByPath(String path)方法 ,代碼如下:

protected Resource getResourceByPath(String path) {
		return new ClassPathContextResource(path, getClassLoader());
	}

步驟三,假如資源表達式以classpath開頭,則截取除前綴calsspath:的路徑,并做為ClassPathResource的構造參數,生成ClassPathResource實例后返回。咱們可以在web.xml中做如下配置:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/config/applicationContext.xml</param-value>
</context-param>

6、通過refresh()內部的實現我們大致可以了解整個refresh()方法擔負了整個Spring容器初始化和加載的所有邏輯,包括Bean工廠的初始化、post-processor的注冊以及調用、bean的實例化、事件發(fā)布等。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • java連接mysql數據庫詳細步驟解析

    java連接mysql數據庫詳細步驟解析

    以下是對java連接mysql數據庫的具體詳細步驟進行了分析介紹,需要的朋友可以過來參考下
    2013-08-08
  • Spring零基礎到進階之使用方法詳解

    Spring零基礎到進階之使用方法詳解

    Spring框架是一個開放源代碼的J2EE應用程序框架,由Rod?Johnson發(fā)起,是針對bean的生命周期進行管理的輕量級容器(lightweight?container)。?Spring解決了開發(fā)者在J2EE開發(fā)中遇到的許多常見的問題,提供了功能強大IOC、AOP及Web?MVC等功能
    2022-07-07
  • Java如何通過反射取實體類字段取值

    Java如何通過反射取實體類字段取值

    這篇文章主要介紹了Java如何通過反射取實體類字段取值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-07-07
  • flutter?TabBarView?動態(tài)添加刪除頁面的示例代碼

    flutter?TabBarView?動態(tài)添加刪除頁面的示例代碼

    在Flutter中使用TabBarView動態(tài)添加和刪除頁面時,如果未為每個頁面設置唯一的key,會導致刪除頁面時出現狀態(tài)錯誤或刪除錯誤的頁面,正確的做法是為每個頁面指定全局唯一的key,這樣可以確保頁面在添加和刪除時狀態(tài)正確,感興趣的朋友跟隨小編一起看看吧
    2024-11-11
  • spring源碼下載、編譯、debug的詳細教程

    spring源碼下載、編譯、debug的詳細教程

    這篇文章主要介紹了spring源碼下載、編譯、debug的詳細教程,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-10-10
  • Java中excel表數據的批量導入方法

    Java中excel表數據的批量導入方法

    這篇文章主要為大家詳細介紹了Java中excel表數據的批量導入方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-05-05
  • Java之MyBatis入門詳解

    Java之MyBatis入門詳解

    這篇文章主要介紹了Java之MyBatis入門詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • 詳解Java注解實現自己的ORM

    詳解Java注解實現自己的ORM

    這篇文章主要介紹了Java注解實現自己的ORM知識,本文通過示例代碼給大家講解的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2022-10-10
  • Mybatis基于注解形式的sql語句生成實例代碼

    Mybatis基于注解形式的sql語句生成實例代碼

    這篇文章主要介紹了 Mybatis基于注解形式的sql語句生成實例代碼,需要的朋友可以參考下
    2017-09-09
  • SVN導入maven項目報錯解決方案

    SVN導入maven項目報錯解決方案

    這篇文章主要介紹了SVN導入maven項目報錯解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-12-12

最新評論

滨州市| 禄丰县| 大悟县| 会泽县| 隆化县| 青海省| 承德市| 泾川县| 龙陵县| 且末县| 黄陵县| 商水县| 肃宁县| 沙坪坝区| 赫章县| 龙泉市| 大石桥市| 琼中| 南华县| 江阴市| 大同县| 绵阳市| 杭锦旗| 保康县| 克拉玛依市| 太湖县| 阿克陶县| 南宁市| 张掖市| 来凤县| 武威市| 海城市| 肇庆市| 高台县| 张家口市| 奉新县| 田林县| 武威市| 奎屯市| 五峰| 龙口市|