spring boot--自动化注入组件原理、内嵌tomcat-1

这篇具有很好参考价值的文章主要介绍了spring boot--自动化注入组件原理、内嵌tomcat-1。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

我们知道开发spring boot项目,在启动类上添加注解@SpringBootApplication ,然后引入要自动注入的组件依赖,然后现application.properties中加上相应配置就可以自动注入这个组件,那么下面看看自动注入组件是如何实现的

一、@SpringBootApplication 注解

1、查看SpringBootApplication 类如下:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
}

2、查看@EnableAutoConfiguration类

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

    Class<?>[] exclude() default {};

    String[] excludeName() default {};
}

这个类又通过@Import({AutoConfigurationImportSelector.class}) 导入了
3、AutoConfigurationImportSelector这个bean,查看这个bean

public class AutoConfigurationImportSelector
		implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware,
		BeanFactoryAware, EnvironmentAware, Ordered {
		}

4、这个AutoConfigurationImportSelector类继承了DeferredImportSelector最终继承了ImportSelector,重写这个类的selectImports方法可以快速导入一个bean,查看selectImports方法

@Override
	public String[] selectImports(AnnotationMetadata annotationMetadata) {
		if (!isEnabled(annotationMetadata)) {
			return NO_IMPORTS;
		}
		AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
				.loadMetadata(this.beanClassLoader);
		AnnotationAttributes attributes = getAttributes(annotationMetadata);
		List<String> configurations = getCandidateConfigurations(annotationMetadata,
				attributes);
		configurations = removeDuplicates(configurations);
		Set<String> exclusions = getExclusions(annotationMetadata, attributes);
		checkExcludedClasses(configurations, exclusions);
		configurations.removeAll(exclusions);
		configurations = filter(configurations, autoConfigurationMetadata);
		fireAutoConfigurationImportEvents(configurations, exclusions);
		return StringUtils.toStringArray(configurations);
	}

5、查看List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
这个方法

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

6、这个方法最终会调用loadSpringFactories方法,这个方法把META-INF/spring.factories定义的类全部读到出来
spring boot--自动化注入组件原理、内嵌tomcat-1,spring boot,自动化,tomcat

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
        MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);
        if (result != null) {
            return result;
        } else {
            try {
                Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
                LinkedMultiValueMap result = new LinkedMultiValueMap();

                while(urls.hasMoreElements()) {
                    URL url = (URL)urls.nextElement();
                    UrlResource resource = new UrlResource(url);
                    Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                    Iterator var6 = properties.entrySet().iterator();

                    while(var6.hasNext()) {
                        Entry<?, ?> entry = (Entry)var6.next();
                        List<String> factoryClassNames = Arrays.asList(StringUtils.commaDelimitedListToStringArray((String)entry.getValue()));
                        result.addAll((String)entry.getKey(), factoryClassNames);
                    }
                }

                cache.put(classLoader, result);
                return result;
            } catch (IOException var9) {
                throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var9);
            }
        }
    }

7、最终spring会根据这些组件中定义的注入条件将这些组件自动注入,org.springframework.boot.autoconfigure下放了所有自动注入的组件,以aop这个组件为例:
spring boot--自动化注入组件原理、内嵌tomcat-1,spring boot,自动化,tomcat

@Configuration
//条件注入,当有 `EnableAspectJAutoProxy.class, Aspect.class, Advice.class,`这些class存在时才注入,也就是说当引入相关依赖包时注入
		AnnotatedElement.class
@ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class,
		AnnotatedElement.class })
//当配置文件中有spring.aop 配置时才注入
@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
public class AopAutoConfiguration {

	@Configuration
	@EnableAspectJAutoProxy(proxyTargetClass = false)
	@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false", matchIfMissing = false)
	public static class JdkDynamicAutoProxyConfiguration {

	}

	@Configuration
	@EnableAspectJAutoProxy(proxyTargetClass = true)
	@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", matchIfMissing = true)
	public static class CglibAutoProxyConfiguration {

	}

}
二、spring boot内嵌tomcat

最简单的tomcat集成
1、添加pom文件

<dependencies>

        <!--Java语言操作tomcat -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <version>8.5.16</version>
        </dependency>

        <!-- tomcat对jsp支持 -->
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jasper</artifactId>
            <version>8.5.16</version>
        </dependency>

    </dependencies>

