主頁 > 後端開發 > SpringBoot

SpringBoot

2023-02-17 06:37:17 後端開發

一. Spring Boot 

1.1 Spring Boot 概述

1.1.1 什么是Spring Boot

Spring Boot是Spring專案中的一個子工程,與我們所熟知的Spring-framework 同屬于spring的產品:

其最主要作用就是幫助開發人員快速的構建龐大的spring專案,并且盡可能的減少一切xml配置,做到開箱即用,迅速上手,讓開發人員關注業務而非配置,

主要特點:

  1. 自動配置 : 不需要再關注各個框架的整合配置, springboot全部已經配置好了
  2. 起步依賴 : 我們在需要使用某個框架的時候, 直接添加這個框架的啟動器依賴即可 , 不需要在關注jar包的沖突和整合

設計目的: 用來簡化 Spring 應用的初始搭建以及開發程序,

從最根本上來講,Spring Boot 就是一些庫的集合,它能夠被任意專案所使用,它使用 “習慣優于配置”的理念讓你的專案快速運行起來,spring boot 其實不是什么新的框架,它默認配置了很多框架的使用方式,就像 maven 整合了所有的 jar 包,spring boot 整合了所有的框架,總結一下及幾點:

(1)為所有 Spring 開發提供一個更快更廣泛的入門體驗,

(2)零配置,無冗余代碼生成和XML 強制配置,遵循“約定大于配置” ,

(3)集成了大量常用的第三方庫的配置, Spring Boot 應用為這些第三方庫提供了幾乎可以零配置的開箱即用的能力,

(4)提供一系列大型專案常用的非功能性特征,如嵌入服務器等,

使用 Spring Boot有什么好處:

其實就是簡單快速方便

平時如果我們需要搭建一個 Spring Web 專案的時候需要怎么做呢?

  • 1)配置 web.xml,加載 Spring 和 Spring mvc
  • 2)配置資料庫連接、配置 Spring 事務
  • 3)配置加載組態檔的讀取,開啟注解
  • 4)配置日志檔案
  • 配置完成之后部署 Tomcat 除錯

1.1.2 Spring Boot的優勢

使用Java開發程式 , 一直困擾我們的就是臃腫、麻煩,搭建專案的程序相當復雜 , 我們需要考慮很多問題 , 主要的問題有如下兩點 :

  1. 復雜的配置
  2. 混亂的依賴管理

Spring Boot幫我們解決了這個些, 我們在使用Spring Boot開發時, 不需要關注各種復雜的整合配置 , 也不用關注各個庫之間的依賴及沖突問題 , Spring Boot已經默認幫我們整合配置好了 !

節省了大量的配置及依賴調整時間, 讓我們能夠把時間用在刀刃上, 專注業務邏輯的開發,

1.2 Spring Boot 快速入門

下面,我們就利用Spring Boot搭建一個web工程,體會一下Spring Boot的魅力所在!

1.2.1 需求

需求:訪問 http://localhost:8080/hello輸出 “Hello Spring Boot”

1.2.2 步驟

  1. 創建Maven工程
  2. 添加依賴(springboot父工程依賴 , web啟動器依賴)
  3. 撰寫啟動引導類(springboot專案運行的入口)
  4. 撰寫處理器Controller
  5. 啟動專案

1.2.3 實作

創建專案: springboot_01

1.2.3.1 創建工程

1.2.3.2 添加依賴

SpringBoot可以幫我們方便的管理專案依賴 , 在Spring Boot提供了一個名為**spring-boot-starter-parent**的工程,里面已經對各種常用依賴的版本進行了管理,我們的專案需要以這個專案為父工程,這樣我們就不用操心依賴的版本問題了,需要什么依賴,直接引入坐標(不需要添加版本)即可!

  1. 添加父工程坐標

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.2.2.RELEASE</version>

</parent>

  1. 添加web啟動器

為了讓Spring Boot幫我們完成各種自動配置,我們必須引入Spring Boot提供的自動配置依賴,我們稱為啟動器,因為我們是web專案,這里我們引入web啟動器,在 pom.xml 檔案中加入如下依賴:

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

</dependencies>

需要注意的是,我們并沒有在這里指定版本資訊 , 當我們添加好啟動器之后我們發現專案中已經依賴了大量的Jar包

  1. 配置JDK版本

<properties>

<java.version>1.8</java.version>

</properties>

思考: 為什么我們這里僅僅配置了這么一個變數 , 專案的JDK版本就會改變呢 ?

因為jdk插件已經在父工程中定義好了 , 默認會讀取${java.version}變數值

  1. 完整的pom.xml檔案

配置完畢之后完整的**pom.xml**組態檔如下所示

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.2.2.RELEASE</version>

</parent>

 

<groupId>com.atguigu</groupId>

<artifactId>springboot_01</artifactId>

<version>1.0-SNAPSHOT</version>

<properties>

<java.version>1.8</java.version>

</properties>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

</dependencies>

</project>

1.2.3.3 創建啟動類

Spring Boot專案通過main函式即可啟動,我們需要創建一個啟動類:

package com.atguigu;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class,args);

}

}

1.2.3.4 撰寫controller

package com.atguigu.controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class HelloController {

@RequestMapping("/hello")

public String sayHello(){

return "hello spring boot!!" ;

}

}

1.2.3.5 啟動測驗

運行啟動類的main方法 :

控制臺會輸出如下資訊 :

通過輸出的日志我們知道了以下資訊 :

  1. 監聽的埠是8080
  2. 專案的背景關系路徑是""

打開瀏覽器,訪問:http://localhost:8080/hello

1.3 Spring Boot 入門 – 思考

問題1:

為什么我們在添加啟動器的時候不需要在啟動器的坐標中指定版本?

答案:因為我們指定了專案的父工程,在spring-boot-starter-parent中已經通過Maven的版本鎖定了Jar包的版本,所以就不需要再指定了,

