《Springboot设计思想》2-Springboot青出于蓝

相信使用过Springboot的各位应该深有体会,Springboot的快速搭建能力比传统的Spring framework高出不少。我个人认为归功于一下几点:

  • 版本依赖管理

基于Springboot initializer创建的Springboot工程,继承了Spring-boot-stater的父pom

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

父pom已经管理好适用版本,在传统Spring framework还在纠结jar包版本的时候,Springboot工程就可以放心的引入,版本管理就委托给Springboot,这个也是我们规约大于配置的一部分。

  • 按需装配

在Springboot中,按照模块化的思想设计各个功能,比如web功能,从MVC到web容器,只要添加一个依赖就可以完成

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

在当前依赖中已经集成了SpringMVC 和内嵌式tomcat的容器,不需要我们再做其他工作,就可以进行web服务的开发

比如要继承mybatis功能,可以添加依赖

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

上面的功能就是Springboot的EnableAutoConfiguration注解结合starter提供的一个功能。

  • 更灵活的功能扩展

为什么要说这一点呢。在传统的Spring-framework工程中,主要的核心组件有三个

  1. application context
  2. Environment
  3. BeanFactory

上面三个核心组件中ApplicationContext可监听的声明周期有4个

ContextStartedEvent

ContextRefreshEvent

扫描二维码关注公众号,回复: 11938112 查看本文章

ContextStopEvent

ContextClosedEvent

Evironment能够调整的节点只有在ApplicationContext新建之后,obtainFreshBeanFactory()之前,其余的时候再调整配置,在beanFactory之后就不能起到很好的调整功能。

但是Springboot新增了一个非常重要的核心组件:

SpringApplication

他们的关系大概如下

在Spring framework中,ApplicationContext主管应用的生命周期,在Springboot中 委托给SpringApplication 主管生命周期。

所以在SpringBoot中可以监听的事件包含传统Spring的周期,但又扩展了以下几种

  1. ApplicationStartingEvent
  2. ApplicationEnvironmentPreparedEvent
  3. ApplicationPreparedEvent
  4. ApplicationStartedEvent
  5. ApplicationReadyEvent
  6. ApplicationFailedEvent

以上1-5是按序发送的,如果启动失败会监听到 ApplicationFailedEvent

所以在ApplicationContext实例化之前,我们就可以配置或者更改我们的应用。

以上三个点就是我认为Springboot优于Spring framework的根本原因,当然spring framework是根基,而Springboot也不能脱离了Springframwork单独使用。所以学好前面系列的《Spring设计思想》才能更好的理解本系列的内容。有兴趣的小伙伴可以翻看前面系列的文章巩固知识。

猜你喜欢

转载自blog.csdn.net/David_lou/article/details/108421865