Springboot(大总结)

本文详细探讨了Springboot的优点和缺点,以及如何创建第一个Springboot程序。深入解析了Springboot的依赖管理、自动配置和容器功能,包括组件添加、条件装配、配置绑定等。文章还涵盖了Springboot的核心功能,如Web开发、错误处理、监控指标和外部化配置,并介绍了如何自定义配置、集成Mybatis以及单元测试等实践操作。此外,还讨论了Springboot的启动原理和Profile功能。
摘要由CSDN通过智能技术生成

Springboot

springboot优点

​ 创建独立的spring应用

​ 内嵌web服务器

​ 自动starte依赖,简化构建配置

​ 自动配置spring以及第三方功能

​ 提供生产级别的监控、健康检查以及外部化检查

​ 无代码生成、无需编写xml文件

缺点

​ 版本迭代过快需要时刻关注

​ 封装太深,内部原理复杂

第一个springboot程序

条件:maven3.3以上、JDK1.8

1在电脑终端输入mvn -v查看maven的版本

2在电脑终端输入java -version查看jdk版本

3使用idea创建一个maven工程

​ 新建项目maven
在这里插入图片描述
在这里插入图片描述

打开pom.xml文件加入依赖(在springboot官网也有)

<!--springboot依赖-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.4</version>
</parent>
 <!--web开发依赖springboot官网-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

在java目录中创建一个主文件(MainApplication.java)

package com.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/*
主程序类
@SpringBootApplication告诉springboot这是一个springboot应用*/
@SpringBootApplication
public class MainApplication {
   
    public static void main(String[] args) {
   
 
 /*主程序运行*/       SpringApplication.run(MainApplication.class,args);
    }
}

在创建一个Controller类

package com.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/*@ResponseBody
@Controller*/
@RestController//就是@ResponseBody和@Controller
public class HelloController {
   

    @RequestMapping("/hello")
    public  String hello01(){
   
        return "hello Springboot2";
    }
}

直接运行主类就可以了

在这里插入图片描述