問題2:

為什么我們就添加一個啟動器依賴,專案就可以運行起來了,運行專案所需要的Jar包從何而來?

答案:因為我們添加了這個啟動器的依賴,它已經把自己運行所需要的必要包集成在這個啟動器中,通過Maven的依賴傳遞性,將這些包都依賴到咱們的專案里了,

點擊專案右鍵 open module settings

1.4 組態檔詳解

springboot支持二種型別的組態檔

  • properties屬性組態檔
  • yaml組態檔

組態檔必須放置在專案的類加載目錄下, 并且名字必須是application

springboot專案在運行的時候會自動加載這些組態檔

同級目錄下打開:spring-configuration-metadata.json

搜素:server.port

為什么可以在resources下創建application.properties檔案呢?我們查看springboot的啟動依賴:

點擊spring-boot-starter-parent

1.4.1 屬性組態檔

在 resource 檔案夾下面新建 application.properties 組態檔

spring.jdbc.datasource.driverClassName=com.mysql.jdbc.driver

spring.jdbc.datasource.url=jdbc:mysql:///springboot_01

spring.jdbc.datasource.username=root

spring.jdbc.datasource.password=root

新建 properties 包,創建類 DataSourceProperties

package com.atguigu.properties;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;

@Component

public class DataSourceProperties {

@Value("${spring.jdbc.datasource.driverClassName}")

private String driverClassName;

@Value("${spring.jdbc.datasource.url}")

private String url;

@Value("${spring.jdbc.datasource.username}")

private String username;

@Value("${spring.jdbc.datasource.password}")

private String password;

// 生成get set 和 toString方法

}

在 controller 添加 sayHello2 方法

package com.atguigu.controller;

import com.atguigu.properties.DataSourceProperties;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class HelloController {

@Autowired

private DataSourceProperties dataSourceProperties ;

 

@RequestMapping(path = "/hello")

public String sayHello() {

System.out.println(dataSourceProperties);

return "Hello Spring Boot ! " ;

}

}

請求地址:http://localhost:8080/hello

控制臺列印:

DataSourceProperties{driverClassName='com.mysql.jdbc.Driver', url='jdbc:mysql:///springboot_01', username='root', password='root'}

1.4.2 YAML組態檔

何謂YAML?

? YAML是一種組態檔格式

基本格式:

語法 :

1.資料結構用樹形結構呈現,通過縮進來表示層級,

2.連續的專案通過減號 ” - ” 來表示

3.鍵值結構里面的key/value對用冒號 ” : ” 來分隔,

4.YAML組態檔的擴展名是yaml 或 yml

在 resource 檔案夾下面新建 application.yml 組態檔,修改 application.properties 組態檔名字為 application.properties.bak

spring:

jdbc:

datasource:

driverClassName: com.mysql.jdbc.Driver

url: jdbc:mysql:///springboot_01

username: root

password: root

運行專案,重新請求 http://localhost:8080/hello

yml組態檔的特征:

  1. 樹狀層級結構展示配置項;
  2. 配置項之間如果有關系的話需要分行,空兩格;
  3. 配置項如果有值的話,那么需要在 :之后空一格再寫配置項值;

yaml與properties組態檔除了展示形式不相同以外,其它功能和作用都是一樣的

1.4.3 多環境profile切換配置

我們剛剛說過在Spring Boot專案中組態檔的名稱只能是**application** , 如果我們把所有的配置全都寫在一個組態檔中如果配置項比較多, 組態檔就會顯得比較復雜和臃腫 ! 不利于后期的專案維護和開發

例如下面幾個場景 :

1.因為開發環境的變化, 我們需要修改組態檔中某一個配置項的值(比如之前是mysql資料庫,切換成oracle資料庫)

2.專案開發完成需要上線了 , 需要把一些環境修改成正式環境(開發測驗上線,多環境切換)

解決方案 :使用profiles拆分配置

spring boot專案中允許使用多個YAML組態檔,

這些檔案名稱必須為application-***.yml,并且在application.yml中激活,

創建application-dev.yml檔案如下:

# 配置資料庫連接池資訊 ,開發環境

spring:

jdbc:

datasource:

driverClassName: com.mysql.jdbc.Driver

url: jdbc:mysql:///springboot

username: root

password: root

創建application-pro.yml檔案如下:

# 配置資料庫連接池資訊,上線環境

spring:

jdbc:

datasource:

driverClassName: com.mysql.jdbc.Driver

url: jdbc:mysql:///business

username: business

password: business

在 application.yml 檔案中添加如下配置:

# 激活組態檔

spring:

profiles:

active: dev

直接運行專案:http://localhost:8080/hello

列印結果:

DataSourceProperties{driverClassName='com.mysql.jdbc.Driver', url='jdbc:mysql:///springboot', username='root', password='root'}

修改 application.yml 組態檔:

# 激活組態檔

spring:

profiles:

active: pro

列印結果:

DataSourceProperties{driverClassName='com.mysql.jdbc.Driver', url='jdbc:mysql:///business', username='business', password='business'}

注意 :

如果properties和yml檔案都存在,不存在spring.profiles.active設定,如果有重疊屬性,默認以properties優先,

如果設定了spring.profiles.active,并且有重疊屬性,以active設定優先,

可以在兩種檔案中分別增加server.port屬性指定不同的埠,啟動專案查看控制臺埠號進行測驗,

二. Spring Boot 自動配置(理解)

2.1 @ConfigurationProperties注解

@ConfigurationProperties是SpringBoot提供的重要注解, 他可以將一些配置屬性**批量**注入到bean物件,

application.yml組態檔

spring:

jdbc:

datasource:

driverClassName: com.mysql.jdbc.driver

url: jdbc:mysql:///springboot_01

username: root

password: root

DataSourceProperties.java

public class DataSourceProperties {

private String driverClassName;

private String url;

private String username;

private String password;

 

// 省略getter和setter.....

}

