飙血推荐
  • HTML教程
  • MySQL教程
  • JavaScript基础教程
  • php入门教程
  • JavaScript正则表达式运用
  • Excel函数教程
  • UEditor使用文档
  • AngularJS教程
  • ThinkPHP5.0教程

走进Spring Boot源码学习之路和浅谈入门

时间:2021-12-10  作者:itxiaoshen  
走进Spring Boot源码学习之路和浅谈入门 作为笔者见解,Spring Boot 不算是一个全新的框架,Spring Boot 底层还是大量依赖于Spring Framework,而Spring Framework很早以前版本就已提供基于注解、Java Config而不仅是XML配置编程;Spring Boot采用约定大于配置方式替代xml配置,是Spring Framework一个大升级版本,整合很多自动装配组件,让开发者开箱即用,接下来我们一起来学习下Spring Boot三个重要的特性和大名鼎鼎开箱即用starter开发简易剖析。

Spring Boot浅聊入门

**本人博客网站 **IT小神 域名

Spring Boot官网地址:https://域名/projects/spring-boot/

Spring Boot可以轻松创建独立的、基于Spring的产品级应用程序“直接运行”。

作为笔者见解,Spring Boot 不算是一个全新的框架,Spring Boot 底层还是大量依赖于Spring Framework,而Spring Framework很早以前版本就已提供基于注解、Java Config而不仅是XML配置编程;Spring Boot采用约定大于配置方式替代xml配置,是Spring Framework一个大升级版本,整合很多自动装配组件,让开发者开箱即用,接下来我们一起来聊聊Spring Boot三个重要的特性和starter开发简易剖析

Spring Boot源码编译

使用最新Releases版本v2.5.3

image-20210811090719315

目前Spring boot和Spring Framework项目都是使用Gradle自动化构建工具,编译直接查看项目根目录下域名文件即可,有时网络不好可以多次编译重试

image-20210811090507786

零配置

Spring Web MVC简述

Spring Web Mvc官网地址 https://域名/spring-framework/docs/current/reference/html/域名

Spring Web MVC是基于Servlet API的原始Web框架,从一开始就包含在Spring框架中。“Spring Web MVC”的正式名称来自其源模块的名称(Spring -webmvc),但它通常被称为“Spring MVC”

零配置实现

Spring Web MVC官网开篇最前面第一章第一小节也即是1.1 DispatcherServlet中就重点引用一下这六句代码实现原来我们Spring MVC 工程域名里面配置功能,仅通过下面这一小段代码就初始化了Spring根容器和Web子容器,这种方式也是官方推荐使用的

public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) {

        // Load Spring web application configuration
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        域名ster(域名s);

        // Create and register the DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(context);
        域名mic registration = 域名ervlet("app", servlet);
        域名oadOnStartup(1);
        域名apping("/app/*");
    }
}

而我们非常熟悉的Spring Web Mvc工程域名配置示例注册和初始化DispatcherServlet:

