1-简介

Spring Boot是基于Spring框架开发的全新框架,其设计目的是简化Spring应用的初始化搭建和开发过程。

Spring Boot整合了许多框架和第三方库配置,几乎可以达到“开箱即用”。

优点

可快速构建独立的Spring应用

直接嵌入Tomcat、Jetty和Undertow服务器(无需部署WAR文件)

提供依赖启动器简化构建配置

极大程度的自动化配置Spring和第三方库

提供生产就绪功能

极少的代码生成和XML配置

2-环境准备

2-1-参考

2-2-工具

安装JDK 1.8.0_201(及以上版本)

classpath:.; %JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar;%CATALINA_HOME%\lib\servlet-api.jar

安装Tomcat9

安装eclipse

安装spring Tools插件

打开eclipse----菜单----Help----Eclipse Marketplace----在Find搜索框中输入spring----回车搜索

可能会失败,多来几次,安装时间比较长。

安装Apache Maven 3.6.0

Eclipse配置Maven参考

1.目前eclipse自带maven,也可以使用自己的maven,如下图所示

2.修改settings.xml,设置本地仓库位置和远程仓库镜像

<localRepository>D:/repository</localRepository>
<mirror><id>alimaven</id><name>aliyun maven</name><url>https://maven.aliyun.com/repository/public</url><mirrorOf>central</mirrorOf></mirror>

3.eclipse使用自己的settings.xml

3-入门程序

3-1-maven手动创建

创建Maven项目

在pom.xml中添加Spring Boot相关依赖

<!-- 引入Spring Boot依赖 --><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.3.RELEASE</version></parent>

<dependencies><!-- 引入Web场景依赖启动器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies>

编写主程序启动类

@SpringBootApplication(scanBasePackages = "com.itheima")public class ManualApp {public static void main(String[] args) throws Exception {SpringApplication.run(ManualApp.class, args);}}

创建一个用于Web访问的Controller

@RestController
publicclass HelloController {@GetMapping("/hello")public String hello() {return "hello Spring Boot";}
}

运行项目

在浏览器地址栏输入 http://localhost:8080/hello即可看到运行结果

如果遇到端口占用,新建application.properties,设置端口号

# 应用服务 WEB 访问端口
server.port=8080

3-2-spring stater project创建

创建项目

下图中的service url:https://start.aliyun.com/,创建项目就会变快

创建HelloController

@RestController
publicclass HelloController {@GetMapping("/hello")public String hello() {return "hello Spring Boot";}
}

测试同上

4-单元测试和热部署

4-1-单元测试

在pom文件中添加spring-boot-starter-test测试启动器

 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency>

打开自动创建的单元测试类

编写单元测试方法

@Autowired
private HelloController helloController;@Test
public void helloControllerTest() {String hello = helloController.hello();System.out.println(hello);}

执行测试方法helloControllerTest()

4-2-热部署

在pom文件中添加spring-boot-devtools热部署依赖

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

或者

设置自动构建

热部署测试

修改HelloController的方法的返回值

5-Spring Boot 原理分析

以入门程序为例子,<spring-boot.version>2.4.3.RELEASE</spring-boot.version>

5-1-Spring Boot 依赖管理

spring-boot-starter-parent

配置文件管理

<resources>
      <resource>
        <directory>${basedir}/src/main/resources</directory>
        <filtering>true</filtering>
        <includes>
          <include>**/application*.yml</include>
          <include>**/application*.yaml</include>
          <include>**/application*.properties</include>
        </includes>
      </resource>
      <resource>
        <directory>${basedir}/src/main/resources</directory>
        <excludes>
          <exclude>**/application*.yml</exclude>
          <exclude>**/application*.yaml</exclude>
          <exclude>**/application*.properties</exclude>
        </excludes>
      </resource>
    </resources>

spring-boot-dependencies

1.常用技术的版本号管理

<properties>
    <activemq.version>5.15.14</activemq.version>

2.常用技术的依赖管理

<dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-amqp</artifactId>
        <version>${activemq.version}</version>
      </dependency>

3.插件管理