方式一 : 使用@Value一個個注入

這種注入方式,如果屬性特別多,一個一個注入太麻煩啦o(╥﹏╥)o

@Component

public class DataSourceProperties {

@Value("${spring.jdbc.datasource.driverClassName}")

private String driverClassName;

@Value("${spring.jdbc.datasource.url}")

private String url;

@Value("${spring.jdbc.datasource.username}")

private String username;

@Value("${spring.jdbc.datasource.password}")

private String password;

// 省略getter和setter.....

}

方式二 : 使用@ConfigurationProperties批量注入

這種注入方式,屬性再多,只要按照規則就可以一次性自動注入,方便的很哦\(^o^)/~

package com.atguigu.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.stereotype.Component;

@Component

@ConfigurationProperties(prefix = "spring.jdbc.datasource")

public class DataSourceProperties2 {

private String driverClassName;

private String url;

private String username;

private String password;

 

// 省略getter和setter.....

}

 

  • 在類上通過@ConfigurationProperties注解宣告該類要讀取屬性配置
  • prefix="spring.jdbc.datasource" 讀取屬性檔案中前綴為spring.jdbc.datasource的值,前綴和屬性名稱和組態檔中的key必須要保持一致才可以注入成功
  • Spring Boot默認讀取application.properties屬性檔案

開啟@ConfigurationProperties注解使用

@Controller

@EnableConfigurationProperties(DataSourceProperties2.class)

public class HelloController {

 

@Autowired

private DataSourceProperties2 dataSourceProperties2 ;

@RequestMapping(path = "/hello")

@ResponseBody

public String sayHello(){

System.out.println(dataSourceProperties2);

return "hello spring boot";

}

}

使用@EnableConfigurationProperties(DataSourceProperties2.class),開啟DataSourceProperties2身上的@ConfigurationProperties注解 , 他就會生效了, 就會幫助我們注入資料了

請求地址:http://localhost:8080/hello

列印結果:

DataSourceProperties2{driverClassName='com.mysql.jdbc.Driver', url='jdbc:mysql:///springboot_01', username='root', password='root'}

報錯提示,請在pom檔案添加配置資訊

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-configuration-processor</artifactId>

<optional>true</optional>

</dependency>

2.2 @SpringBootApplication注解

  • @SpringBootConfiguration : 代表這個類就是一個配置類 , 本質上就是一個@Configuration注解
  • @ComponentScan : 組件掃描, 默認掃描啟動類所在包及子包下的類身上的注解
  • @EnableAutoConfiguration : 自動配置注解 , 添加了此注解會自動去讀取spring.factories組態檔中的自動配置類

2.3 條件化配置注解

我們看到自動配置類上有一些ConditionalXxxx注解 , 這些注解的作用就是進行條件化選擇

所謂條件化選擇就是如果滿足條件, 該配置類就生效, 如果不滿足該配置類就不生效

常用的條件化選擇注解如下 :

注解

作用

@ConditionalOnBean

如果存在某個Bean, 配置類生效

@ConditionalOnMissingBean

如果不存在某個Bean, 配置類生效

@ConditionalOnClass

如果存在某個類, 配置類生效

@ConditionalOnMissingClass

如果不存在某個類, 配置類生效

@ConditionalOnProperty

如果存在某個屬性配置, 配置類生效

@ConditionalOnWebApplication

如果是一個web應用, 配置類生效

@ConditionalOnNotWebApplication

如果不是一個web應用, 配置類生效

因為我們配置了DispatcherServlet 滿足上面定義的條件, 所以WebMvcAutoConfiguration會生效 , 那么WebMvcAutoConfiguration自動配置類中幫我們配置了什么呢 ?

視圖決議器

處理器配接器(HandlerAdapter)

這些配置都是我們之前在學習SpringMVC時需要自己配置的 , 現在Spring Boot框架都已經提前幫我們配置好了 , 所以我們才能使用的那么方便

2.4 自動配置原理

2.4.1 加載spring.factories

在**SpringApplication**類構建的時候,有這樣一段初始化代碼:

跟進去往下走

這里發現會通過loadFactoryNames嘗試加載一些FactoryName,然后利用createSpringFactoriesInstances將這些加載到的類名進行實體化, 繼續跟進loadFactoryNames方法:

發現此處會利用類加載器加載一個檔案: META-INF/spring.factories ,我們知道,ClassLoader默認是從classpath下讀取檔案,因此,SpringBoot會在初始化的時候,加載所有classpath:META-INF/spring.factories檔案,包括jar包當中的,而在Spring的一個依賴包:spring-boot-autoconfigure中,就有這樣的檔案:

我們引入的任何第三方啟動器,只要實作自動配置,也都會有類似檔案,

2.4.2 讀取自動配置類

我們打開**spring.factories**檔案

可以發現以EnableAutoConfiguration介面為key的一系列配置,key所對應的值,就是所有的自動配置類,可以在當前的jar包中找到這些自動配置類:

幾乎涵蓋了現在主流的開源框架 , 我們來看一個我們熟悉的,例如SpringMVC,查看mvc 的自動配置類:

打開WebMvcAutoConfiguration

2.4.3 默認屬性配置

配置類我們找到了 , 那么這些默認配置的屬性來自哪里呢?

例如 : 我們配置視圖決議器的時候需要配置前綴和后綴 , 那么這些配置在哪配置的呢 ?

通過原始碼發現, 這個配置是從this.mvcProperties.getView()中讀取的 ,this.mvcProperties又是什么呢 ? 我們繼續跟蹤,發現其實就是定義的一個變數

這個變數中又有一個View型別的變數 , 這個變數中配置的就是前綴和后綴

View中的原始碼如下 :

可以看到, 默認讀取就是這里的前綴和后綴變數的值 , 默認就是null .

2.4.4 覆寫默認屬性配置

