主頁 > 後端開發 > spring boot 加載web容器tomcat流程原始碼分析

spring boot 加載web容器tomcat流程原始碼分析

2021-06-20 06:08:34 後端開發

spring boot 加載web容器tomcat流程原始碼分析

我本地的springboot版本是2.5.1,后面的分析都是基于這個版本

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
  

我們通過在pom檔案中引入

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

來引入web容器,默認的web容器時tomcat,

本文章主要描述spring boot加載web容器 tomcat的部分,為了避免文章知識點過于分散,其他相關的如bean的加載,tomcat內部流程等不做深入討論,

1、在springboot web工程中,全域背景關系是AnnotationConfigServletWebApplicationContext

下面的部分,我們具體來看下

首先,我們的入口代碼一般都是這樣寫的

    public static void main(String[] args) {
        SpringApplication.run(BootargsApplication.class,args);
    }

跳轉到run方法里面,依次會呼叫下面兩個方法

	public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
		return run(new Class<?>[] { primarySource }, args);
	}
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
   return new SpringApplication(primarySources).run(args);
}

首先會創建SpringApplication實體物件,跳轉到SpringApplication的構造方法去看看,依次會呼叫如下方法

	public SpringApplication(Class<?>... primarySources) {
		this(null, primarySources);
	}
@SuppressWarnings({ "unchecked", "rawtypes" })
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
   ......
   //本次不相關的代碼全部省略掉,只保留相關代碼
   //這里的 this.webApplicationType=WebApplicationType.SERVLET, 我們來分析下這個代碼的具體的執行賦值
   this.webApplicationType = WebApplicationType.deduceFromClasspath();
   ......
}

繼續跳轉到WebApplicationType.deduceFromClasspath()去看看

	//這個方法主要是在當前類路徑下查找指定的class類是否存在,回傳對飲列舉型別
	static WebApplicationType deduceFromClasspath() {
	// WEBMVC_INDICATOR_CLASS = "org.springframework.web.servlet.DispatcherServlet";
	
	//我們通過pom檔案引入spring-boot-starter-web,會簡介引入spring-webmvc,上面這個類就在這個webmvc中,所以不會進入這個if分支
		if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
				&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
			return WebApplicationType.REACTIVE;
		}
	//SERVLET_INDICATOR_CLASSES = { "javax.servlet.Servlet",
			"org.springframework.web.context.ConfigurableWebApplicationContext" }
	//javax.servlet.Servlet這個類存在于tomcat-embed-core中
    //org.springframework.web.context.ConfigurableWebApplicationContext這個類存在于spring-web中
    //這兩個jar都是由spring-boot-starter-web間接引入的,所以也不會走這個分支
		for (String className : SERVLET_INDICATOR_CLASSES) {
			if (!ClassUtils.isPresent(className, null)) {
				return WebApplicationType.NONE;
			}
		}
		//所以會從這里回傳
		return WebApplicationType.SERVLET;
	}

下面看下jar包的引入

回到new SpringApplication(primarySources).run(args)的呼叫來看run方法的代碼

public ConfigurableApplicationContext run(String... args) {
		.......
		try {
			......
			//我們來看這個context的創建,context=new AnnotationConfigServletWebServerApplicationContext()下面來具體看這塊的執行
			context = createApplicationContext();
		    ......
		    //后續幾個部分會來說明這個方法
			refreshContext(context);
			......
		}
		catch (Throwable ex) {
			......
		}

		try {
		.......
		}
		catch (Throwable ex) {
		.......
		}
		return context;
	}

createApplicationContext()依次會呼叫如下方法

	protected ConfigurableApplicationContext createApplicationContext() {
		//這里的this.webApplicationType就是上面的WebApplicationType.SERVLET
		return this.applicationContextFactory.create(this.webApplicationType);
	}
	//最侄訓呼叫到這個lambda運算式,入參就是上面的WebApplicationType.SERVLET
	ApplicationContextFactory DEFAULT = (webApplicationType) -> {
		try {
			switch (webApplicationType) {
			case SERVLET:
				//會從這里回傳
				return new AnnotationConfigServletWebServerApplicationContext();
			case REACTIVE:
				return new AnnotationConfigReactiveWebServerApplicationContext();
			default:
				return new AnnotationConfigApplicationContext();
			}
		}
		catch (Exception ex) {
			throw new IllegalStateException("Unable create a default ApplicationContext instance, "
					+ "you may need a custom ApplicationContextFactory", ex);
		}
	};

到這里,我們的背景關系context就已經創建出來了,這塊代碼也比較簡單,就不多說什么了

2、查找ServletWebServerFactory

再次回到new SpringApplication(primarySources).run(args)的呼叫來看run方法的代碼

