1. 程式人生 > 實用技巧 >SpringBoot學習文件

SpringBoot學習文件

SpringBoot學習筆記

一、概述

1.1 Spring優缺點分析

Spring優點

Spring是Javaee的輕量級代替品,無需開發重量級的Enterprise JavaBean(EJB)物件,Spring為企業級Java開發提供了一種相對簡單的方法,通過依賴注入和麵向切面程式設計,用簡單的Java物件(POJO)實現了EJB的功能。

Spring的缺點

雖然Spring是輕量級的,但是Spring的配置卻是重量級的,一開始,SPring用xml配置,Spring2.5引入了基於註解的元件掃描,這消除了大量針對應用程式自身元件的顯式xml配置,Spring3.0引入了基於Java的配置,這是一種型別安全的可重構配置方式,可以代替xml。所有這些配置代表了開發時的損耗。

除此之外,專案的依賴管理也十分耗時耗力,在環境搭建時,需要分析匯入那些庫的座標,而且還需要分析匯入與所有依賴關係其他哭的座標,一旦選錯了依賴的版本,不相容問題也十分嚴重。

1.2 SpringBoot的概述

SpringBoot解決Spring的缺點

springboot對上述缺點進行改善和優化,基於約定優於配置的思想,可以讓開發人員不必在配置與邏輯業務之間進行思維的切換,大大提高了開發的效率,一定程度縮短了專案週期。

SpringBoot的特點

  • 為基於Spring開發提供更快的入門體驗
  • 開箱即用,無需xml配置,可以通過預設值開滿足特定的需求。
  • 提供了一些大型專案中常見的非功能性的特性,如嵌入式伺服器、安全、指標、健康檢測、外部配置等。
  • SpringBoot不是對Spring功能上的增強,而是提供了一種快速使用Spring的方式

SpringBoot的核心功能

  • 起步依賴

    起步依賴本質上是一個Maven專案物件模型(POM),定義了對其他庫的傳遞依賴,這些東西加在一起及支援某項功能。

  • 自動配置

    springboot的自動配置是一個執行時(應用程式啟動時)的過程

1.3 SpringBoot快速入門

  1. 建立maven工程

    普通java工程即可

  2. 新增SpringBoot的起步依賴

    springboot要求專案要繼承springboor的起步以來spring-boot-starter-parent

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
    </parent>
    

    springboot要整合springmvc的controller,所以專案要匯入web的啟動依賴

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    
  3. 編寫SpringBoot的引導類

    通過springboot提供的引導類起步SpringBoot才可以進行訪問

    package com.yhr.testspringboot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class MySpringBootApp {
        public static void main(String[] args) {
            SpringApplication.run(MySpringBootApp.class);
        }
    }
    
    
  4. 編寫controller

    在引導類MySpringBootApp同級包或者子級包中建立QuickStartController

    package com.yhr.testspringboot.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    public class QuickStartController {
        
        @RequestMapping("/quick")
        @ResponseBody
        public String quick(){
            return "SpringBoot 訪問成功";
        }
    }
    
    
  5. 測試

    啟動SpringBoot起步類的主方法,控制檯日誌列印如下,tomcat已經啟動,開啟瀏覽器訪問localhost:8080/quick

    2020-11-26 10:10:50.903 INFO 4060 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
    2020-11-26 10:10:50.919 INFO 4060 --- [ main] com.yhr.testspringboot.MySpringBootApp : Started MySpringBootApp in 3.077 seconds (JVM running for 3.587)

    顯示springboot訪問成功

1.4 SpringBoot快速入門解析

SpringBoot程式碼解析

  • @SpringBootApplication:標註SpringBoot的啟動類,具備多種功能
  • SpringApplication.run(MySpringBootApp.class)代表執行SpringBoot的啟動類,引數為SpringBoot啟動類的位元組碼物件

SpringBoot工程熱部署