如果我們想自己指定視圖的前綴和后綴該如何去做呢 ?

我們再看WebMvcAutoConfiguration這個類的宣告, 發現這個類身上有這么一個注解, 我們之前也使用過 , 引入了二個配置物件 , 所以我們知道下面成員位置的WebMvcProperties這個成員變數 , 就是從這里來的

我們再進去看看這兩個配置類 , 配置類身上使用ConfigurationProperties讀取配置,前綴是spring.mvc , 所以如果我們在組態檔中配置spring.mvc前綴開頭的配置 , 是不是就可以將自己配置的資料注入到這個物件的屬性中 !

所以如果想要自己設定視圖前綴和后綴就可以這么配置

# 激活組態檔

spring:

mvc:

view:

prefix: /WEB-INF/

suffix: .jsp

修改服務器埠 :

server:

port: 10000

2.5 自定義啟動器

2.5.1 需求介紹

定義一個連接池啟動器 , 當用戶引入了連接池啟動依賴之后 , 專案中就已經自動配置了連接池

2.5.2 步驟分析

  1. 創建啟動器專案
  2. 添加啟動器相關依賴
  3. 創建屬性配置類
  4. 創建自動配置類
  5. 撰寫自動組態檔(**spring.factories**)
  6. 使用自定義的啟動器

2.5.3 代碼實作

2.5.3.1 創建專案并引入依賴

創建專案 spring-boot-jdbc-starter

引入依賴

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.2.2.RELEASE</version>

</parent>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<java.version>1.8</java.version>

</properties>

<dependencies>

<!--引入spring‐boot‐starter;所有starter的基本配置-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter</artifactId>

</dependency>

<!--自動配置連接池-->

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>druid</artifactId>

<version>1.1.12</version>

</dependency>

<dependency>

<groupId>c3p0</groupId>

<artifactId>c3p0</artifactId>

<version>0.9.1.2</version>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-configuration-processor</artifactId>

<optional>true</optional>

</dependency>

</dependencies>

2.5.3.2 創建屬性配置類

package com.atguigu.autoconfig;

import org.springframework.boot.context.properties.ConfigurationProperties;

@Component

@ConfigurationProperties(prefix = "spring.jdbc.datasource")

public class DataSourceProperties {

private String driverClassName ;

private String url;

private String username;

private String password;

// 生成set get toString方法

}

 

2.5.3.3 創建自動配置類

package com.atguigu.autoconfig;

import com.alibaba.druid.pool.DruidDataSource;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.context.properties.EnableConfigurationProperties;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@SpringBootConfiguration

@EnableConfigurationProperties(DataSourceProperties.class)

public class DataSourceAutoConfiguration {

@Autowired

private DataSourceProperties dataSourceProperties ;

@Bean

public DataSource createDataSource(){

DruidDataSource dataSource = new DruidDataSource();

dataSource.setDriverClassName(dataSourceProperties.getDriverClassName());

dataSource.setUrl(dataSourceProperties.getUrl());

dataSource.setUsername(dataSourceProperties.getUsername());

dataSource.setPassword(dataSourceProperties.getPassword());

return dataSource;

}

}

2.5.3.4 撰寫自動配置屬性檔案

在 resource 檔案夾下面新建 META-INF/spring.factories

# Auto Configure

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.atguigu.autoconfig.DataSourceAutoConfiguration

做完了之后注意要執行install , 安裝專案

2.5.3.5 使用自定義啟動器

在 springboot_01 專案當中引入依賴

<dependency>

<groupId>com.atguigu</groupId>

<artifactId>spring-boot-jdbc-starter</artifactId>

<version>1.0-SNAPSHOT</version>

</dependency>

配置連接池資訊

新建 application-datasource.yml

spring:

jdbc:

datasource:

driverClassName: com.mysql.jdbc.Driver

url: jdbc:mysql:///springboot_01

username: root

password: root

激活組態檔 application.yml

# 激活組態檔

spring:

profiles:

active: datasource

注入連接池, 查看連接池屬性

package com.atguigu.controller;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.context.properties.EnableConfigurationProperties;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;

@RestController

public class HelloController {

@Autowired

private DataSource dataSource ;

@RequestMapping(path = "/hello")

public String sayHello() {

System.out.println(dataSource.getClass());//列印DruidDataSource資料源

return "Hello Spring Boot ! " ;

}

}

 

2.5.4 多種資料源

如果想讓我們的啟動器支持多種資料源, 例如 : C3P0和Druid , 根據配置進行選擇 , 就可以使用條件選擇進行實作,例如 : 如下配置中, 有二個創建連接池的配置, 一個是C3P0 , 一個是Druid ,如何能夠根據組態檔自動選擇呢 ?

修改組態檔 application-datasource.yml

spring:

jdbc:

datasource:

driverClassName: com.mysql.jdbc.Driver

url: jdbc:mysql:///springboot_01

username: root

password: root

type: druid # 資料源型別

  • 如果組態檔中配置了spring.jdbc.datasource.type=c3p0使用c3p0資料源
  • 如果組態檔中配置了spring.jdbc.datasource.type=druid使用druid資料源

在專案 spring-boot-jdbc-starter , 添加創建 c3p0 方法

package com.atguigu.autoconfig;

import com.alibaba.druid.pool.DruidDataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.context.properties.EnableConfigurationProperties;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration

@EnableConfigurationProperties(DataSourceProperties.class)