springboot主配置文件(官网链接: https://docs.spring.io/spring-boot/docs/2.4.4/reference/html/appendix-application-properties.html#common-application-properties)

在这里插入图片描述

导包插件(在pom.xml文件中引入插件)

<!--导包插件-->
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

运行结果
在这里插入图片描述

Springboot依赖管理

父项目做依赖管理(子项目继承父项目子项目无需版本号)

<!--springboot依赖-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.4</version>
</parent>

修改pom.xml里面jar包的版本

先找到父项目的版本

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-dependencies</artifactId>
  <version>2.4.4</version>
</parent>

修改Mysql(<mysql.version>8.0.23</mysql.version>)这里mysql的版本号是8.0.23

在pom.xml里面修改

<properties>
    <mysql.version>5.1.43</mysql.version>
</properties>

starter场景启动器

1.spring-boot-starter-*;星就代表的某种场景

2.只要引入spring-boot-starter-*,这个场景的所有需要的依赖和jar包都会引入进来

所有场景启动器最底层的依赖

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

3.springboot所有支持的场景官方文档链接:https://docs.spring.io/spring-boot/docs/2.4.4/reference/html/using-spring-boot.html#using-boot-starter

*-spring-boot-starter(代表着第三方的starter)
在这里插入图片描述

在这里插入图片描述

自动配置

自动配好tomcat

​ 引入tomcat依赖

​ 配置tomcat

自动配好springmvc

​ 引入springmvc全套组件

​ 自动配置好springmvc常用组件

可以在主程序下用以下方法查看

public class MainApplication {
   
    public static void main(String[] args) {
   
        //1.返回一个ioc容器
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);

        //查看容器里面的组件
        String[] names = run.getBeanDefinitionNames();
        for (String name : names) {
   
            System.out.println(name);
        }
    }

自动配好web常见功能

​ springboot帮我们配置好了所有web开发的场景

默认的包结构

​ 主程序所在包及其下面的所欲子包里面的组件都会被默认扫面进来

​ 无需以前的包扫描配置

​ 想要改变扫面路径,使用:

@SpringBootApplication(scanBasePackages = "com.springboot")

各种配置拥有默认值

​ 默认配置最终都会映射到MultipartProperties

​ 配置文件的值最终会绑定某个类上,这个类会在容器中创建对象

按需加载所有自动配置项

​ 非常多的starter

​ 引入了那些场景这个场景的自动配置才会开启

​ springboot所有的自动配置功能都在spring-boot-autoconfigure包里面

容器功能

组件添加

​ 1.@Configuration

​ 基本使用

​ Full模式与Lite模式

@Configuration(proxyBeanMethods =true)/*告诉springboot这是一个配置类
    配置类本身也是一个组件
    proxyBeanMethods =true 代理方法
        Full(proxyBeanMethods =true)、Lite(proxyBeanMethods =false)(每次访问都不一样)
    @Configuration(proxyBeanMethods =true)(每次访问都是IOC里面的配置)代理对象调用方法。springboot总会检查这个组件是否在容器中
    保持组件单实例
   */
public class MyConfig {
   
        /**
         * 外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
         * **/
    @Bean//给容器中添加组件,以方法名作为组件id 返回类型就是组件类型。 返回对象就是组件容器中的实例(默认为单例)
    public User user01(){
   
        User Zhangsan=new User("zhangsan",18);
        Zhangsan.setPet(tomcat());
        return Zhangsan;
    }
    @Bean("tom")//括号里面为自定义名字(默认名字是方法名)
    public Pet tomcat(){
   

        return  new Pet("12"); 
        
    }
}

在main方法测试(提前在User类里加入了Pet属性)

 User user01=run.getBean("user01", User.class);
Pet tom=  run.getBean("tom",Pet.class);
  user01.getPet();
 // Full(proxyBeanMethods =true)(配置类组件之间有依赖关系,方法会被调用得到之前单例组件)
  //Lite(proxyBeanMethods =false)(配置组件之间无依赖关系用Lite模式加速容器启动的过程,减少判断)
  System.out.println("用户宠物"+(user01.getPet()==tom));

Import注解(给容器中自动创建出这类型的组件)

/* @Import给容器中自动创建出这两个类型的组件
默认组件的名字就是全类名*/
@Import({
   User.class , DBHelper.class})
@Conditional条件装配

@Conditional的关系树(在满足某种条件或者不满足某种条件创建组件等方法 可以使用在类前面)

在这里插入图片描述

在这里插入图片描述

我们在main方法里面尝试拿取一下组件

在这里插入图片描述

运行结果

在这里插入图片描述

@ImportResource("classpath:beans.xml")可以导入以前xml的配置方式

我在spring.xml里面创建了一个组件如果直接拿那么结果是false因为springboot不知道它是是什么

如果在任何一个类上面加入@ImportResource(“classpath:beans.xml”)那么他会自动解析里面的组件放入springboot

<bean id="hh" class="com.springboot.bean.User">
    <property name="name" value="12"></property>
    <property name="age" value="11"></property>
</bean>
@ImportResource("classpath:beans.xml")//可以导入以前xml的配置方式
配置绑定

第一种在实例类上加上

prefix是前缀代表着前缀里面的属性和car里面的属性一致

@Component加入ioc容器

Car实例类

package com.springboot.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/*
* 只有在放在容器中才会生效
* */
@Component
@ConfigurationProperties(prefix = "mycard")
public class Car {
   
    private String brand;
    private Integer price;



    public String getBrand() {
   
        return brand;
    }

    public void setBrand(String brand) {
   
        this.brand = brand;
    }

    public Integer getPrice() {
   
        return price;
    }

    public void setPrice(Integer price) {
   
        this.price = price;
    }

    @Override
    public String toString() {
   
        return "Car{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
}

主配置文件

mycard.brand=BM
mycard.price=10000

测试

HelloController

使用自动装配

package com.springboot.controller;

import com.springboot.bean.Car;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/*@ResponseBody(告诉springboot直接返回给浏览器)
@Controller*/
@RestController//就是@ResponseBody和@Controller
public class HelloController {
   


    @Autowired
    Car car;
    @RequestMapping("/card")
    public Car car(){
   
    return car;
    }
}

测试结果

在这里插入图片描述

第二种方法:因为我们可能引入的car为第三方的无法加入@Component导致无法导入配置文件

使用@EnableConfigurationProperties+@ConfigurationProperties(开启car配置绑定功能
把car这个组件自动注册到容器中)@EnableConfigurationProperties在主配置文件类使用

@EnableConfigurationProperties(Car.class)

运行结果

在这里插入图片描述

自动配置原理

引导加载自动装配
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {
   @Filter(
    type = FilterType.CUSTOM,
    classes = {
   TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {
   AutoConfigurationExcludeFilter.class}
)}
)

1.@SpringBootConfiguration:

​ Configuration代表这当前是一个配置类

2.@ComponentScan(指定扫面哪些注解)

3.@EnableAutoConfiguration

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

@AutoConfigurationPackage 自动配置包(指定了默认的包规则

@Import({
   Registrar.class})
//利用Registrar给容器种导入一系列组件
//将指定的包下的所有组件导入进来MainApplication所在的报下

@Import({AutoConfigurationImportSelector.class})

1.利用this.getAutoConfigurationEntry(annotationMetadata);给容器中批量导入一些组件
 2.    List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);获取到所有需要导入到容器中的配置类
  3.例如工厂加载
    List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader)得到组件
 4.从META-INF/spring.factories位置来加载一个文件
    默认扫面我们当前系统里所有MET-INF/spring.factories位置的文件

在这里插入图片描述

这些组件在xml中已经写死了

在这里插入图片描述

按需开启自动配置项

1.当我们导入相关的jar包才会开启相应的组件

2.springboot会预先加载配置类

3.每个自动配置类按照条件生效

4.生效的配置类就会给容器中装配很对组件

5.只要容器中有这些组件,就相当于这些功能有了

6.只要用户有自己配置的,就以用户的优先

​ xxxxAutoConfiguration–>组件–>xxxProperties里面拿值—>application.properties

实战

引入场景依赖

https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot

查看自动配置了那些

​ 自己分析,引入场景对应的配置一般都会生效

​ 配置文件中的debug=true开启自动配置报告 Negative(不生效)

是否修改配置项

​ 参照文档修改配置项

​ https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#common-application-properties

​ 自己查看分析xxxproperties绑定了配置文件的那些

自定义加入或替换组件

Lombok(javaben简化开发)

pom.xml中引入配置

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

再idea软件市场下载lombok插件

在这里插入图片描述
搜索插件里面搜索lombok

再javabean中删除set/get方法再类上加入lombok的Data的注解

如果需要定制全参构造自己写就好

package com.springboot.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor//无参构造
@Data//set/get方法
@AllArgsConstructor//全参构造
public class User {
   
    private String name;
    private int age;
    private Pet pet;


    public  User(String name,Integer age){
   
        this.name=name;
        this.age=age;
    }


}

controller类

package com.springboot.controller;

import com.springboot.bean.Car;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/*@ResponseBody(告诉springboot直接返回给浏览器)
@Controller*/
@RestController//就是@ResponseBody和@Controller
@Slf4j//(日志注解提供方法log.info)
public class HelloController {
   


    @Autowired
    Car car;
    @RequestMapping("/card")
    public Car car(){
   
        log.info("请求");
        return car;
    }
}

运行结果

在这里插入图片描述

dev-tools(开发者工具)

作用:如果后台文件或者代码发生改变会重启如果是静态资源则不会重启

<!--devtools日更新 更改前端页面无需每次刷新ctrl+f9即可实时生效(自动重启)-->

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

spring Initailizr(项目初始化)

再创建新项目时选择spring Initailizr

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

导入了依赖

在这里插入图片描述

springBOOT核心功能

配置文件(yaml)

YAML是"YAML Ain’t Markup Language”(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML的意思其实是:“Yet Another Markup Language”(仍是一种标记语言)。

非常适合来做以数据为中心的配置文件

基本语法

key:value; kv 之间有空格

大小写敏感

使用缩进便是层级关系

缩进不允许使用tab,只允许空格

缩进的空格数不重要,只要同层级的元素左对齐即可

‘#’代表注释

"与"表示字符串内容 会被 转义/不转义

数据类型

​ 字面量:单个的、不可在分值。date boolean string number null

​ k: v

对象:键值对的集合 map hash set object

Person类(再pom.xml中引入了lombok使用@Data和@ToString再用@Component放入容器)@ConfigurationProperties(prefix = “person”)(使用前缀引入配置文件)

package com.springinitailizr.boot01.bean;

import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

@ConfigurationProperties(prefix = "person")
@Component
@Data
@ToString
public class Person {
   
    private String userName;
    private boolean boss;
    private Date birth;
    private Integer age;
    private String[] interests;
    private List<String> animal;
    private Map<String,Object> score;
    private Set<Double> salarys;
    private Map<String , List<Pet>> allPets;
}

Pet

package com.springinitailizr.boot01.bean;

import lombok.Data;
import lombok.ToString;

@Data
@ToString
public class Pet {
   
    private String name;
    private Double weight;
}

application.yaml(后缀为yml也可以)

person:
   #字面量书写格式
  userName: "zs \n ls"
  #单引号会将\n作为字符串输出
  #双引号会将\n作为换行输出
  boss: true
  birth: 2019/2/19
  age: 18
  #数组的两种书写格式
  #interests: [篮球,足球]
  interests:
    - 篮球
    - 足球
    - 18
    #List集合书写格式
  animal: [阿毛,阿狗]
  #Map集合书写的两种格式
#  score:
#    english: 80
#    math: 90
  score: {
   english: 80,math: 90}
  #Set集合的书写方式(和数组书写方式一样)
  salarys:
    - 999
    - 9998
    #对象属性的书写格式
  pet:
    name: 阿狗
    weight: 99
  #Map<String,List<Pet>>v是集合 书写格式
  allPets:
    sick:
      - {
   name: 阿狗,weight: 99.99}
      - {
   name: 阿2,weight: 99.99}
      - name:weight: 75.1

    health:
      - {
   name: 阿黑,weight: 199}
      - {
   name:, weight: 200}

双引号拿Person取值

在这里插入图片描述

单引号拿取Person名字的值

在这里插入图片描述

yaml配置提示功能以及排除processor被打包

添加依赖

<!--yaml依赖(配置yaml时有代码提示)-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

 <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes> 
                        <!--打包插件不会把processor打包-->
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

提示效果:
在这里插入图片描述

Web开发

静态资源访问

​ 1.静态资源目录

只要静态资源放在类路径下/static(or/publicor/resourcesor/META-INF/resources)

访问:当前项目的根路径/+静态资源名

原理:静态资源映射/**

请求进来先去controller处理,如不能处理则所有请求再交给静态资源。如果静态资源也找不到则404

​ 2.静态资源访问前缀

​ 默认无前缀

配置前缀后访问路径 项目名/res/静态资源名

再yaml下配置

#静态资源前缀
spring:
  mvc:
    static-path-pattern: /res/**
    #改变默认静态资源目录
  web:
    resources:
      static-locations: classpath:/bbb/

3.webjar(把一些常用的CSS、js的静态资源打成jar包只需要引用依赖则课访问它的静态资源)(官网链接:https://www.webjars.org/)

在这里插入图片描述

再pom.xml中引入依赖然后重启项目进行访问:

http://localhost:8080/webjars/jquery/3.6.0/jquery.js 后面的地址要按照包路径进行访问

运行结果

在这里插入图片描述

欢迎页面

1.给静态资源路径下方一个index.html

​ 可以配置静态资源路径

​ 但是不可以配置静态资源的访问前缀。否则导致index.html不能被默认访问

#静态资源前缀(会导致默认页面无法访问)
spring:
  mvc:
    static-path-pattern: /res/**
    #改变默认静态资源目录
  web
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

洛尘 programmer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值