在開發中反覆修改類、頁面等資源,每次修改需要重新啟動才生效,這樣每次都需要重新啟動很麻煩,浪費大量部署的時間,在pom.xml中新增如下配置可以實現在修改程式碼後不重啟就能生效,我們稱之為熱部署。

<!--熱部署配置-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>

IDEA進行SpringBoot熱部署失敗的原因:

根本原因是因為IDEA預設情況下不會自動編譯,需要對IDEA進行自動編譯的設定。

  1. 點選Settings中Build下的Compiler,在右側選中Make project automatically
  2. 退出Settings,按下Shift+Ctrl+Alt+/,選中Registry,然後在彈出框中勾選compiler.automake.allow.when.app.running
  3. 重啟IDEA

使用IDEA快速建立SpringBoot專案

在新建中選擇Spring Initializr而不是maven專案

二、SpringBoot原理分析

2.1 起步依賴原理分析

2.1.1 spring-boot-starter-parent

按住CTRL點選pom中的spring-boot-starter-parent跳轉到了spring-boot-starter-parent中的pom.xml,部分配置如下:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.0.1.RELEASE</version>
    <relativePath>../../spring-boot-dependencies</relativePath>
</parent>

繼續跳轉到spring-boot-dependencies,部分配置如下:

<properties>
    <activemq.version>5.15.3</activemq.version>
    <antlr2.version>2.7.7</antlr2.version>
    <appengine-sdk.version>1.9.63</appengine-sdk.version>
    <artemis.version>2.4.0</artemis.version>
    <aspectj.version>1.8.13</aspectj.version>
    <assertj.version>3.9.1</assertj.version>
</properties>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot</artifactId>
            <version>2.0.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
            <version>2.0.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test-autoconfigure</artifactId>
            <version>2.0.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator</artifactId>
            <version>2.0.1.RELEASE</version>
        </dependency>
    </dependencies>
</dependencyManagement>

可見一部分座標的版本、依賴管理、外掛管理已經定義好,所以我們的SpringBoot工程繼承spring-boot-starter-parent後已經具備版本鎖定等配置了。所以起步依賴的作用就是進行依賴的傳遞。

2.1.2 spring-boot-starter-web

跳轉spring-boot-starter-web的pom中部分配置如下

<dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.0.1.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-json</artifactId>
      <version>2.0.1.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <version>2.0.1.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.hibernate.validator</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>6.0.9.Final</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.0.5.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.0.5.RELEASE</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>

spring-boot-starter-web就是將web開發要使用的spring-web、spring-webmvc等座標進行了“打包”,這樣我們的工程只要引入spring-boot-starter-web起步依賴的座標就可以進行web開發了,同樣體現了依賴傳遞的作用。

2.2 自動配置原理分析

檢視@SpringBootApplication註解的原始碼,原始碼如下:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
@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 {
    @AliasFor(
        annotation = EnableAutoConfiguration.class
    )
    Class<?>[] exclude() default {};

    @AliasFor(
        annotation = EnableAutoConfiguration.class
    )
    String[] excludeName() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackages"
    )
    String[] scanBasePackages() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackageClasses"
    )
    Class<?>[] scanBasePackageClasses() default {};
}

其中

@SpringBootConfiguration:等同於@Configuration,既標註該類是一個Spring的配置類
@EnableAutoConfiguration:SpringBoot的自動配置功能開啟

檢視@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})匯入了AutoConfigurationImportSelector類,點選檢視AutoConfigurationImportSelector的原始碼:部分原始碼如下:

public String[] selectImports(AnnotationMetadata annotationMetadata) {
    if (!this.isEnabled(annotationMetadata)) {
        return NO_IMPORTS;
    } else {
        AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
        AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
        //獲取配置
        List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
        configurations = this.removeDuplicates(configurations);
        Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
        this.checkExcludedClasses(configurations, exclusions);
        configurations.removeAll(exclusions);
        configurations = this.filter(configurations, autoConfigurationMetadata);
        this.fireAutoConfigurationImportEvents(configurations, exclusions);
        return StringUtils.toStringArray(configurations);
    }
}
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
    List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.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;
}