2、新建一个servlet文件

public class IndexServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().print("this is index... tomcat");
    }

}

3、新建一个启动类

public class DTomcat {

    private static int PORT = 8080;
    private static String CONTEX_PATH = "/clock";
    private static String SERVLET_NAME = "indexServlet";

    public static void main(String[] args) throws LifecycleException, InterruptedException {

        // 创建tomcat服务器
        Tomcat tomcatServer = new Tomcat();
        // 指定端口号
        tomcatServer.setPort(PORT);
        // 是否设置自动部署
        tomcatServer.getHost().setAutoDeploy(false);
        // 创建上下文
        StandardContext standardContex = new StandardContext();
        standardContex.setPath(CONTEX_PATH);
        // 监听上下文
        standardContex.addLifecycleListener(new Tomcat.FixContextListener());
        // tomcat容器添加standardContex
        tomcatServer.getHost().addChild(standardContex);

        // 创建Servlet
        tomcatServer.addServlet(CONTEX_PATH, SERVLET_NAME, new IndexServlet());
        // servleturl映射
        standardContex.addServletMappingDecoded("/index", SERVLET_NAME);
        tomcatServer.start();
        System.out.println("tomcat服务器启动成功..");
        // 异步进行接收请求
        tomcatServer.getServer().await();

    }
}

4、运行main,在浏览器输入:
http://localhost:8080/clock/index

spring boot内嵌tomcat
1、启动一个spring boot项目,查看控制台最下的日志:
可以看出spring boot在启动的时候,启动一个tomcat,实际上它启动的方式也是上面那么启动方式
spring boot--自动化注入组件原理、内嵌tomcat-1,spring boot,自动化,tomcat
2、tomcat加载流程
tomcat也是一个组件,那么它的引入方式也是通过spring.factories文件注入的
spring boot--自动化注入组件原理、内嵌tomcat-1,spring boot,自动化,tomcat
3、查看ServletWebServerFactoryAutoConfiguration这个类
ServletWebServerFactoryAutoConfiguration这个类用@import快速导入了EmbeddedTomcat类
spring boot--自动化注入组件原理、内嵌tomcat-1,spring boot,自动化,tomcat
4、查看EmbeddedTomcat类
这个类注入了TomcatServletWebServerFactory这个bean

@Configuration
	@ConditionalOnClass({ Servlet.class, Tomcat.class, UpgradeProtocol.class })
	@ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT)
	public static class EmbeddedTomcat {

		@Bean
		public TomcatServletWebServerFactory tomcatServletWebServerFactory() {
			return new TomcatServletWebServerFactory();
		}

	}

4、查看TomcatServletWebServerFactory类
这个类有一个getWebServer方法如下:
这个方法启动了一个tomcat,那么这个方法是在哪个地方调用的?可以在这个方法上打上断点,查看它的调用链

public WebServer getWebServer(ServletContextInitializer... initializers) {
        Tomcat tomcat = new Tomcat();
        File baseDir = this.baseDirectory != null ? this.baseDirectory : this.createTempDir("tomcat");
        tomcat.setBaseDir(baseDir.getAbsolutePath());
        Connector connector = new Connector(this.protocol);
        tomcat.getService().addConnector(connector);
        this.customizeConnector(connector);
        tomcat.setConnector(connector);
        tomcat.getHost().setAutoDeploy(false);
        this.configureEngine(tomcat.getEngine());
        Iterator var5 = this.additionalTomcatConnectors.iterator();

        while(var5.hasNext()) {
            Connector additionalConnector = (Connector)var5.next();
            tomcat.getService().addConnector(additionalConnector);
        }

        this.prepareContext(tomcat.getHost(), initializers);
        return this.getTomcatWebServer(tomcat);
    }

5、在getWebServer()方法,打断点,然后启动spring boot的main方法,查看调用链如下:
spring boot--自动化注入组件原理、内嵌tomcat-1,spring boot,自动化,tomcat
6、启动流程分析
查看main里面的run方法,
这个方法主要new 了一个SpringApplication对象,然后执行了run方法

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

SpringApplication结构方法:
加载了相关类,没有执行