public class DataSourceAutoConfiguratioin {

@Autowired

private DataSourceProperties dataSourceProperties ;

@Bean

@ConditionalOnProperty(value = "https://www.cnblogs.com/ygstudy/p/spring.jdbc.datasource.type",havingValue = "https://www.cnblogs.com/ygstudy/p/druid")

public DataSource createDataSource(){

DruidDataSource dataSource = new DruidDataSource();

dataSource.setDriverClassName(dataSourceProperties.getDriverClassName());

dataSource.setUrl(dataSourceProperties.getUrl());

dataSource.setUsername(dataSourceProperties.getUsername());

dataSource.setPassword(dataSourceProperties.getPassword());

return dataSource;

}

@Bean

@ConditionalOnProperty(value = "https://www.cnblogs.com/ygstudy/p/spring.jdbc.datasource.type",havingValue = "https://www.cnblogs.com/ygstudy/p/c3p0")

public DataSource createC3P0DataSource() throws Exception{

ComboPooledDataSource dataSource = new ComboPooledDataSource();

dataSource.setDriverClass(dataSourceProperties.getDriverClassName());

dataSource.setJdbcUrl(dataSourceProperties.getUrl());

dataSource.setUser(dataSourceProperties.getUsername());

dataSource.setPassword(dataSourceProperties.getPassword());

return dataSource;

}

}

我們可以使用條件選擇實作 , 如下圖所示

@ConditionalOnProperty(value = "https://www.cnblogs.com/ygstudy/p/spring.jdbc.datasource.type",havingValue = "https://www.cnblogs.com/ygstudy/p/druid")

install 安裝 spring-boot-jdbc-starter , 運行 springboot_01

修改組態檔 ,重新安裝,再次請求

三. Spring Boot常用啟動器(掌握)

3.1 SpringBoot整合MVC

創建專案 springboot_02_mvc

3.1.1 起步依賴

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.2.2.RELEASE</version>

</parent>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

</dependencies>

① 新建入口程式類 Application

package com.atguigu;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class,args);

}

}

② 新建 javabean

package com.atguigu.pojo;

public class User {

private String username ;

private String password ;

private Integer age ;

private String sex ;

③ 新建 UserController

package com.atguigu.controller;

import com.atguigu.pojo.User;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;

import java.util.List;

@Controller

@RequestMapping(path = "/user")

public class UserController {

@RequestMapping(path = "/findAll")

@ResponseBody

public List<User> findAll(){

//查詢所有

List<User> users = new ArrayList<User>();

User user1 = new User();

user1.setUsername("楊過");

user1.setPassword("123456");

user1.setAge(18);

user1.setSex("男");

User user2 = new User();

user2.setUsername("小龍女");

user2.setPassword("654321");

user2.setAge(18);

user2.setSex("女");

User user3 = new User();

user3.setUsername("尹志平");

user3.setPassword("666666");

user3.setAge(19);

user3.setSex("女");

users.add(user1);

users.add(user2);

users.add(user3);

return users ;

}

}

運行程式

3.1.2 靜態資源目錄

在WEB開發中我們經常需要引入一些靜態資源 , 例如 : HTML , CSS , JS , 圖片等 , 如果是普通的專案靜態資源可以放在專案的webapp目錄下

現在使用Spring Boot做開發 , 專案中沒有webapp目錄 , 我們的專案是一個jar工程,那么就沒有webapp,我們的靜態資源該放哪里呢?

在springboot中有一個叫做ResourceProperties的類,里面就定義了靜態資源的默認查找路徑:

默認的靜態資源路徑為:

  • classpath:/META-INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public

我們只要靜態資源放在這些目錄中任何一個,SpringMVC都會幫我們處理, 我們習慣會把靜態資源放在classpath:/static/ 目錄下,在resources目錄下創建index.html檔案

打開瀏覽器輸入 : http://localhost:8080/index.html

覆寫路徑

如果想要修改默認的靜態資源路徑, 配置如下 :

新建 application.yml

spring:

resources:

static-locations: classpath:/webapp/

請求地址 http://localhost:8080/index.html

3.1.3 自定義攔截器

web開發中的攔截器也是我們經常需要使用的組件,可以幫我們完成一些日志記錄 , 資料過濾 , 請求過濾等等很多功能,那么在SpringBoot中該如何配置呢?

回顧一下SpringMVC中配置攔截器的步驟 :

  1. 撰寫一個攔截器(實作HandlerInterceptor介面)
  2. 注冊攔截器(mvc:interceptors)

springmvx.xml

<!--配置攔截器-->

<mvc:interceptors>

<mvc:interceptor>

<!--配置攔截路徑-->

<mvc:mapping path="/user/**"/>

<!--配置不攔截路徑:不攔截路徑是指從攔截路徑中排除-->

<mvc:exclude-mapping path="/user/sayByby"></mvc:exclude-mapping>

<!--配置攔截器bean-->

<bean class="com.atguigu.interceptor.LogInterceptor2"></bean>

</mvc:interceptor>

</mvc:interceptors>

因為SpringBoot沒有XML組態檔了 , 所以在SpringBoot中使用攔截器的注冊攔截器的方式就不太一樣了, 需要借助一個WebMvcConfigurer類幫助我們注冊攔截器 , 實作攔截器的具體步驟如下 :

  1. 撰寫一個攔截器
  2. 通過WebMvcConfigurer注冊攔截器

撰寫攔截器

package com.atguigu.interceptor;

import org.springframework.stereotype.Component;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@Component

public class MyInterceptor implements HandlerInterceptor {

@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

System.out.println("MyInterceptor攔截器的preHandle方法執行....");

return false;

}

@Override

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

System.out.println("MyInterceptor攔截器的postHandle方法執行....");

}

@Override

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

System.out.println("MyInterceptor攔截器的afterCompletion方法執行....");

}

}

注冊攔截器

package com.atguigu.config;

import com.atguigu.interceptor.MyInterceptor;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration

public class MvcConfig implements WebMvcConfigurer {

@Autowired

private MyInterceptor myInterceptor ;

/**

* /** 攔截當前目錄及子目錄下的所有路徑 /user/** /user/findAll /user/order/findAll

* /* 攔截當前目錄下的以及子路徑 /user/* /user/findAll

* @param registry

*/

@Override

public void addInterceptors(InterceptorRegistry registry) {

registry.addInterceptor(myInterceptor).addPathPatterns("/**");

}

}