其中SpringFactoriesLoader.loadFactoryNames方法的作用就是從META-INF/spring.factories檔案中讀取指定類對應的類名稱列表。

spring.factories有關原始碼:

....
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
.....

上面配置檔案存在大量的以Configuration為結尾的類名稱,這些類就是存有自動配置資訊的類,而SpringApplication在獲取這些類名後再載入。

我們以其中ServletWebServerFactoryAutoConfiguration為例,其部分原始碼如下:

@Configuration
@AutoConfigureOrder(-2147483648)
@ConditionalOnClass({ServletRequest.class})
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
@EnableConfigurationProperties({ServerProperties.class})
@Import({ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class, EmbeddedTomcat.class, EmbeddedJetty.class, EmbeddedUndertow.class})
public class ServletWebServerFactoryAutoConfiguration {

@EnableConfigurationProperties(ServerProperties.class) 代表載入ServerProperties伺服器配置屬性類

ServerProperties原始碼:

@ConfigurationProperties(
    prefix = "server",
    ignoreUnknownFields = true
)
public class ServerProperties {
    private Integer port;
    private InetAddress address;
    @NestedConfigurationProperty
    private final ErrorProperties error = new ErrorProperties();
    private Boolean useForwardHeaders;
    private String serverHeader;
    private int maxHttpHeaderSize = 0;
    。。。。。。

prefix = "server" 表示SpringBoot配置檔案中的字首,SpringBoot會將配置檔案中以server開始的屬性對映到該類
的欄位中。

例如在spring-configuration-metadata.json檔案中某段以server字首加上屬性server.port配置了預設值:

{
    "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties",
    "defaultValue": 8080,
    "name": "server.port",
    "description": "Server HTTP port.",
    "type": "java.lang.Integer"
},

以上為預設值,且可以覆蓋,如果在yml檔案中設定配置即可修改配置。

在spring-boot-starter-parent的pom.xml中如下

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

以上代表在resources中如果設定了配置檔案即可覆蓋預設配置。

三、SpringBoot的配置檔案

3.1 SpringBoot配置檔案型別

springboot是基於約定的,所以很多配置都有預設值,如果想替換預設配置的話,就可以使用application.properties或者application.yml進行設定。

SpringBoot預設會從resources目錄下載入application.properties或者application.yml檔案。

其中properties是以鍵值對的方式,下面詳細介紹yml配置方式

3.1.1 application.yml配置檔案

yml是以YMAL(YAML Aint Markup Language)編寫的檔案格式,是一種直觀的能被電腦識別的資料序列化格式,且易被閱讀,易與指令碼語言互動,yml是以資料為核心的,比xml更簡潔。

3.1.2 yml配置檔案的語法

配置普通資料

key: value

name : haha

注意value前有一個空格

配置物件資料

key:

key1: value1

key2: value2

或者

key: {key1: value,key2: value2}

persion:
	name: haha
	age: 10
	addr: beijing
#或者
persion: {name: haha,age: 10,addr: beijing}

注意:在yml語法中相同縮排代表同一個級別

配置map資料

與上相同

配置陣列(List、Set)資料

key:

- value

- value

或者key: [value1,value2]

city:
	- beijing
	- nanjing
	- tianjing
#或者
city: [beijing,nanjing,tianjing]
#集合的元素是物件形式
student: 
	-name: haha
	 age: 18
	 score: 80
	-name: lala
	 age: 19
	 score: 60

注意:value1與之間的- 之間存在一個空格

3.1.3 SpringBoot配置資訊的查詢

可以通過修改application.properties或者application.yml來修改springboot的預設配置,例如:

properties

server.port=8081
server.servlet.context-path=demp

yml

server:
	port: 8081
	servlet:
		context-path: /demo

3.2 配置檔案與配置類的屬性對映方式

3.2.1 使用註解@Value對映

我們可以通過@Value將配置檔案中的值對映到一個Spring管理的Bean上,此時使用的是${}

ps:

@Value("#{}") 表示SpEl表示式通常用來獲取bean的屬性,或者呼叫bean的某個方法。當然還有可以表示常量

通過@Value("${}") 可以獲取對應屬性檔案中定義的屬性值。假如我有一個sys.properties檔案 裡面規定了一組值: web.view.prefix =/WEB-INF/views/

#properties
persion:
	name: haha
	age: 18
#yml
persion:
	name: haha
	age: 18

Bean:

@Controller
public class QuickStartController {
    @Value("${person.name}")
    private String name;
    @Value("${person.age}")
    private Integer age;
    