<build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>build-helper-maven-plugin</artifactId>
          <version>${build-helper-maven-plugin.version}</version>
        </plugin>

spring-boot-starter-web

<dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.3.7.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-json</artifactId>
      <version>2.3.7.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <version>2.3.7.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.2.12.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.12.RELEASE</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>

5-2-Spring Boot 自动配置

由@SpringBootApplication配置springboot

源码:

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

@SpringBootConfiguration

@Configuration
public @interface SpringBootConfiguration {

说明是一个配置类,相当于XML配置文件

@EnableAutoConfiguration

@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

@AutoConfigurationPackage

@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {

static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {

@Override
        public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
            register(registry, new PackageImports(metadata).getPackageNames().toArray(new String[0]));
        }

new PackageImports(metadata).getPackageNames().toArray(new String[0]):获取主程序启动类所在包

AutoConfigurationImportSelector.class中

有个方法getAutoConfigurationEntry()中

List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);:获取自动配置类

# 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,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\

。。。。。。

configurations = getConfigurationClassFilter().filter(configurations);:选出符合当前项目的自动配置类

@ComponentScan

扫描主程序启动类所在包下的组件

5-3-Spring Boot 执行流程

SpringApplication.run(Springboot11Application.class, args);

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实例并初始化和调用run方法启动项目

SpringApplication实例并初始化

public SpringApplication(Class<?>... primarySources) {
        this(null, primarySources);
    }

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();//判断web应用类型,servlet应用还是reactive应用
        setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));//设置SpringApplication应用的初始化器
        setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));//设置SpringApplication应用的监听器
        this.mainApplicationClass = deduceMainApplicationClass();//推断主程序启动类
    }

static WebApplicationType deduceFromClasspath() {
        if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
                && !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
            return WebApplicationType.REACTIVE;
        }
        for (String className : SERVLET_INDICATOR_CLASSES) {
            if (!ClassUtils.isPresent(className, null)) {
                return WebApplicationType.NONE;
            }
        }
        return WebApplicationType.SERVLET;
    }

run方法

public ConfigurableApplicationContext run(String... args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
        configureHeadlessProperty();
        SpringApplicationRunListeners listeners = getRunListeners(args);//获取监听器
        listeners.starting();//启动监听器

        try {
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);// Create and configure the environment
            configureIgnoreBeanInfo(environment);//

            Banner printedBanner = printBanner(environment);
            context = createApplicationContext();
            exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                    new Class[] { ConfigurableApplicationContext.class }, context);
            prepareContext(context, environment, listeners, applicationArguments, printedBanner);
            refreshContext(context);
            afterRefresh(context, applicationArguments);

            stopWatch.stop();
            if (this.logStartupInfo) {
                new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
            }
            listeners.started(context);
            callRunners(context, applicationArguments);//调用自定义的执行器,在启动项目后立即执行一些特定程序
        }
        catch (Throwable ex) {
            handleRunFailure(context, ex, exceptionReporters, listeners);
            throw new IllegalStateException(ex);
        }

try {

/**
     * Called immediately before the run method finishes, when the application context has
     * been refreshed and all {@link CommandLineRunner CommandLineRunners} and
     * {@link ApplicationRunner ApplicationRunners} have been called.
     * @param context the application context.
     * @since 2.0.0
     */
            listeners.running(context);//
        }
        catch (Throwable ex) {
            handleRunFailure(context, ex, exceptionReporters, null);
            throw new IllegalStateException(ex);
        }
        return context;
    }