public ConfigurableApplicationContext run(String... args) {
		.......
		try {
			......
			//上面已經對context做過了講解,context=new AnnotationConfigServletWebServerApplicationContext()
			context = createApplicationContext();
		    ......
		    //下面來看這個方法
			refreshContext(context);
			......
		}
		catch (Throwable ex) {
			......
		}

		try {
		.......
		}
		catch (Throwable ex) {
		.......
		}
		return context;
	}

點到refreshContext(context)

	private void refreshContext(ConfigurableApplicationContext context) {
		if (this.registerShutdownHook) {
			shutdownHook.registerApplicationContext(context);
		}
		refresh(context);
	}

繼續點到refresh(context)

	protected void refresh(ConfigurableApplicationContext applicationContext) {
        //這里的applicationContext就是AnnotationConfigServletWebServerApplicationContext的物件,由于這個類沒有refresh方法,會跳轉到它的父類ServletWebServerApplicationContext的方法中去,我們繼續點進去
		applicationContext.refresh();
	}

點到ServletWebServerApplicationContext的refresh方法

	public final void refresh() throws BeansException, IllegalStateException {
		try {
            //繼續跳轉到父類AbstractApplicationContext方法
			super.refresh();
		}
		catch (RuntimeException ex) {
			WebServer webServer = this.webServer;
			if (webServer != null) {
				webServer.stop();
			}
			throw ex;
		}
	}

打開AbstractApplicationContext的refresh方法

//springboot 大部分的初始化作業是在這里完成的,不過這不是我們本地的重點,不相關的我們統統略過
public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			......
			try {
			......
				//繼續點到這個方法,這里又會跳轉到ServletWebServerApplicationContext這個類的方法
				onRefresh();
			.....
			}

			catch (BeansException ex) {
			.....
			}

			finally {
			.....
			}
		}
	}

打開ServletWebServerApplicationContext的onRefresh方法

	protected void onRefresh() {
		super.onRefresh();
		try {
			//這里就是我們本次的重點,會在這里創建具體的web容器,我們點進去看看,還是ServletWebServerApplicationContext這個類的方法
			createWebServer();
		}
		catch (Throwable ex) {
			throw new ApplicationContextException("Unable to start web server", ex);
		}
	}

打開ServletWebServerApplicationContext的createWebServer方法

	private void createWebServer() {
	
		WebServer webServer = this.webServer;
		ServletContext servletContext = getServletContext();
		//第一次進來webServer servletContext都是null,會進到if分支里面
		if (webServer  == null && servletContext == null) {
		   //這里只是做個標記,不用關注,跳過
			StartupStep createWebServer = this.getApplicationStartup().start("spring.boot.webserver.create");
			//這里就會來查找ServletWebServerFactory,也就是web容器的工廠,具體看下getWebServerFactory()方法,還是ServletWebServerApplicationContext這個類的方法
			ServletWebServerFactory factory = getWebServerFactory();
			createWebServer.tag("factory", factory.getClass().toString());
			this.webServer = factory.getWebServer(getSelfInitializer());
			createWebServer.end();
			getBeanFactory().registerSingleton("webServerGracefulShutdown",
					new WebServerGracefulShutdownLifecycle(this.webServer));
			getBeanFactory().registerSingleton("webServerStartStop",
					new WebServerStartStopLifecycle(this, this.webServer));
		}
		else if (servletContext != null) {
			try {
				getSelfInitializer().onStartup(servletContext);
			}
			catch (ServletException ex) {
				throw new ApplicationContextException("Cannot initialize servlet context", ex);
			}
		}
		initPropertySources();
	}

打開ServletWebServerApplicationContext的getWebServerFactory方法

	protected ServletWebServerFactory getWebServerFactory() {
		// Use bean names so that we don't consider the hierarchy
		//從beanFactory中查找ServletWebServerFactory型別的bean的定義,回傳對應bean的名字
		String[] beanNames = getBeanFactory().getBeanNamesForType(ServletWebServerFactory.class);
		if (beanNames.length == 0) {
			throw new ApplicationContextException("Unable to start ServletWebServerApplicationContext due to missing "
					+ "ServletWebServerFactory bean.");
		}
		if (beanNames.length > 1) {
			throw new ApplicationContextException("Unable to start ServletWebServerApplicationContext due to multiple "
					+ "ServletWebServerFactory beans : " + StringUtils.arrayToCommaDelimitedString(beanNames));
		}
        //這里會從beanFactory中回傳bean的名字為beanNames[0],型別為ServletWebServerFactory.class的bean物件,如果當前bean還未創建,則此時就會創建bean物件并回傳	
		return getBeanFactory().getBean(beanNames[0], ServletWebServerFactory.class);
	}

從上面的代碼并看不出來實際的ServletWebServerFactory物件具體是什么?下面帶著大家一起簡單過下這部分的加載,這里具體就是springboot 加載bean的流程了,這部分的邏輯比較多,本次就不具體展開,關于springboot 加載bean的流程計劃后續專門再寫一篇,