    @RequestMapping("/quick")
    @ResponseBody
    public String quick(){
        return "SpringBoot 訪問成功 name="+name +"age="+age;
    }
}

3.2.2 使用註解@ConfigurationProperties對映

通過註解@ConfigurationProperties(prefix="配置檔案中的key的字首")可以將配置檔案中的配置自動與實體進行對映

@Controller
@ConfigurationProperties(prefix="person")
public class QuickStartController {
    
    private String name;

    private Integer age;
    
    public void setName(String name) {
    	this.name = name;
    }
    public void setAge(Integer age) {
    	this.age = age;
    }

    
    @RequestMapping("/quick")
    @ResponseBody
    public String quick(){
        return "SpringBoot 訪問成功 name="+name +"age="+age;
    }
}

使用@ConfigurationProperties方式可以進行配置檔案與實體欄位的自動對映,但需要欄位必須提供set方法才可以,而使用@Value註解修飾的欄位不需要提供set方法

四、SpringBoot整合其他技術

4.1 整合Mybatis

mysql8.0以上版本

新增依賴

<!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--MYSQL驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>

配置檔案

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/taotaostore?useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=manager
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

資料庫建表並建立實體類

//建表略
public class User{
    private Long id;
    private String username;
    private String password;
    private String name;
    //get set方法略
}

編寫mapper

介面

@Mapper
public interface UserMapeer {
    public List<User> queryUserList();
}

xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.itheima.mapper.UserMapper">
    <select id="queryUserList" resultType="user">
        select * from user
    </select>
</mapper>

Controller

@Controller
public class QuickStartController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/queryUser")
    @ResponseBody
    public List<User> queryUser(){
        List<User> users = userMapper.queryUserList();
        return users;
    }
}

測試成功

4.2 整合Junit

新增依賴

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

測試類

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApp.class)
public class TestMapper {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void test(){
        List<User> users = userMapper.queryUserList();
        System.out.println(users);
    }
}

@SpringBootTest的屬性指定的是引導類的位元組碼物件

4.3 整合Spring Data JPA

新增依賴

<!--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>
    <version>8.0.11</version>
</dependency>

配置

#JPA
#DB Configuration 同上
#JPA Configuration
spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update

實體類

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User_JPA {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private Integer age;

    private String username;

    private String password;

    private String email;

    private String sex;

   //get set方法
}

介面

public interface UserRepository extends JpaRepository<User_JPA,Integer>{

    public List<User_JPA> findAll();
}

測試

    @Test
    public void test1(){
        List<UserJPA> users = userRepository.findAll();
        System.out.println(users);
    }

如果是jdk9需要以下座標

<dependency>
	<groupId>javax.xml.bind</groupId>
    <artifactId>javax-api</artifactId>
	<version>2.3.0</version>
</dependency>

4.4 整合Redis

新增依賴

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

配置資訊

#redis配置
spring.redis.host=127.0.0.1
spring.redis.port=6379

注入RedisTemplate操作測試