1-springboot基础相关推荐

  1. SpringBoot基础系列-SpringCache使用

    原创文章,转载请标注出处:<SpringBoot基础系列-SpringCache使用> 一.概述 SpringCache本身是一个缓存体系的抽象实现,并没有具体的缓存能力,要使用Sprin ...

  2. SpringBoot基础重难点

    来源:SpringBoot基础重难点 - liangxiaolong - 博客园 1.SpringBoot 1.1 概念 Spring Boot是构建所有基于Spring的应用程序的起点.Spring ...

  3. 【Java笔记+踩坑】SpringBoot基础3——开发。热部署+配置高级+整合NoSQL/缓存/任务/邮件/监控

      导航: [黑马Java笔记+踩坑汇总]JavaSE+JavaWeb+SSM+SpringBoot+瑞吉外卖+SpringCloud/SpringCloudAlibaba+黑马旅游+谷粒商城 目录 ...

  4. SpringBoot基础知识

    SpringBoot基础知识 SpringBoot课程笔记 前言 ​ 很荣幸有机会能以这样的形式和互联网上的各位小伙伴一起学习交流技术课程,这次给大家带来的是Spring家族中比较重要的一门技术课程- ...

  5. 8. SpringBoot基础学习笔记

    SpringBoot基础学习笔记 课程前置知识说明 1 SpringBoot基础篇 1.1 快速上手SpringBoot SpringBoot入门程序制作 1.2 SpringBoot简介 1.2.1 ...

  6. SpringBoot基础学习之SpringBoot配置(上篇)

    前言: 小伙伴们,大家好,我是狂奔の蜗牛rz,当然你们可以叫我蜗牛君,我是一个学习Java半年多时间的小菜鸟,同时还有一个伟大的梦想,那就是有朝一日,成为一个优秀的Java架构师. 这个SpringB ...

  7. SpringBoot基础学习之整合Swagger框架(上篇)

    前言: 小伙伴们,大家好,我是狂奔の蜗牛rz,当然你们可以叫我蜗牛君,我是一个学习Java半年多时间的小菜鸟,同时还有一个伟大的梦想,那就是有朝一日,成为一个优秀的Java架构师. 这个SpringB ...

  8. SpringBoot基础的依赖说明

    SpringBoot基础的依赖说明 前言 前提 spring-boot-starter-parent spring-boot-starter-web spring-boot-configuration ...

  9. 动力节点王鹤SpringBoot3学习笔记——第二章 掌握SpringBoot基础篇

    目录 二.掌控SpringBoot基础篇 2.1 Spring Boot ? 2.1.1 与Spring关系 2.1.2 与SpringCloud关系 2.1.3  最新的Spring Boot3 新 ...

  10. SpringBoot 基础入门

    SpringBoot 基础入门 Spring Boot简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的创建.运行.调试.部署等.使用Spring ...

最新文章

  1. dataframe 查找特定值_省时省力的查找引用函数
  2. python中文叫什么意思-在python中,“~”是什么意思?
  3. Tramp data In Kernel
  4. linux内核删不掉,linux 删除内核文件,未能启动,修复方法 CDROM与网络法
  5. 教育部最新公布!2019年高校新增和撤销了这些本科专业
  6. vivo z5和z5x有什么区别
  7. 半自动添加Grafana 模板之 ---- POST提交
  8. ABP理论学习之NHibernate集成
  9. [充电]Code Review
  10. JavaScript:工具库MyTools.js(自用不断填充····)
  11. CAN FD协议描述
  12. (附源码)Python在线办公系统 毕业设计 071116
  13. 银河麒麟支持php吗,银河麒麟Linux
  14. dsp2812 c语言数据类型长度,DSP2812代码长度超出RAM容量,有谁遇到过吗?
  15. 魔方优化大师 v5.15 中文绿色版
  16. Web功能测试(邮箱,手机号,验证码,身份证号测试用例)
  17. openssl rand
  18. java开发购物系统菜单_Java控制台购物系统
  19. python爬取千图网_python爬取lol官网英雄图片代码
  20. NI的LabView2022工具的安装与使用

热门文章

  1. python scheduler 定时执行_python使用apscheduler做定时任务的管理
  2. 【Spring】Feign客户端发送HTTPS请求绕过认证
  3. 【算法】剑指 Offer 47. 礼物的最大价值
  4. 95-20-020-启动器-Cloneable
  5. 【Flink】Flink 报错 ResourceManager leader changed to new address null
  6. 60-100-032-使用-MySQL大小写敏感的解决方法
  7. 【MySQL】MySQL 8 Show innodb status 命令改变
  8. SpringBoot : 注解@Resource
  9. spark学习-53-Spark下Java版HBase下的根据权重获取最真实数据
  10. MySQL-02-windows下查看frm,myi,myd