springboot在啟動程序中會在當前類路徑下META-INF/spring.factories這個檔案中,key=org.springframework.boot.autoconfigure.EnableAutoConfiguration的屬性的作為bean的定義進行加載,在這程序中還會使用key=org.springframework.boot.autoconfigure.AutoConfigurationImportFilterfilter的屬性作為過濾,配合META-INF/spring-autoconfigure-metadata.properties對這些類做一個過濾,剔除掉不符合的類(后續還會根據類上的注解判斷是否要繼續剔除),

當前這些主要在spring-boot-autoconfigure-2.5.1.jar這個檔案中

下面截取上面說的兩部分,可以看到這里的過濾器就3個,具體不展開討論了,自動匯入的類就是下面的再加過濾去掉的

# Auto Configuration Import Filters
org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
org.springframework.boot.autoconfigure.condition.OnBeanCondition,\
org.springframework.boot.autoconfigure.condition.OnClassCondition,\
org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
......
#下面這個會在創建servelt中使用,下部分我們再關注它
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
#下面這個就是我們需要用到的
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
......
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
......

我們看下上面的org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration這個類,這個類在web 場景下,不會被剔除,會被加載,我們看看這個類,我們只看頭部就可以了

這里我們看到類上有Import注解,會繼續匯入這幾個類,

ServletWebServerFactoryConfiguration.EmbeddedTomcat.class,
ServletWebServerFactoryConfiguration.EmbeddedJetty.class,
ServletWebServerFactoryConfiguration.EmbeddedUndertow.class

這三個都是本次相關的,它們都是ServletWebServerFactoryConfiguration的內部類,我們進去看看,類的結構都是一樣的,我們就看下ServletWebServerFactoryConfiguration.EmbeddedTomcat類吧

可以看到EmbeddedTomcat上面有ConditionalOnClass,ConditionalOnMissingBean這兩個注解,

簡單說下,ConditionalOnClass是表示當前類路徑下存在對應類是加載

ConditionalOnMissingBean是表示當前beanFactory中沒有對應型別bean定義的話加載

多個條件都是and的關系,有一個條件不成立,就不會去進行后續處理,

在這里EmbeddedTomcat類這兩個條件是成立的,這時就會繼續遍歷當前類的所有方法,找到@Bean注解的方法,加載到beanFactory中去

而EmbeddedJetty,EmbeddedUndertow兩個類條件是不成立的,就不會進行后續執行,剔除掉了

這里就會把EmbeddedTomcat.tomcatServletWebServerFactory這個方法進行加載,回傳值是TomcatServletWebServerFactory型別,我們看下TomcatServletWebServerFactory類的繼承圖,可以看到它正好是繼承了ServletWebServerFactory介面,

再次打開ServletWebServerApplicationContext的getWebServerFactory方法

	protected ServletWebServerFactory getWebServerFactory() {
		.......
        //所以這里的邏輯實際上會執行ServletWebServerFactoryConfiguration.EmbeddedTomcat類的tomcatServletWebServerFactory方法,回傳TomcatServletWebServerFactory物件,相關的屬性注入等等這里就不講述了            
		return getBeanFactory().getBean(beanNames[0], ServletWebServerFactory.class);
	}

到這里,整個ServletWebServerFactory的查找就完成了

3、創建DispatcherServletRegistrationBean,DispatcherServlet

再看看上面的META-INF/spring.factories檔案

# Auto Configuration Import Filters
org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
org.springframework.boot.autoconfigure.condition.OnBeanCondition,\
org.springframework.boot.autoconfigure.condition.OnClassCondition,\
org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
......
#現在我們重點來看這個類
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
......
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
......

我們打開org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration這個類看看

@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Configuration(proxyBeanMethods = false)
//我們當前只關注這ConditionalOnWebApplication、ConditionalOnClass注解
//ConditionalOnWebApplication是根據type來判斷指定類是否存在
//當前的type是 Type.SERVLET,是來查找org.springframework.web.context.support.GenericWebApplicationContext類是否存在,這個類存在于spring-web中,所以這個條件是true
@ConditionalOnWebApplication(type = Type.SERVLET)
//這個注解上面說過了 ,就是查找指定的類是否存在,這個是查找DispatcherServlet.class是否存在,這里也會回傳true
@ConditionalOnClass(DispatcherServlet.class)
//上面兩個條件都成立,就會執行后續的操作,去遍歷內部類和方法
@AutoConfigureAfter(ServletWebServerFactoryAutoConfiguration.class)
public class DispatcherServletAutoConfiguration {

	/**
	 * The bean name for a DispatcherServlet that will be mapped to the root URL "/".
	 */
	public static final String DEFAULT_DISPATCHER_SERVLET_BEAN_NAME = "dispatcherServlet";