public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
		this.resourceLoader = resourceLoader;
		Assert.notNull(primarySources, "PrimarySources must not be null");
		//保存主类
		this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
		//判断当前是什么类型项目
		this.webApplicationType = WebApplicationType.deduceFromClasspath();
	//从类路径下找到META-INF/spring.factories配置的所有ApplicationContextInitializer
		setInitializers((Collection) getSpringFactoriesInstances(
				ApplicationContextInitializer.class));
	//从类路径下找到META-INF/spring.factories配置的所有ApplicationListener
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
		this.mainApplicationClass = deduceMainApplicationClass();
}

run方法:

public ConfigurableApplicationContext run(String... args) {
	StopWatch stopWatch = new StopWatch();
	stopWatch.start();
	ConfigurableApplicationContext context = null;
	Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
	configureHeadlessProperty();
	//从类路径下META‐INF/spring.factories,取得SpringApplicationRunListeners;
	SpringApplicationRunListeners listeners = getRunListeners(args);
//回调所有的获取SpringApplicationRunListener.starting()方法
	listeners.starting();
	try {
	    //封装命令行参数
		ApplicationArguments applicationArguments = new DefaultApplicationArguments(
				args);
	    //准备环境
		ConfigurableEnvironment environment = prepareEnvironment(listeners,
				applicationArguments);
		configureIgnoreBeanInfo(environment);
           //创回调SpringApplicationRunListener.environmentPrepared();
//表示环境准备完成

		//打印Banner 
		Banner printedBanner = printBanner(environment);
           //根据环境创建context
		context = createApplicationContext();
	    //错误的异常报表
		exceptionReporters = getSpringFactoriesInstances(
				SpringBootExceptionReporter.class,
				new Class[] { ConfigurableApplicationContext.class }, context);
            //准备上下文环境;
           //将environment保存到ioc中;
           //applyInitializers()调用所有的ApplicationContextInitializer的initialize方法
//调用所有的SpringApplicationRunListener的contextPrepared();
		prepareContext(context, environment, listeners, applicationArguments,
				printedBanner);
//SpringApplicationRunListener的contextLoaded
//刷新容器
//扫描,创建,加载所有组件;
		refreshContext(context);
		afterRefresh(context, applicationArguments);
		stopWatch.stop();
		if (this.logStartupInfo) {
			new StartupInfoLogger(this.mainApplicationClass)
					.logStarted(getApplicationLog(), stopWatch);
		}
		//所有的SpringApplicationRunListener回调started方法
		listeners.started(context);
		//获取所有的ApplicationRunner和CommandLineRunner进行调用
		callRunners(context, applicationArguments);
	}
	catch (Throwable ex) {
		handleRunFailure(context, ex, exceptionReporters, listeners);
		throw new IllegalStateException(ex);
	}

	try {
		//所有的SpringApplicationRunListener的running();
		listeners.running(context);
	}
	catch (Throwable ex) {
		handleRunFailure(context, ex, exceptionReporters, null);
		throw new IllegalStateException(ex);
	}
	return context;
}
三、spring boot内嵌tomcat,修改web容器

从spring boot启动日志看,我们知道spring boot内嵌的web容器是tomcat,那么如果我们不想用tomcat 也可以换别的web容器
1、修改pom
排除tomcat,引入undertow容器

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>
    </dependencies>

这个再启动spring boot项目用的就是undertow容器文章来源地址https://www.toymoban.com/news/detail-610103.html

