欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

如何啟動(dòng)Spring項(xiàng)目

這篇文章主要為大家展示了“如何啟動(dòng)Spring項(xiàng)目”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“如何啟動(dòng)Spring項(xiàng)目”這篇文章吧。

成都網(wǎng)站建設(shè)、做網(wǎng)站中從網(wǎng)站色彩、結(jié)構(gòu)布局、欄目設(shè)置、關(guān)鍵詞群組等細(xì)微處著手,突出企業(yè)的產(chǎn)品/服務(wù)/品牌,幫助企業(yè)鎖定精準(zhǔn)用戶,提高在線咨詢和轉(zhuǎn)化,使成都網(wǎng)站營銷成為有效果、有回報(bào)的無錫營銷推廣。創(chuàng)新互聯(lián)公司專業(yè)成都網(wǎng)站建設(shè)10余年了,客戶滿意度97.8%,歡迎成都創(chuàng)新互聯(lián)客戶聯(lián)系。

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

以通用的Tomcat為例

如何啟動(dòng)Spring項(xiàng)目

2、項(xiàng)目容器啟動(dòng)時(shí)需要加載讀取web.xml配置文件

如下圖:

如何啟動(dòng)Spring項(xiàng)目

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

說明:

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

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

4、ContextLoaderListener中的contextInitialized()進(jìn)行了spring容器的啟動(dòng)配置,調(diào)用initWebApplicationContext初始化spring容器;

@Override
public void contextInitialized(ServletContextEvent event) {
  initWebApplicationContext(event.getServletContext());
}
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
  //Spring 啟動(dòng)的句柄,spring容器開始啟動(dòng)的根目錄
  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容器是否已經(jīng)創(chuàng)建(只創(chuàng)建沒有創(chuàng)建spring的各個(gè)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容器的各個(gè)組件
          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)建完成后,準(zhǔn)備開始實(shí)例化加載bean,Spring容器創(chuàng)建完成后,準(zhǔn)備向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();
 }
}

此處略過如何調(diào)用DefaultResourceLoader

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

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

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

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

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

如何啟動(dòng)Spring項(xiàng)目

如何啟動(dòng)Spring項(xiàng)目

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

@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,先用擴(kuò)展協(xié)議解析器解析資源地址并返回。舉個(gè)例子,咱們可以自定義資源解析器來完成帶前綴“classpath:”的解析:

首先實(shí)現(xiàn)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,假設(shè)location以斜杠開頭,則調(diào)用該類中 getResourceByPath(String path)方法 ,代碼如下:

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

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

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

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

以上是“如何啟動(dòng)Spring項(xiàng)目”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

分享文章:如何啟動(dòng)Spring項(xiàng)目
地址分享:http://chinadenli.net/article16/gjeodg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、面包屑導(dǎo)航、網(wǎng)站制作、網(wǎng)站建設(shè)、移動(dòng)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

營銷型網(wǎng)站建設(shè)