	/**
	 * The bean name for a ServletRegistrationBean for the DispatcherServlet "/".
	 */
	public static final String DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME = "dispatcherServletRegistration";

	@Configuration(proxyBeanMethods = false)
    //這里還是個條件,通過實作Condition介面,通過matches方法來判斷
    //DefaultDispatcherServletCondition這個類就在當前這個檔案里,matches判斷的結果也是true
	@Conditional(DefaultDispatcherServletCondition.class)
    //ServletRegistration.class這個類存在于tomcat-embed-core里面,這個結果也是true
	@ConditionalOnClass(ServletRegistration.class)
    //上面兩個條件成立,就會執行后續的操作,去遍歷內部類和方法
	@EnableConfigurationProperties(WebMvcProperties.class)
	protected static class DispatcherServletConfiguration {

        //beanFactory會創建這個DispatcherServletbean的定義,bean的名字就是dispatcherServlet
		@Bean(name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
		public DispatcherServlet dispatcherServlet(WebMvcProperties webMvcProperties) {
			DispatcherServlet dispatcherServlet = new DispatcherServlet();
			dispatcherServlet.setDispatchOptionsRequest(webMvcProperties.isDispatchOptionsRequest());
			dispatcherServlet.setDispatchTraceRequest(webMvcProperties.isDispatchTraceRequest());
			dispatcherServlet.setThrowExceptionIfNoHandlerFound(webMvcProperties.isThrowExceptionIfNoHandlerFound());
			dispatcherServlet.setPublishEvents(webMvcProperties.isPublishRequestHandledEvents());
			dispatcherServlet.setEnableLoggingRequestDetails(webMvcProperties.isLogRequestDetails());
			return dispatcherServlet;
		}

		@Bean
		@ConditionalOnBean(MultipartResolver.class)
		@ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
		public MultipartResolver multipartResolver(MultipartResolver resolver) {
			// Detect if the user has created a MultipartResolver but named it incorrectly
			return resolver;
		}

	}

	@Configuration(proxyBeanMethods = false)
    //和上面的一樣,不說了
	@Conditional(DispatcherServletRegistrationCondition.class)
    //和上面的一樣,不說了
	@ConditionalOnClass(ServletRegistration.class)
	@EnableConfigurationProperties(WebMvcProperties.class)
    //這里會要在查找DispatcherServletConfiguration.class,并執行加載bean定義的流程,這就是上面的類了
	@Import(DispatcherServletConfiguration.class)
	protected static class DispatcherServletRegistrationConfiguration {

		@Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)
        //ConditionalOnBean查找是否存在指定bean的定義,這個方法要注入引數,需要這個類,當前這里就是上面的dispatcherServlet方法定義的,這里也是存在的
		@ConditionalOnBean(value = https://www.cnblogs.com/wbo112/p/DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
        //DispatcherServlet dispatcherServlet這個就是dispatcherServlet這個方法定義的bean,在創建DispatcherServletRegistrationBean這個bean的時候,就會去查找dispatcherServlet是否存在,如果不存在,先創建dispatcherServlet這個bean,再創建DispatcherServletRegistrationBean
		public DispatcherServletRegistrationBean dispatcherServletRegistration(DispatcherServlet dispatcherServlet,
				WebMvcProperties webMvcProperties, ObjectProvider multipartConfig) {
			DispatcherServletRegistrationBean registration = new DispatcherServletRegistrationBean(dispatcherServlet,
					webMvcProperties.getServlet().getPath());
			registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
			registration.setLoadOnStartup(webMvcProperties.getServlet().getLoadOnStartup());
			multipartConfig.ifAvailable(registration::setMultipartConfig);
			return registration;
		}

	}
  ......
}
      

上面就是創建DispatcherServlet,DispatcherServletRegistrationBean的程序了

4、創建tomcat,加載Servlet.class,filter.class,監聽器

再次回到ServletWebServerApplicationContext的createWebServer方法

	private void createWebServer() {
		WebServer webServer = this.webServer;
		ServletContext servletContext = getServletContext();
		if (webServer == null && servletContext == null) {
			StartupStep createWebServer = this.getApplicationStartup().start("spring.boot.webserver.create");
			//上面我們已經看到了這里,factory是TomcatServletWebServerFactory類的一個實體物件
			ServletWebServerFactory factory = getWebServerFactory();
            //這里還是做個標記,不用關注
            createWebServer.tag("factory", factory.getClass().toString());
            //這里就是具體創建tomcat了,這里的入參getSelfInitializer()是個lambda運算式,這個后續很重要
			this.webServer = factory.getWebServer(getSelfInitializer());
			createWebServer.end();
			getBeanFactory().registerSingleton("webServerGracefulShutdown",
					new WebServerGracefulShutdownLifecycle(this.webServer));
			getBeanFactory().registerSingleton("webServerStartStop",
					new WebServerStartStopLifecycle(this, this.webServer));
		}
		else if (servletContext != null) {
			try {
				getSelfInitializer().onStartup(servletContext);
			}
			catch (ServletException ex) {
				throw new ApplicationContextException("Cannot initialize servlet context", ex);
			}
		}
		initPropertySources();
	}
	private org.springframework.boot.web.servlet.ServletContextInitializer getSelfInitializer() {
		return this::selfInitialize;
	}
	//是創建webServer的引數
	private void selfInitialize(ServletContext servletContext) throws ServletException {
		prepareWebApplicationContext(servletContext);
		registerApplicationScope(servletContext);
		WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), servletContext);
		for (ServletContextInitializer beans : getServletContextInitializerBeans()) {
			beans.onStartup(servletContext);
		}
	}