打開瀏覽器,輸入 : http://localhost:8888/user/findAll

3.2 SpringBoot整合Spring Data JPA

新建專案 springboot_jpa

添加Spring Data JPA的起步依賴

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.2.2.RELEASE</version>

<relativePath/>

</parent>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<java.version>1.8</java.version>

</properties>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

<!-- springBoot JPA的起步依賴 -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<!-- MySQL連接驅動 -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

</dependency>

<!-- 配置使用redis啟動器 -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

</dependencies>

在application.yml中配置資料庫和jpa的相關屬性

logging:

level:

com.atguigu.dao: debug # 配置日志

spring:

datasource:

username: root

password: root

url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai

driver-class-name: com.mysql.cj.jdbc.Driver

jpa:

database: mysql

show-sql: true

generate-ddl: true

hibernate:

ddl-auto: update

naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy

server:

port: 18081

注意:Mysql8.x版本,連接時url需要指定時區,并且驅動類包名發生了變化,

創建物體配置物體

package com.atguigu.domain;

import javax.persistence.*;

@Entity

@Table(name = "user")

public class User{

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = "id")

private Long id;

@Column(name = "username")

private String username;

@Column(name = "password")

private String password;

@Column(name = "name")

private String name;

 

//此處省略setter和getter方法... ...

}

撰寫UserDao

package com.atguigu.dao;

import com.atguigu.domain.User;

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserDao extends JpaRepository<User,Long> {

}

撰寫service類

package com.atguigu.service;

import com.atguigu.domain.User;

import java.util.List;

public interface UserService {

List<User> findUsers();

User findUserById(Long id);

void saveUser(User user);

void updateUser(User user);

void deleteUserById(Long id);

}

package com.atguigu.service.impl;

import com.atguigu.dao.UserDao;

import com.atguigu.domain.User;

import com.atguigu.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.List;

@Service

public class UserServiceImpl implements UserService {

@Autowired

private UserDao userDao;

/**

* 查詢所有

* @return

*/

@Override

public List<User> findUsers() {

return userDao.findAll();

}

/**

* 根據id查詢

* @return

*/

@Override

public User findUserById(Integer id) {

return userDao.findById(id).get();

}

/**

* 保存

* @return

*/

@Override

public void saveUser(User user) {

userDao.save(user);

}

/**

* 更新

* @return

*/

@Override

public void updateUser(User user) {

userDao.save(user);

}

/**

* 根據id洗掉

* @return

*/

@Override

public void deleteUserById(Integer id) {

userDao.deleteById(id);

}

}

撰寫controller類

package com.atguigu.controller;

import com.atguigu.domain.User;

import com.atguigu.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController

@RequestMapping("/user")

public class UserController {

@Autowired

private UserService userService;

@RequestMapping("/findAll")

public List<User> findAll(){

return userService.findUsers();

}

}

撰寫主程式類

測驗運行,控制臺列印資訊

注意:

自動生成的表的存盤引擎是MyISAM,此引擎不支持事務,需要該為InnoDB,

創建hibernate.properties組態檔添加以下配置

hibernate.dialect.storage_engine=innodb

洗掉表重寫啟動服務器

四. SpringBoot綜合案例(應用)

4.2 環境搭建

4.2.1 資料庫準備

create database springboot character set utf8 ;

use springboot ;

CREATE TABLE `tb_user` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`name` varchar(20) NOT NULL,

`gender` varchar(5) DEFAULT NULL,

`age` int(11) DEFAULT NULL,

`address` varchar(32) DEFAULT NULL,

`qq` varchar(20) DEFAULT NULL,

`email` varchar(50) DEFAULT NULL,

`username` varchar(20) NOT NULL,

`phone` varchar(11) DEFAULT NULL,

PRIMARY KEY (`id`),

UNIQUE KEY `user_username_uindex` (`username`)

) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

INSERT INTO `tb_user` VALUES (1,'黃蓉','女',38,'桃花島','212223390222','[email protected]','huangrong','15600003333'),(2,'黃老邪','男',58,'湖北省武漢市','212223390','[email protected]','huanglaoxie','15872320405'),(3,'小龍女','男',18,'湖北省荊門市','212223390','[email protected]','xiaolongnv','15600004444'),(7,'楊過','男',30,'揚州','212223390','[email protected]','yangguo','15600005555');

4.2.2 創建專案及包結構

創建專案 springboot_case

4.2.3 匯入依賴

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.2.2.RELEASE</version>

</parent>

<dependencies>

<!--單元測驗啟動器-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

</dependency>

<!--通用mapper啟動器依賴-->

<dependency>

<groupId>tk.mybatis</groupId>

<artifactId>mapper-spring-boot-starter</artifactId>

<version>2.1.5</version>

</dependency>

<!--JDBC啟動器依賴-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-jdbc</artifactId>

</dependency>

<!--mysql驅動-->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>5.1.47</version>

</dependency>

<!--druid啟動器依賴-->

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>druid-spring-boot-starter</artifactId>

<version>1.1.10</version>

</dependency>

<!--web啟動器依賴-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<!--spring boot actuator依賴-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

<!--編碼工具包-->

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-lang3</artifactId>

</dependency>

<!--熱部署-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-devtools</artifactId>

<scope>runtime</scope>

<optional>true</optional>

</dependency>

</dependencies>

<build>

<plugins>

<!--spring boot maven插件 , 可以將專案運行依賴的jar包打到我們的專案中-->

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

 

</project>

4.2.4 創建啟動類

package com.atguigu;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication

@MapperScan(basePackages = "com.atguigu.dao")

@EnableTransactionManagement

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class,args);

}

}

4.3 資料訪問層

4.3.1 撰寫組態檔application.yml

server:
port: 10001

spring:

datasource:

driver-class-name: com.mysql.jdbc.Driver