到了这里,关于spring boot--自动化注入组件原理、内嵌tomcat-1的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Jenkins + Docker 一键自动化部署 Spring Boot 项目,步骤齐全,少走坑路!

    本文章实现最简单全面的Jenkins+docker+springboot 一键自动部署项目,步骤齐全,少走坑路。 环境 :centos7+git(gitee) 简述实现步骤:在docker安装jenkins,配置jenkins基本信息,利用Dockerfile和shell脚本实现项目自动拉取打包并运行。 推荐一个开源免费的 Spring Boot 实战项目: https://git

    2024年02月08日
    浏览(56)
  • 自动化机器学习流水线:基于Spring Boot与AI机器学习技术的融合探索

    🧑 作者简介:阿里巴巴嵌入式技术专家,深耕嵌入式+人工智能领域,具备多年的嵌入式硬件产品研发管理经验。 📒 博客介绍:分享嵌入式开发领域的相关知识、经验、思考和感悟,欢迎关注。提供嵌入式方向的学习指导、简历面试辅导、技术架构设计优化、开发外包等服

    2024年04月27日
    浏览(29)
  • Spring Boot Testing: 使用springboot-test提供的测试框架来实现自动化测试

    作者:禅与计算机程序设计艺术 软件测试是在开发过程中不可缺少的一环。单元测试、集成测试、功能测试等都是为了保证系统的质量而进行的测试活动。单元测试主要验证各个模块(类、方法)在各种情况下是否正常工作;集成测试则是将不同模块组合起来看是否可以正常

    2024年02月07日
    浏览(36)
  • sqlmap 是一个自动化的 sql 注入渗透工具

    一.介绍 sqlmap 是一个自动化的 sql 注入渗透工具,指纹检测、注入方式、注入成功后的取数据等等都是自动化的,sqlmap 还提供了很多脚本.但在实践测试的时候基本用不上.用于检测和利用 Web 应用程序中的 SQL 注入漏洞。它自动化了识别和利用 SQL 注入漏洞的过程,并可用于执

    2024年01月23日
    浏览(37)
  • Spring Boot中的依赖注入和自动注入

    以下内容为本人学习 Spring Boot的依赖注入和自动注入 与ChatGpt提问后对其回答 进行部分修改 (有的错误实在是离谱 = =)、格式调整等操作后的答案, 可能对于其中部分细节(是错是对,能力有限有的看不出来 = =),并未做深入探究 ,大家感兴趣的话可以自行验证。 依赖注

    2024年02月06日
    浏览(34)
  • 【安全测试学习】自动化注入攻击之 FuzzDB和Burp 组合拳

    一、FuzzDB 开源的应用程序模糊测试数据库,包含了各种攻击 payload 的测试用例集合。 主要功能: OS 命令注入 目录遍历 文件上传绕过 身份验证绕过 XSS SQL 注入 HTTP 头注入 CRLF 注入 NoSQL 注入等 还包含了一些用不同语言写成的 webshell 与常用的账号密码字典。 github地址: GitH

    2023年04月08日
    浏览(38)
  • 【网络安全-sql注入(5)】sqlmap以及几款自动化sql注入工具的详细使用过程(提供工具)

    分享一个非常详细的网络安全笔记,是我学习网安过程中用心写的,可以点开以下链接获取: 超详细的网络安全笔记 (也可以拿自己的环镜来玩,我是用pikachu靶场来演示的) 【网路安全 --- pikachu靶场安装】超详细的pikachu靶场安装教程(提供靶场代码及工具)_网络安全_Ai

    2024年02月08日
    浏览(40)
  • 使用Burp Suite和Python进行自动化漏洞挖掘—SQL测试注入插件

    每次测注入都是用burp的Intruder模块,很不方便就是批量跑批量测哪些没有过滤 懒人鹅上线,准备搞一个sql测试的插件 本篇文章代码量大,基础可以去看上一篇 测试sql基本注入的载荷,在可能有sql注入的地方发送测试包,目前只测试url中的,并可以根据错误回显判断出数据库

    2024年02月09日
    浏览(30)
  • 自动化测试 - Web自动化测试原理

    目前市面上有很多Web UI自动化测试框架,比如WatiN, Selinimu,WebDriver,还有VS2010中的Coded UI等等. 这些框架都可以操作Web中的控件,模拟用户输入,点击等操作,实现Web自动化测试。其实这些工具的原理都一样,都是通过调用IE COM接口和HTML DOM 对IE浏览器以及WEB测试对象的操作。

    2024年01月16日
    浏览(35)
  • python自动化测试-自动化基本技术原理

    在之前的文章里面提到过:做自动化的首要本领就是要会  透过现象看本质  ,落实到实际的IT工作中就是  透过界面看数据 。 掌握上面的这样的本领可不是容易的事情,必须要有扎实的计算机理论基础,才能看到深层次的本质东西。 数据库应用系统  可能是最典型的网络

    2024年02月10日
    浏览(29)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包