factory.getWebServer(getSelfInitializer())會呼叫到TomcatServletWebServerFactory的getWebServer的方法

	public WebServer getWebServer(ServletContextInitializer... initializers) {
        .......
		//上面的入參會在這里傳下去
		prepareContext(tomcat.getHost(), initializers);
		return getTomcatWebServer(tomcat);
	}

點進prepareContext(tomcat.getHost(), initializers)去看看


	protected void prepareContext(Host host, ServletContextInitializer[] initializers) {
		......
		ServletContextInitializer[] initializersToUse = mergeInitializers(initializers);
		host.addChild(context);
		//繼續傳下去
		configureContext(context, initializersToUse);
		postProcessContext(context);
	}

再點到configureContext(context, initializersToUse)這個呼叫去看看

	protected void configureContext(Context context, ServletContextInitializer[] initializers) {
		//會傳遞給TomcatStarter,作為構造引數,下面我們去這里看看
		TomcatStarter starter = new TomcatStarter(initializers);
        ......
    }

下面我們去看看TomcatStarter這個類是怎么使用這個initializers這個構造引數的,

這個類不長
class TomcatStarter implements ServletContainerInitializer {
    ......
	TomcatStarter(ServletContextInitializer[] initializers) {
        //入參會作為它的成員屬性
		this.initializers = initializers;
	}

	@Override
	public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
		try {
			for (ServletContextInitializer initializer : this.initializers) {
                //會在這里呼叫onStartup方法,這里的入參就是ApplicationContextFacade的物件,里面包裝了ApplicationContext,里面再包裝了TomcatEmbeddedContext,這要就和tomcat聯系起來了,下面的截圖就是servletContext的物件結構
				initializer.onStartup(servletContext);
			}
		}
		catch (Exception ex) {
			......
	}

上面的initializer.onStartup(servletContext)會呼叫到ServletWebServerApplicationContext的selfInitialize方法