url: jdbc:mysql:///springboot

username: root

password: root

type: com.alibaba.druid.pool.DruidDataSource

mybatis:

type-aliases-package: com.atguigu.pojo

4.3.2 撰寫物體類User

package com.atguigu.pojo;

import java.io.Serializable;

@Entity
@Table(name = "tb_user")

public class User implements Serializable {

@Id
private Integer id;
private String name;
private String gender;
private Integer age;
private String address;
private String qq;
private String email;
private String username;
private String phone;

…省略了getter和setter方法和toString方法

4.3.3 Mapper介面和映射配置

package com.atguigu.dao;

import com.atguigu.pojo.User;

import tk.mybatis.mapper.common.Mapper;

import java.util.List;

public interface UserMapper extends Mapper<User> {

}

4.3.4 撰寫測驗代碼

@RunWith(SpringRunner.class)

@SpringBootTest

public class UserMapperTest {

@Autowired

private UserMapper userMapper ;

@Test

public void findAll() {

List<User> users = userMapper.selectAll();

System.out.println(users);

}

}

4.4 業務層

4.4.1編寫介面

public interface UserService {

/**

* 查詢所有用戶資訊

* @return

*/

public List<User> findAll();

}

4.4.2 撰寫實作類

package com.atguigu.service.impl;

import com.atguigu.dao.UserMapper;

import com.atguigu.pojo.User;

import com.atguigu.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.List;

@Service

public class UserServiceImpl implements UserService {

@Autowired

private UserMapper userMapper;

@Override

@Transactional(readOnly = true ,propagation = Propagation.SUPPORTS)

public List<User> findAll() {

return userMapper.selectAll();

}

}

4.4.3 撰寫測驗代碼

@RunWith(SpringRunner.class)

@SpringBootTest

public class UserServiceTest {

@Autowired

private UserService userService;

@Test

public void findAll() {

List<User> users = userService.findAll();

System.out.println(users);

}

}

Spring Boot整合單元測驗 , 需要在測驗類上添加二個注解

  1. @RunWith(SpringRunner.class)指定Junit核心運行類
  2. @SpringBootTest 指定這是一個Spring Boot的測驗類, 運行時會自動加載Spring Boot運行環境

4.5 表現層

4.5.1 引入起步依賴

<!--Web起步依賴-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<!--編碼工具包-->

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-lang3</artifactId>

</dependency>

4.5.2 新建工具類

package com.atguigu.utils;

import java.io.Serializable;

public class Result implements Serializable {

private boolean status ; //回應狀態 true false

private String msg ; // 回應資訊

private Object data ; //處理成功的回應資料

public static Result ok(Object data){

Result result = new Result();

result.setStatus(true);

result.setData(data);

return result ;

}

public static Result error(String msg){

Result result = new Result();

result.setStatus(false);

result.setMsg(msg);

return result ;

}

 

// 生成set get tostring方法

 

}

 

4.5.3 撰寫表現層代碼

@Controller

@RequestMapping(path = "/user")

public class UserController {

@Autowired

private UserService userService;

/**

* 查詢所有用戶資訊

* @return

*/

@RequestMapping(path = "/findAll")

@ResponseBody

public Result findAll() {

List<User> users = userService.findAll();

return Result.ok(users);

}

}

4.5.4 代碼測驗

使用postman進行測驗

4.6 頁面展示

在resources目錄下創建static目錄 , 將提供的頁面復制進來 , 修改即可 :

  • 頁面異步請求的埠和服務器埠一致
  • 頁面異步請求訪問的路徑和對應的表現層控制方法路徑要致
  • 頁面異步請求引數名稱和和對應的表現層控制方法引數一致

修改之后, 訪問頁面即可 : localhost:10001/list.html

4.7 快取優化

4.7.1 快取需求

4.7.2 引入起步依賴

<!--springboot整合redis啟動器-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

4.7.3 撰寫組態檔

spring:

redis: # 配置redis

host: 192.168.6.100

port: 6379

4.7.4 修改業務層實作類代碼

package com.atguigu.service.impl;

import com.atguigu.mapper.UserMapper;

import com.atguigu.pojo.User;

import com.atguigu.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Propagation;

import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service

public class UserServiceImpl implements UserService {

@Autowired

private UserMapper userMapper ;

@Autowired

private RedisTemplate redisTemplate ;

@Override

@Transactional(readOnly = true ,propagation = Propagation.SUPPORTS)

public List<User> findAll() {

//從快取中查詢資料 規定存盤用戶資訊使用string型別進行存盤, 存盤的key就是userList

List<User> userList = (List<User>) redisTemplate.boundValueOps("userList").get();

//如果快取中沒有資料, 查詢資料庫 , 將查詢到的資料放入快取

if(userList==null){

userList = userMapper.findAll();

redisTemplate.boundValueOps("userList").set(userList);

System.out.println("從資料庫中查詢...");

}else {

System.out.println("從快取中查詢.....");

}

//如果快取中有資料, 直接回傳

return userList ;

}

}

五. SpringBoot其他組件(了解)

5.1 SpringBoot Actuator組件

Spring Boot Actuator是SpringBoot自帶的一個組件 , 可以幫助我們監控和管理Spring Boot應用,比如健康檢查、審計、統計和HTTP追蹤等,

引入SpringBoot Actuator起步依賴

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

配置SpringBoot Actuator引數

management:

endpoints:

web:

exposure:

include: '*' # 對外暴露的訪問入口 , 默認是/health和/info

base-path: /monitor # 默認是actuator

endpoint:

health:

show-details: ALWAYS # 顯示所有健康狀態

server:

port: 9999

啟動專案獲取系統資訊

專案啟動之后就可以通過發送http請求獲取系統健康資料了 , 例如 : http://localhost:9999/monitor/health , 回傳資料如下 :

{

"status": "UP",

"details": {

"db": {

"status": "UP",

"details": {

"database": "MySQL",

"hello": 1

}

},

"diskSpace": {

"status": "UP",

"details": {

"total": 355816562688,

"free": 129251151872,

"threshold": 10485760

}

},

"redis": {

"status": "UP",

"details": {

"version": "2.8.9"

}

}

}

}

常用的訪問路徑如下 :

HTTP 方法

路徑

描述

GET

/autoconfig

提供了一份自動配置報告,記錄哪些自動配置條件通過了,哪些沒通過

GET

/configprops

描述配置屬性(包含默認值)如何注入Bean

GET

/beans

描述應用程式背景關系里全部的Bean,以及它們的關系

GET

/dump

獲取執行緒活動的快照

GET

/env

獲取全部環境屬性

GET

/env/{name}

根據名稱獲取特定的環境屬性值

GET

/health

報告應用程式的健康指標,這些值由HealthIndicator的實作類提供

GET

/info

獲取應用程式的定制資訊,這些資訊由info打頭的屬性提供

GET

/mappings

描述全部的URI路徑,以及它們和控制器(包含Actuator端點)的映射關系

GET

/metrics

報告各種應用程式度量資訊,比如記憶體用量和HTTP請求計數

GET

/metrics/{name}

報告指定名稱的應用程式度量值

POST

/shutdown

關閉應用程式,要求endpoints.shutdown.enabled設定為true

GET

/trace

提供基本的HTTP請求跟蹤資訊(時間戳、HTTP頭等)

我們可以通過發送這些請求, 獲取系統狀態資訊

5.2 SpringBoot Admin組件

上面我們講了Spring Boot Actuator , 可以通過http協議獲取系統狀態資訊 , 但是回傳的是JSON格式資料, 看起來不太方面, 而且還需要記憶路徑, 比較麻煩 , Spring Boot Admin給我們提供了更加友好的可視化界面來查看這些資訊 !

Spring Boot Admin是一個開源社區專案,用于管理和監控SpringBoot應用程式, 應用程式作為Spring Boot Admin Client向Spring Boot Admin Server注冊 , Client會定時向Server發送資料, Server使用友好的界面展示資料,

5.2.1 SpringBoot Admin服務端