<web-app>

    <listener>
        <listener-class>域名.域名extLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app-域名</param-value>
    </context-param>

    <servlet>
        <servlet-name>app</servlet-name>
        <servlet-class>域名.域名atcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>app</servlet-name>
        <url-pattern>/app/*</url-pattern>
    </servlet-mapping>

</web-app>

父子容器

个人猜测Spring Boot基于内嵌容器特性会渐渐淡化父子容器的概念,最终只是一个大容器

image-20210810174536660

内嵌容器

概述

Spring Boot 内嵌像Tomcat、Jetty、Undertow等实现Servlet规范的容器,如果有研究过Tomcat这只三脚猫logo中间件(后续有时间我们再分享一下Tomcat源码和原理)也知道Tomcat也是一个用Java语言编写的强大中间件,在Spring Boot通过New Tomcat方式来配置和启动web容器。

Spring Framework源码编译

使用最新Release版本域名.RELEASE

image-20210811091403678

同样找到项目根目录下域名,从githubSpring Framework源码 wiki找到编译源码说明

image-20210811091723913

image-20210811091927447

实现

根据Servlet从3.0版本之后的规范,所有实现Servlet规范的Web容器都会扫描jar包下面META-INF/services下的文件,在Spring Web子项目中利用Java 的SPI机制(SPI是一种扩展机制,很多框架底层都使用或甚至重新实现自己的SPI机制,比如像Spring和Dubbo都实现自己的SPI,以后我们再找时间来讨论,暂且到这里),在根目录下META-INF/services创建一个文件名域名letContainerInitializer,文件内容是实现类的域名.SpringServletContainerInitializer全类名

image-20210810175831748

SpringServletContainerInitializer实现类针对通过@HandlesTypes感兴趣注解, 将所有实现WebApplicationInitializer的实现类放到一个Set集合中,然后再逐个调用其onStartup()方法,所以这里我们接上了1.1章节官网MyWebApplicationInitializer实现WebApplicationInitializer接口这一部分

@HandlesTypes(域名s)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
	@Override
	public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
			throws ServletException {

		List<WebApplicationInitializer> initializers = 域名yList();

		if (webAppInitializerClasses != null) {
			initializers = new ArrayList<>(域名());
			for (Class<?> waiClass : webAppInitializerClasses) {
				// Be defensive: Some servlet containers provide us with invalid classes,
				// no matter what @HandlesTypes says...
				if (!域名terface() && !域名stract(域名odifiers()) &&
						域名signableFrom(waiClass)) {
					try {
						域名((WebApplicationInitializer)
								域名ssibleConstructor(waiClass).newInstance());
					}
					catch (Throwable ex) {
						throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
					}
				}
			}
		}

		if (域名pty()) {
			域名("No Spring WebApplicationInitializer types detected on classpath");
			return;
		}

		域名(域名() + " Spring WebApplicationInitializers detected on classpath");
		域名(initializers);
		for (WebApplicationInitializer initializer : initializers) {
			域名artup(servletContext);
		}
	}

}

接下来我们再来看看Web容器如Tomcat是如何在Spring Boot中运行的,首先我们先得知道SpringBoot启动过程,我们知道Spring Boot 应用程序都是从域名开始的,而run方法则始于SpringApplication类,返回ApplicationContext接口的子接口ConfigurableApplicationContext,通过refreshContext方法调用Spring Framework最大名鼎鼎的refresh方法初始化Spring容器,而refresh方法中的onRefresh是留给子类扩展使用的,而也是在这里开始初始化Web容器的

image-20210811094042778

image-20210811094642698

找到其实现类ServletWebServerApplicationContext,在这里createWebServer开始创建WebServer,

image-20210811094919733

image-20210811100427533

这里会根据我们我们pom文件starter依赖来决定创建Tomcat、Undertow、Jetty,Undertow在并发下性能明显优化另外Tomcat和Jetty,建议优先使用Undertow,但这里由于大家对于Tomcat印象比较深刻,所以我们示例还是以Tomcat为主

Spring Boot内嵌容器默认为Tomcat,想要换成Undertow也是非常容易的,只需修改spring-boot-starter-web依赖,移除tomcat的依赖:

<dependency>
    <groupId>域名</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>域名</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

添加undertow依赖:

<dependency>
    <groupId>域名</groupId>
    <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
server:  
    port: 8084  
    http2:  
        enabled: true  
    undertow:  
        io-threads: 16  
        worker-threads: 256  
        buffer-size: 1024  
        buffers-per-region: 1024  
        direct-buffers: true 

至此,这里我们通过ServletWebServerFactory的实现类TomcatServletWebServerFactory的getWebServer方法找到new Tomcat的源码

image-20210811102649821

image-20210811102803486

	@Override
	public WebServer getWebServer(ServletContextInitializer... initializers) {
		if (域名bleMBeanRegistry) {
			域名bleRegistry();
		}
		Tomcat tomcat = new Tomcat();
		File baseDir = (域名Directory != null) ? 域名Directory : createTempDir("tomcat");
		域名aseDir(域名bsolutePath());
		Connector connector = new Connector(域名ocol);
		域名hrowOnFailure(true);
		域名ervice().addConnector(connector);
		customizeConnector(connector);
		域名onnector(connector);
		域名ost().setAutoDeploy(false);
		configureEngine(域名ngine());
		for (Connector additionalConnector : 域名tionalTomcatConnectors) {
			域名ervice().addConnector(additionalConnector);
		}
		prepareContext(域名ost(), initializers);
		return getTomcatWebServer(tomcat);
	}

自动装配

@SpringBootApplication注解

我们知道所有运用Spring Boot应用程序在根目录的主类上都标有一个@SpringBootApplication的注解,这个就是SpringBoot自动装配实现的入口,我们接下来一步步的来分析,首先@SpringBootApplication在域名.域名ngBootApplication中,Spring Boot的自动装配也都是在域名.autoconfigure项目里实现的

image-20210811104306064

而我们经常看到spring-boot-starter-xxx这种里面主要是定义了依赖包装成一个个启动器,实际实现还是在spring-boot-autoconfigure中,这些都是Spring Boot官方帮我们整合实现并提供开箱即可工具,此外还有一些第三方整合提供以xxx开头的xxx-spring-boot-starter比如阿里巴巴的druid-spring-boot-starter和苞米豆mybatis-plus-boot-starter等

image-20210811104925144

在@SpringBootApplication注解里主要有下面这三个注解

  • @SpringBootConfiguration(继承了Configuration,表示当前是注解类)

  • @ComponentScan (包含扫描和排除扫描组件配置)

  • @EnableAutoConfiguration (在这里开启Spring Boot的自动配置注解功能)

    • @AutoConfigurationPackage
    • @Import(域名s)

核心之核心的地方就是借助@import导入AutoConfigurationImportSelector,这个是Spring中ImportSelector接口的实现类,ImportSelect接口是域名ext里的内容,在Spring Framework 3.1版本之后就有,后续我们有时间讨论Spring Framework 的时候再来详说

image-20210811110931317

image-20210811111307436

image-20210811113250346

重要的方法也即是这个getCandidateConfigurations,调用loadFactoryNames,而loadFactoryNames调用loadSpringFactories方法,域名esources这里就是谜底揭开的时候,通过JDK classLoader加载FACTORIES_RESOURCE_LOCATION(META-INF/域名ories)文件内容

	protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
		List<String> configurations = 域名FactoryNames(getSpringFactoriesLoaderFactoryClass(),
				getBeanClassLoader());
		域名mpty(configurations, "No auto configuration classes found in META-INF/域名ories. If you "
				+ "are using a custom packaging, make sure that file is correct.");
		return configurations;
	}

	public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
		ClassLoader classLoaderToUse = classLoader;
		if (classLoaderToUse == null) {
			classLoaderToUse = 域名lassLoader();
		}
		String factoryTypeName = 域名ame();
		return loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, 域名yList());
	}

	private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
		Map<String, List<String>> result = 域名(classLoader);
		if (result != null) {
			return result;
		}

		result = new HashMap<>();
		try {
			Enumeration<URL> urls = 域名esources(FACTORIES_RESOURCE_LOCATION);
			while (域名oreElements()) {
				URL url = 域名Element();
				UrlResource resource = new UrlResource(url);
				Properties properties = 域名Properties(resource);
				for (域名y<?, ?> entry : 域名ySet()) {
					String factoryTypeName = ((String) 域名ey()).trim();
					String[] factoryImplementationNames =
							域名aDelimitedListToStringArray((String) 域名alue());
					for (String factoryImplementationName : factoryImplementationNames) {
						域名uteIfAbsent(factoryTypeName, key -> new ArrayList<>())
								.add(域名());
					}
				}
			}

			// Replace all lists with unmodifiable lists containing unique elements
			域名aceAll((factoryType, implementations) -> 域名am().distinct()
					.collect(域名ectingAndThen(域名st(), Collections::unmodifiableList)));
			域名(classLoader, result);
		}
		catch (IOException ex) {
			throw new IllegalArgumentException("Unable to load factories from location [" +
					FACTORIES_RESOURCE_LOCATION + "]", ex);
		}
		return result;
	}

image-20210811111853490

通过spring-boot-autoconfigure的resource目录下META-INF目录找到域名ories文件后我们可以看到这里面就是Spring SPI机制实现,在此定义一个规范的路径和文件名,文件内容放置了一个个Spring Boot提供自动装配的组件,而后面我们可想而知Spring Boot底层肯定还是利用反射机制将这些类放到Spring容器中管理,我们就可以通过Spring Boot通用三板斧使用步骤,第一步加坐标依赖starter,第二步启动类中开启使用注解,第三步配置配置文件参数后轻松使用工具类的功能

image-20210811112441095

Starter开发简易剖析

步骤

  • 建立autoconfigure工程
    • 开发自动配置的实现类
      • 域名s 提供参数配置实现类,比如redis的host、url等,我们也可以从这里找到所有配置参数信息
      • 域名s,由@Import注解导入依赖类
      • xxxAutoConfiguration实现类,然后通过Java Config和@Bean注解方式将Java Bean注册到Spring容器里,后续使用则直接从Spring容器中拿即可
    • 项目根目录resource建立META-INF文件夹,下面建立域名ories文件,将自动配置类的全类名方放在域名.域名leAutoConfiguration里
  • 建立spring-boot-starter-xxx工程,管理依赖,如下Redis Starter gradle配置

RedisAutoConfiguration分析

RedisAutoConfiguration实现

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(域名s)
@EnableConfigurationProperties(域名s)
@Import({ 域名s, 域名s })
public class RedisAutoConfiguration {

   @Bean
   @ConditionalOnMissingBean(name = "redisTemplate")
   @ConditionalOnSingleCandidate(域名s)
   public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
      RedisTemplate<Object, Object> template = new RedisTemplate<>();
      域名onnectionFactory(redisConnectionFactory);
      return template;
   }

   @Bean
   @ConditionalOnMissingBean
   @ConditionalOnSingleCandidate(域名s)
   public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
      StringRedisTemplate template = new StringRedisTemplate();
      域名onnectionFactory(redisConnectionFactory);
      return template;
   }

}

Redis Starter依赖

plugins {
	id "域名.starter"
}

description = "Starter for using Redis key-value data store with Spring Data Redis and the Lettuce client"

dependencies {
	api(project(":spring-boot-project:spring-boot-starters:spring-boot-starter"))
	api("域名:spring-data-redis")
	api("域名uce:lettuce-core")
}

标签:编程
湘ICP备14001474号-3  投诉建议:234161800@qq.com   部分内容来源于网络,如有侵权,请联系删除。