	private void selfInitialize(ServletContext servletContext) throws ServletException {
        //這里是將ApplicationContextFacade設定到當前的servletContext上
		prepareWebApplicationContext(servletContext);
        //這里是在beanFactory中注冊application的scope
		registerApplicationScope(servletContext);
        //這里還是注冊背景關系相關的bean
		WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), servletContext);
        //我們重點來看這里getServletContextInitializerBeans()是定義個一個ServletContextInitializerBeans物件,我們點進去看看
		for (ServletContextInitializer beans : getServletContextInitializerBeans()) {
			beans.onStartup(servletContext);
		}
	}
	protected Collection<ServletContextInitializer> getServletContextInitializerBeans() {
		//這里的getBeanFactory()就是全域的beanFactory
		return new ServletContextInitializerBeans(getBeanFactory());
	}

	public ServletContextInitializerBeans(ListableBeanFactory beanFactory,
			Class<? extends ServletContextInitializer>... initializerTypes) {
		this.initializers = new LinkedMultiValueMap<>();
        //由于我們沒有傳initializerTypes這個引數,所以this.initializerTypes里面就只有ServletContextInitializer.class這個類
		this.initializerTypes = (initializerTypes.length != 0) ? Arrays.asList(initializerTypes)
				: Collections.singletonList(ServletContextInitializer.class);
        //這里主要是從beanFactory中查找this.initializerTypes型別,我們進去看看,就是下面這個方法了
		addServletContextInitializerBeans(beanFactory);
		addAdaptableBeans(beanFactory);
		List<ServletContextInitializer> sortedInitializers = this.initializers.values().stream()
				.flatMap((value) -> value.stream().sorted(AnnotationAwareOrderComparator.INSTANCE))
				.collect(Collectors.toList());
		this.sortedList = Collections.unmodifiableList(sortedInitializers);
		logMappings(this.initializers);
	}

	private void addServletContextInitializerBeans(ListableBeanFactory beanFactory) {
		for (Class<? extends ServletContextInitializer> initializerType : this.initializerTypes) {
            //默認情況下這里找到就只有上面第3部分的DispatcherServletRegistrationBean對應的bean
			for (Entry<String, ? extends ServletContextInitializer> initializerBean : getOrderedBeansOfType(beanFactory,
					initializerType)) {
                //這里的key是bean的名字,value就是bean物件,在進去看看,就是下面這個方法
				addServletContextInitializerBean(initializerBean.getKey(), initializerBean.getValue(), beanFactory);
			}
		}
	}
	private void addServletContextInitializerBean(String beanName, ServletContextInitializer initializer,
			ListableBeanFactory beanFactory) {
        //會走到這個分支
		if (initializer instanceof ServletRegistrationBean) {
            //這里回傳的servlet也還是第3部分DispatcherServlet對應的bean
			Servlet source = ((ServletRegistrationBean<?>) initializer).getServlet();
            //再點進去
			addServletContextInitializerBean(Servlet.class, beanName, initializer, beanFactory, source);
		}
		else if (initializer instanceof FilterRegistrationBean) {
			Filter source = ((FilterRegistrationBean<?>) initializer).getFilter();
			addServletContextInitializerBean(Filter.class, beanName, initializer, beanFactory, source);
		}
		else if (initializer instanceof DelegatingFilterProxyRegistrationBean) {
			String source = ((DelegatingFilterProxyRegistrationBean) initializer).getTargetBeanName();
			addServletContextInitializerBean(Filter.class, beanName, initializer, beanFactory, source);
		}
		else if (initializer instanceof ServletListenerRegistrationBean) {
			EventListener source = ((ServletListenerRegistrationBean<?>) initializer).getListener();
			addServletContextInitializerBean(EventListener.class, beanName, initializer, beanFactory, source);
		}
		else {
			addServletContextInitializerBean(ServletContextInitializer.class, beanName, initializer, beanFactory,
					initializer);
		}
	}

	private void addServletContextInitializerBean(Class<?> type, String beanName, ServletContextInitializer initializer,
			ListableBeanFactory beanFactory, Object source) {
        //這里的initializers是個map,按照型別,bean物件進行加載,這里的type是javax.servlet.Servlet.class,value是上面的DispatcherServletRegistrationBean
		this.initializers.add(type, initializer);
		if (source != null) {
			// Mark the underlying source as seen in case it wraps an existing bean
            //將DispatcherServlet對應的bean加到這里
			this.seen.add(source);
		}
		if (logger.isTraceEnabled()) {
			String resourceDescription = getResourceDescription(beanName, beanFactory);
			int order = getOrder(initializer);
			logger.trace("Added existing " + type.getSimpleName() + " initializer bean '" + beanName + "'; order="
					+ order + ", resource=" + resourceDescription);
		}
	}

再回到ServletContextInitializerBeans的構造方法,接著看后面的

	public ServletContextInitializerBeans(ListableBeanFactory beanFactory,
			Class<? extends ServletContextInitializer>... initializerTypes) {
		...... //這里的內容上面已經看過了,我們現在看下面這句,點進去
		addAdaptableBeans(beanFactory);
		List<ServletContextInitializer> sortedInitializers = this.initializers.values().stream()
				.flatMap((value) -> value.stream().sorted(AnnotationAwareOrderComparator.INSTANCE))
				.collect(Collectors.toList());
		this.sortedList = Collections.unmodifiableList(sortedInitializers);
		logMappings(this.initializers);
	}

	protected void addAdaptableBeans(ListableBeanFactory beanFactory) {
		//這句不用關注
		MultipartConfigElement multipartConfig = getMultipartConfig(beanFactory);
		//這句不用關注
		addAsRegistrationBean(beanFactory, Servlet.class, new ServletRegistrationBeanAdapter(multipartConfig));
		//點到這里去看看
		addAsRegistrationBean(beanFactory, Filter.class, new FilterRegistrationBeanAdapter());
        
		for (Class<?> listenerType : ServletListenerRegistrationBean.getSupportedTypes()) {
			addAsRegistrationBean(beanFactory, EventListener.class, (Class<EventListener>) listenerType,
					new ServletListenerRegistrationBeanAdapter());
		}
	}

	
	private <T, B extends T> void addAsRegistrationBean(ListableBeanFactory beanFactory, Class<T> type,
			Class<B> beanType, RegistrationBeanAdapter<T> adapter) {
		//這里的beanType是 Filter.class,下面這句就是從beanFactory中獲取所有型別為Filter.class的bean
		List<Map.Entry<String, B>> entries = getOrderedBeansOfType(beanFactory, beanType, this.seen);
		for (Entry<String, B> entry : entries) {
			String beanName = entry.getKey();
			B bean = entry.getValue();
            //將bean放置到this.seen里面
			if (this.seen.add(bean)) {
				// One that we haven't already seen
                //包裝成RegistrationBean物件
				RegistrationBean registration = adapter.createRegistrationBean(beanName, bean, entries.size());
				int order = getOrder(bean);
				registration.setOrder(order);
                //同樣放置到this.initializers里面
				this.initializers.add(type, registration);
				if (logger.isTraceEnabled()) {
					logger.trace("Created " + type.getSimpleName() + " initializer for bean '" + beanName + "'; order="
							+ order + ", resource=" + getResourceDescription(beanName, beanFactory));
				}
			}
		}
	}