  1. 創建專案springboot-admin-server
  2. 起步依賴

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.2.2.RELEASE</version>

</parent>

<groupId>com.atguigu</groupId>

<artifactId>springboot-admin-server</artifactId>

<version>1.0-SNAPSHOT</version>

<properties>

<java.version>1.8</java.version>

</properties>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>de.codecentric</groupId>

<artifactId>spring-boot-admin-starter-server</artifactId>

<version>2.2.0</version>

</dependency>

</dependencies>

</project>

  1. 配置application.yml

spring:

application:

name: admin-server

server:

port: 8769

Spring Boot Admin 埠號 8769

  1. 啟動類

@SpringBootApplication

@EnableAdminServer

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class,args);

}

}

@EnableAdminServer , 開啟管理服務

5.2.2 SpringBoot Admin客戶端

  1. 起步依賴

<dependency>

<groupId>de.codecentric</groupId>

<artifactId>spring-boot-admin-starter-client</artifactId>

<version>2.2.0</version>

</dependency>

  1. 配置

向admin-server注冊的地址為http://localhost:8769,最后暴露自己的actuator的所有埠資訊,具體配置如下:

server:

port: 9999

spring:

application:

name: admin-client

boot:

admin:

client:

url: http://localhost:8769 # 指定注冊地址 , Spring Boot Admin Server地址

management:

endpoints:

web:

exposure:

include: '*'

endpoint:

health:

show-details: ALWAYS

注冊地址一定要和Spring Boot Admin Server地址匹配

5.3.3 啟動測驗

分別開啟客戶端(應用程式)和服務端 ,訪問http://localhost:8769 , 可以看到如下界面

六. Spring Boot專案打包部署(應用)

6.1 專案打包

  1. 在pom.xml中配置Spring Boot專案的maven插件

<build>

<plugins>

<!-- 打jar包時如果不配置該插件,打出來的jar包沒有清單檔案 -->

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

  1. 運行maven的打包命令 : package

  1. 打包之前我們需要跳過測驗 , 如果不跳過測驗那么我們撰寫的測驗類都會被maven自動執行, 可能會出現錯誤,導致打包不成功

  1. 執行之后可以在控制臺看到打包的日志資訊, 其中有生成的包的位置

打開指定目錄就可以發現有一個jar包存在 , 仔細觀察其實我們會發現 , 在target目錄下其實會存在二個jar包 , 一個是springboot_02-1.0-SNAPSHOT.jar一個是springboot_02-1.0-SNAPSHOT.jar.original , 那么這兩個jar包有什么區別呢?

我們如果是普通專案打包那么就只會得到一個jar包 , 這個jar包中不包含專案的一些依賴jar包

但是我們現在是一個Spring Boot專案 , 我們希望打完的包能夠直接運行, 所以專案中就必須包含他的依賴jar包 , 我們之前在pom.xml中配置一個Spring Boot的maven插件可以在普通包的基礎上將我們專案的一些運行及依賴資訊打進jar包里面 , 打完包之后將原來的普通包改名為xxx.jar.original , 新打的包為xxx.jar .

  1. 簡單總結一下 :
  • .jar.original 是普通jar包,不包含依賴
  • .jar 是可執行jar包,包含了pom中的所有依賴,可以直接用java -jar 命令執行
  • 如果是部署,就用.jar , 如果是給別的專案用,就要給.jar.original這個包

6.2 專案運行

打開命令列運行打出來的包;使用命令:java –jar 包全名

java -jar springboot_02-1.0-SNAPSHOT.jar

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/544079.html

標籤:Java

上一篇:讀Java實戰(第二版)筆記11_語言特性和類別庫更新

下一篇:day11-JSON處理和HttpMessageConverter<T>

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more