再回到上面的addAdaptableBeans方法,看后面的


	protected void addAdaptableBeans(ListableBeanFactory beanFactory) {
		......//這里剛才說過了
         //下面這部分不說了,這里基本和上面一樣,不過處理的型別變成了ServletContextAttributeListener.class、ServletRequestListener.class、ServletRequestAttributeListener.class、HttpSessionAttributeListener.class、HttpSessionIdListener.class、HttpSessionListener.class、ServletContextListener.class這些型別
		for (Class<?> listenerType : ServletListenerRegistrationBean.getSupportedTypes()) {
			addAsRegistrationBean(beanFactory, EventListener.class, (Class<EventListener>) listenerType,
					new ServletListenerRegistrationBeanAdapter());
		}
	}

再回到ServletContextInitializerBeans的構造方法,接著看后面的

	public ServletContextInitializerBeans(ListableBeanFactory beanFactory,
			Class<? extends ServletContextInitializer>... initializerTypes) {
		......//這里剛才都說過了,看下面
        //這里就是把上面所有獲取到的相關的bean放置到this.sortedList中,下面我是我本地this.sortedList的截圖
		List<ServletContextInitializer> sortedInitializers = this.initializers.values().stream()
				.flatMap((value) -> value.stream().sorted(AnnotationAwareOrderComparator.INSTANCE))
				.collect(Collectors.toList());
		this.sortedList = Collections.unmodifiableList(sortedInitializers);
		logMappings(this.initializers);
	}

這里ServletContextInitializerBeans的構造方法就完成了,再回過頭去看看這個類的定義

public class ServletContextInitializerBeans extends AbstractCollection<ServletContextInitializer>

這個類繼承了AbstractCollection類,那它就需要實作下面這個抽象方法

public abstract Iterator<E> iterator();

我們看看ServletContextInitializerBeans的iterator的方法

@Override
public Iterator<ServletContextInitializer> iterator() {
   return this.sortedList.iterator();
}

看到了吧,這就是回傳上面的this.sortedList.iterator()

我們再次回到ServletWebServerApplicationContext的selfInitialize方法

private void selfInitialize(ServletContext servletContext) throws ServletException {
	......//這里上面都說過了
	//getServletContextInitializerBeans()這個方法就是構造了ServletContextInitializerBeans
	//這里的for回圈也是呼叫了ServletContextInitializerBeans的iterator的方法,實際上遍歷的也就是上面的this.sortedList
	for (ServletContextInitializer beans : getServletContextInitializerBeans()) {
		//這里就是把在beanFactory中查找到的Servlet.class,filter.class,監聽器等等添加到tomcat容器中,我們就只進到servlet里面去看看
		//進到DispatcherServletRegistrationBean里面去看看
		beans.onStartup(servletContext);
	}
}
	//這個方法在DispatcherServletRegistrationBean的父類RegistrationBean中
	//所有的Servlet.class,filter.class,監聽器都會走到這里
	public final void onStartup(ServletContext servletContext) throws ServletException {
		//這里是回傳的表述,不關注
		String description = getDescription();
		if (!isEnabled()) {
			logger.info(StringUtils.capitalize(description) + " was not registered (disabled)");
			return;
		}
		//這里由不同的子類去實作,DispatcherServletRegistrationBean會呼叫到ServletRegistrationBean中
		register(description, servletContext);
	}
	//這個方法是在ServletRegistrationBean這個類中
	@Override
	protected ServletRegistration.Dynamic addRegistration(String description, ServletContext servletContext) {
		String name = getServletName();
		//這里的servletContext上面的ApplicationContextFacade的物件,這里就會將DispatcherServlet的bean物件加載到TomcatEmbeddedContext中,后續所有的http請求最后都會流轉到DispatcherServlet去進行具體的分發
		return servletContext.addServlet(name, this.servlet);
	}

到這里Servlet.class,filter.class,監聽器就全部加載到tomcat中去

5、創建RequestMappingHandlerMapping

再看看上面的META-INF/spring.factories檔案

# Auto Configuration Import Filters
org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
org.springframework.boot.autoconfigure.condition.OnBeanCondition,\
org.springframework.boot.autoconfigure.condition.OnClassCondition,\
org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
......
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
......
#現在我們重點來看這個類
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
......

具體的加載和上面部分都類似,就不展開了,直接看我們需要的

		//這里會創建RequestMappingHandlerMapping的bean
		@Bean
		@Primary
		@Override
		public RequestMappingHandlerMapping requestMappingHandlerMapping(
				@Qualifier("mvcContentNegotiationManager") ContentNegotiationManager contentNegotiationManager,
				@Qualifier("mvcConversionService") FormattingConversionService conversionService,
				@Qualifier("mvcResourceUrlProvider") ResourceUrlProvider resourceUrlProvider) {
			// Must be @Primary for MvcUriComponentsBuilder to work
			return super.requestMappingHandlerMapping(contentNegotiationManager, conversionService,
					resourceUrlProvider);

看下這個類的繼承圖

RequestMappingHandlerMapping實作了InitializingBean介面,會在bean物件創建后的invokeInitMethods方法中呼叫afterPropertiesSet方法,最侄訓呼叫的AbstractHandlerMethodMapping的afterPropertiesSet方法中

	@Override
	public void afterPropertiesSet() {
		initHandlerMethods();
	}

	/**
	 * Scan beans in the ApplicationContext, detect and register handler methods.
	 * @see #getCandidateBeanNames()
	 * @see #processCandidateBean
	 * @see #handlerMethodsInitialized
	 */
	protected void initHandlerMethods() {
        //這里查找beanFactory中的所有bean進行遍歷
		for (String beanName : getCandidateBeanNames()) {
			if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
                //點到這里去看看
				processCandidateBean(beanName);
			}
		}
		handlerMethodsInitialized(getHandlerMethods());
	}
	protected void processCandidateBean(String beanName) {
		Class<?> beanType = null;
		try {
			//根據beanName獲取對應bean的Class物件
			beanType = obtainApplicationContext().getType(beanName);
		}
		catch (Throwable ex) {
			// An unresolvable bean type, probably from a lazy bean - let's ignore it.
			if (logger.isTraceEnabled()) {
				logger.trace("Could not resolve type for bean '" + beanName + "'", ex);
			}
		}
		//判斷類上是否有Controller.class,RequestMapping.class注解
		if (beanType != null && isHandler(beanType)) {
			//這里就會決議beanName上的所有方法進行遍歷,查找有 RequestMapping.class注解的方法,創建RequestMappingInfo物件,放置到registry屬性中(在AbstractHandlerMethodMapping)中,這樣我們所有定義的controller中的http請求就會全部被掃描到
			detectHandlerMethods(beanName);
		}
	}

6、加載RequestMappingHandlerMapping到DispatcherServlet中

在我們第一次請求的時候,會執行到DispatcherServlet的initStrategies方法,這個方法只會執行一次

	protected void initStrategies(ApplicationContext context) {
		......
		這就會加載之前查找到的RequestMappingHandlerMapping中的我們定義的controller
		initHandlerMappings(context);
		......
	}

會呼叫到這里

	private void initHandlerMappings(ApplicationContext context) {
		this.handlerMappings = null;

		if (this.detectAllHandlerMappings) {
			// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
			//這里會在beanFactory中查找所有HandlerMapping.class的bean,其中就包含我們第5部分的RequestMappingHandlerMapping
			Map<String, HandlerMapping> matchingBeans =
					BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
			if (!matchingBeans.isEmpty()) {
			//將所有查找到的放置到handlerMappings中
				this.handlerMappings = new ArrayList<>(matchingBeans.values());
				// We keep HandlerMappings in sorted order.
				AnnotationAwareOrderComparator.sort(this.handlerMappings);
			}
		}
		......
	}

當我們瀏覽器請求的時候,最侄訓走到DispatcherServlet的doDispatch的方法,處理我們的請求并回傳,簡單看看

	protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
		......

		try {
			ModelAndView mv = null;
			Exception dispatchException = null;

			try {
				processedRequest = checkMultipart(request);
				multipartRequestParsed = (processedRequest != request);

				// Determine handler for the current request.
                //在這里,就會請求request的請求路徑去查找實際要執行的controller的方法,點進去看看
				mappedHandler = getHandler(processedRequest);
				......
	}

	@Nullable
	protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
		if (this.handlerMappings != null) {
            //這其實就是根據遍歷,查找對應的路徑,這個this.handlerMappings就是就是在initHandlerMappings方法中賦值的
			for (HandlerMapping mapping : this.handlerMappings) {
				HandlerExecutionChain handler = mapping.getHandler(request);
				if (handler != null) {
					return handler;
				}
			}
		}
		return null;
	}

到這里,springboot 加載web容器的整個流程基本就算完成了,這塊涉及的東西比較多,所以說的可能比較粗,大家見諒,

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/288116.html

標籤:Java

上一篇:基于 Spring Security 的前后端分離的權限控制系統

下一篇:Java面試題(七):介面和抽象類的區別

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more