SpringBoot基礎(chǔ)

學(xué)習(xí)目標(biāo):

  1. 能夠理解Spring的優(yōu)缺點(diǎn)
  2. 能夠理解SpringBoot的特點(diǎn)
  3. 能夠理解SpringBoot的核心功能
  4. 能夠搭建SpringBoot的環(huán)境
  5. 能夠完成application.properties配置文件的配置
  6. 能夠完成application.yml配置文件的配置
  7. 能夠使用SpringBoot集成Mybatis
  8. 能夠使用SpringBoot集成Junit
  9. 能夠使用SpringBoot集成SpringData JPA

一臣缀、SpringBoot簡(jiǎn)介

1.1 原有Spring優(yōu)缺點(diǎn)分析

1.1.1 Spring的優(yōu)點(diǎn)分析

Spring是Java企業(yè)版(Java Enterprise Edition王滤,JEE池户,也稱J2EE)的輕量級(jí)代替品央拖。無需開發(fā)重量級(jí)的Enterprise JavaBean(EJB)蝶押,Spring為企業(yè)級(jí)Java開發(fā)提供了一種相對(duì)簡(jiǎn)單的方法润讥,通過依賴注入和面向切面編程呛梆,用簡(jiǎn)單的Java對(duì)象(Plain Old Java Object吟税,POJO)實(shí)現(xiàn)了EJB的功能搪泳。

1.1.2 Spring的缺點(diǎn)分析

雖然Spring的組件代碼是輕量級(jí)的稀轨,但它的配置卻是重量級(jí)的。一開始岸军,Spring用XML配置奋刽,而且是很多XML配置。Spring 2.5引入了基于注解的組件掃描艰赞,這消除了大量針對(duì)應(yīng)用程序自身組件的顯式XML配置佣谐。Spring 3.0引入了基于Java的配置,這是一種類型安全的可重構(gòu)配置方式方妖,可以代替XML狭魂。

所有這些配置都代表了開發(fā)時(shí)的損耗。因?yàn)樵谒伎糞pring特性配置和解決業(yè)務(wù)問題之間需要進(jìn)行思維切換,所以編寫配置擠占了編寫應(yīng)用程序邏輯的時(shí)間趁蕊。和所有框架一樣坞生,Spring實(shí)用,但與此同時(shí)它要求的回報(bào)也不少掷伙。

除此之外是己,項(xiàng)目的依賴管理也是一件耗時(shí)耗力的事情。在環(huán)境搭建時(shí)任柜,需要分析要導(dǎo)入哪些庫(kù)的坐標(biāo)卒废,而且還需要分析導(dǎo)入與之有依賴關(guān)系的其他庫(kù)的坐標(biāo),一旦選錯(cuò)了依賴的版本宙地,隨之而來的不兼容問題就會(huì)嚴(yán)重阻礙項(xiàng)目的開發(fā)進(jìn)度摔认。

1.2 SpringBoot的概述

1.2.1 SpringBoot解決上述Spring的缺點(diǎn)

SpringBoot對(duì)上述Spring的缺點(diǎn)進(jìn)行的改善和優(yōu)化,基于約定優(yōu)于配置的思想宅粥,可以讓開發(fā)人員不必在配置與邏輯業(yè)務(wù)之間進(jìn)行思維的切換参袱,全身心的投入到邏輯業(yè)務(wù)的代碼編寫中,從而大大提高了開發(fā)的效率秽梅,一定程度上縮短了項(xiàng)目周期抹蚀。

1.2.2 SpringBoot的特點(diǎn)

  • 為基于Spring的開發(fā)提供更快的入門體驗(yàn)
  • 開箱即用,沒有代碼生成企垦,也無需XML配置环壤。同時(shí)也可以修改默認(rèn)值來滿足特定的需求
  • 提供了一些大型項(xiàng)目中常見的非功能性特性,如嵌入式服務(wù)器钞诡、安全郑现、指標(biāo),健康檢測(cè)荧降、外部配置等
  • SpringBoot不是對(duì)Spring功能上的增強(qiáng)接箫,而是提供了一種快速使用Spring的方式

1.2.3 SpringBoot的核心功能

  • 起步依賴
    起步依賴本質(zhì)上是一個(gè)Maven項(xiàng)目對(duì)象模型(Project Object Model,POM)誊抛,定義了對(duì)其他庫(kù)的傳遞依賴列牺,這些東西加在一起即支持某項(xiàng)功能。
    簡(jiǎn)單的說拗窃,起步依賴就是將具備某種功能的坐標(biāo)打包到一起瞎领,并提供一些默認(rèn)的功能。

  • 自動(dòng)配置
    Spring Boot的自動(dòng)配置是一個(gè)運(yùn)行時(shí)(更準(zhǔn)確地說随夸,是應(yīng)用程序啟動(dòng)時(shí))的過程九默,考慮了眾多因素,才決定Spring配置應(yīng)該用哪個(gè)宾毒,不該用哪個(gè)驼修。該過程是Spring自動(dòng)完成的。

  • 輔助功能
    提供了一些大型項(xiàng)目中常見的非功能性特性,如嵌入式服務(wù)器乙各、安全墨礁、指標(biāo),健康檢測(cè)耳峦、外部配置等恩静。

注意:起步依賴和自動(dòng)配置的原理剖析會(huì)在第三章《SpringBoot原理分析》進(jìn)行詳細(xì)講解

二、SpringBoot快速入門

2.1 代碼實(shí)現(xiàn)

①創(chuàng)建Maven項(xiàng)目
②導(dǎo)導(dǎo)入SpringBoot起步依賴
③定義Controller
④編寫引導(dǎo)類
⑤啟動(dòng)測(cè)試

2.1.1 創(chuàng)建Maven工程

使用idea工具創(chuàng)建一個(gè)maven工程蹲坷,該工程為普通的java工程即可






2.1.2 添加SpringBoot的起步依賴


  • SpringBoot要求驶乾,項(xiàng)目要繼承SpringBoot的起步依賴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進(jìn)行Controller的開發(fā),所以項(xiàng)目要導(dǎo)入web的啟動(dòng)依賴
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

2.1.3 編寫SpringBoot引導(dǎo)類

要通過SpringBoot提供的引導(dǎo)類起步SpringBoot才可以進(jìn)行訪問

package com.itheima;

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

@SpringBootApplication
public class MySpringBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class);
    }

}

2.1.4 編寫Controller

在引導(dǎo)類MySpringBootApplication同級(jí)包或者子級(jí)包中創(chuàng)建QuickStartController

package com.itheima.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 訪問成功!";
    }
    
}

2.1.5 測(cè)試

執(zhí)行SpringBoot起步類的主方法循签,控制臺(tái)打印日志如下:

.   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.1.RELEASE)

2018-05-08 14:29:59.714  INFO 5672 --- [           main] com.itheima.MySpringBootApplication      : Starting MySpringBootApplication on DESKTOP-RRUNFUH with PID 5672 (C:\Users\muzimoo\IdeaProjects\IdeaTest\springboot_quick\target\classes started by muzimoo in C:\Users\muzimoo\IdeaProjects\IdeaTest)
... ... ...
o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-08 14:30:03.126  INFO 5672 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-05-08 14:30:03.196  INFO 5672 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-05-08 14:30:03.206  INFO 5672 --- [           main] com.itheima.MySpringBootApplication      : Started MySpringBootApplication in 4.252 seconds (JVM running for 5.583)

通過日志發(fā)現(xiàn)级乐,Tomcat started on port(s): 8080 (http) with context path ''
tomcat已經(jīng)起步,端口監(jiān)聽8080县匠,web應(yīng)用的虛擬工程名稱為空
打開瀏覽器訪問url地址為:http://localhost:8080/quick

2.2 快速入門解析

2.2.2 SpringBoot代碼解析

  • @SpringBootApplication:標(biāo)注SpringBoot的啟動(dòng)類风科,該注解具備多種功能(后面詳細(xì)剖析)
  • SpringApplication.run(MySpringBootApplication.class) 代表運(yùn)行SpringBoot的啟動(dòng)類,參數(shù)為SpringBoot啟動(dòng)類的字節(jié)碼對(duì)象

2.2.3 SpringBoot工程熱部署

我們?cè)陂_發(fā)中反復(fù)修改類聚唐、頁(yè)面等資源丐重,每次修改后都是需要重新啟動(dòng)才生效,這樣每次啟動(dòng)都很麻煩杆查,浪費(fèi)了大量的時(shí)間,我們可以在修改代碼后不重啟就能生效臀蛛,在 pom.xml 中添加如下配置就可以實(shí)現(xiàn)這樣的功能亲桦,我們稱之為熱部署。

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

注意:IDEA進(jìn)行SpringBoot熱部署失敗原因

出現(xiàn)這種情況浊仆,并不是熱部署配置問題客峭,其根本原因是因?yàn)镮ntellij IEDA默認(rèn)情況下不會(huì)自動(dòng)編譯,需要對(duì)IDEA進(jìn)行自動(dòng)編譯的設(shè)置抡柿,如下:
然后 Shift+Ctrl+Alt+/舔琅,選擇Registry


2.2.4 使用idea快速創(chuàng)建SpringBoot項(xiàng)目





通過idea快速創(chuàng)建的SpringBoot項(xiàng)目的pom.xml中已經(jīng)導(dǎo)入了我們選擇的web的起步依賴的坐標(biāo)

<?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>

    <groupId>com.itheima</groupId>
    <artifactId>springboot_quick2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot_quick2</name>
    <description>Demo project for Spring Boot</description>

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

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>9</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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

可以使用快速入門的方式創(chuàng)建Controller進(jìn)行訪問,此處不再贅述

三洲劣、SpringBoot原理分析

3.1 起步依賴原理分析

3.1.1 分析spring-boot-starter-parent

按住Ctrl點(diǎn)擊pom.xml中的spring-boot-starter-parent备蚓,跳轉(zhuǎn)到了spring-boot-starter-parent的pom.xml,xml配置如下(只摘抄了部分重點(diǎn)配置):

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

按住Ctrl點(diǎn)擊pom.xml中的spring-boot-starter-dependencies囱稽,跳轉(zhuǎn)到了spring-boot-starter-dependencies的pom.xml郊尝,xml配置如下(只摘抄了部分重點(diǎn)配置):

<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>
    <atomikos.version>4.0.6</atomikos.version>
    <bitronix.version>2.1.4</bitronix.version>
    <build-helper-maven-plugin.version>3.0.0</build-helper-maven-plugin.version>
    <byte-buddy.version>1.7.11</byte-buddy.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>
        ... ... ...
    </dependencies>
</dependencyManagement>
<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <version>${kotlin.version}</version>
            </plugin>
            <plugin>
                <groupId>org.jooq</groupId>
                <artifactId>jooq-codegen-maven</artifactId>
                <version>${jooq.version}</version>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.0.1.RELEASE</version>
            </plugin>
            ... ... ...
        </plugins>
    </pluginManagement>
</build>

從上面的spring-boot-starter-dependencies的pom.xml中我們可以發(fā)現(xiàn),一部分坐標(biāo)的版本战惊、依賴管理流昏、插件管理已經(jīng)定義好,所以我們的SpringBoot工程繼承spring-boot-starter-parent后已經(jīng)具備版本鎖定等配置了。所以起步依賴的作用就是進(jìn)行依賴的傳遞况凉。

3.1.2 分析spring-boot-starter-web

按住Ctrl點(diǎn)擊pom.xml中的spring-boot-starter-web谚鄙,跳轉(zhuǎn)到了spring-boot-starter-web的pom.xml,xml配置如下(只摘抄了部分重點(diǎn)配置):

<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starters</artifactId>
        <version>2.0.1.RELEASE</version>
    </parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.0.1.RELEASE</version>
    <name>Spring Boot Web Starter</name>
  
    <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>
</project>

從上面的spring-boot-starter-web的pom.xml中我們可以發(fā)現(xiàn)刁绒,spring-boot-starter-web就是將web開發(fā)要使用的spring-web闷营、spring-webmvc等坐標(biāo)進(jìn)行了“打包”,這樣我們的工程只要引入spring-boot-starter-web起步依賴的坐標(biāo)就可以進(jìn)行web開發(fā)了膛锭,同樣體現(xiàn)了依賴傳遞的作用粮坞。

3.2 自動(dòng)配置原理解析

按住Ctrl點(diǎn)擊查看啟動(dòng)類MySpringBootApplication上的注解@SpringBootApplication

@SpringBootApplication
public class MySpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class);
    }
}

注解@SpringBootApplication的源碼

@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 {

    /**
     * Exclude specific auto-configuration classes such that they will never be applied.
     * @return the classes to exclude
     */
    @AliasFor(annotation = EnableAutoConfiguration.class)
    Class<?>[] exclude() default {};

    ... ... ...

}

其中,

@SpringBootConfiguration:等同與@Configuration初狰,既標(biāo)注該類是Spring的一個(gè)配置類

@EnableAutoConfiguration:SpringBoot自動(dòng)配置功能開啟

按住Ctrl點(diǎn)擊查看注解@EnableAutoConfiguration

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
    ... ... ...
}

其中莫杈,@Import(AutoConfigurationImportSelector.class) 導(dǎo)入了AutoConfigurationImportSelector類

按住Ctrl點(diǎn)擊查看AutoConfigurationImportSelector源碼

public String[] selectImports(AnnotationMetadata annotationMetadata) {
        ... ... ...
        List<String> configurations = getCandidateConfigurations(annotationMetadata,
                                                                   attributes);
        configurations = removeDuplicates(configurations);
        Set<String> exclusions = getExclusions(annotationMetadata, attributes);
        checkExcludedClasses(configurations, exclusions);
        configurations.removeAll(exclusions);
        configurations = filter(configurations, autoConfigurationMetadata);
        fireAutoConfigurationImportEvents(configurations, exclusions);
        return StringUtils.toStringArray(configurations);
}


protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
            AnnotationAttributes attributes) {
        List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
                getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
        
        return configurations;
}

其中,SpringFactoriesLoader.loadFactoryNames 方法的作用就是從META-INF/spring.factories文件中讀取指定類對(duì)應(yīng)的類名稱列表

spring.factories 文件中有關(guān)自動(dòng)配置的配置信息如下:

... ... ...

org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
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,\

... ... ...

上面配置文件存在大量的以Configuration為結(jié)尾的類名稱奢入,這些類就是存有自動(dòng)配置信息的類筝闹,而SpringApplication在獲取這些類名后再加載

我們以ServletWebServerFactoryAutoConfiguration為例來分析源碼:

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

其中,

@EnableConfigurationProperties(ServerProperties.class) 代表加載ServerProperties服務(wù)器配置屬性類

進(jìn)入ServerProperties.class源碼如下:

@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties {

    /**
     * Server HTTP port.
     */
    private Integer port;

    /**
     * Network address to which the server should bind.
     */
    private InetAddress address;
  
    ... ... ...
  
}

其中腥光,

prefix = "server" 表示SpringBoot配置文件中的前綴关顷,SpringBoot會(huì)將配置文件中以server開始的屬性映射到該類的字段中。映射關(guān)系如下:

四武福、SpringBoot的配置文件

4.1 SpringBoot配置文件類型

4.1.1 SpringBoot配置文件類型和作用

SpringBoot是基于約定的议双,所以很多配置都有默認(rèn)值,但如果想使用自己的配置替換默認(rèn)配置的話捉片,就可以使用application.properties或者application.yml(application.yaml)進(jìn)行配置平痰。

SpringBoot默認(rèn)會(huì)從Resources目錄下加載application.properties或application.yml(application.yaml)文件

  • properties:
server.port = 8080
  • yml:
server:
  port: 8080
  • Spring Boot提供了2種配置文件類型:properteis和yml/yaml
  • 默認(rèn)配置文件名稱:application
  • 在同一級(jí)目錄下優(yōu)先級(jí)為:properties>yml>yaml

4.1.2 application.yml配置文件

4.1.2.1 yml配置文件簡(jiǎn)介

YML文件格式是YAML (YAML Aint Markup Language)編寫的文件格式,YAML是一種直觀的能夠被電腦識(shí)別的的數(shù)據(jù)數(shù)據(jù)序列化格式伍纫,并且容易被人類閱讀宗雇,容易和腳本語(yǔ)言交互的,可以被支持YAML庫(kù)的不同的編程語(yǔ)言程序?qū)胗ü妫热纾?C/C++, Ruby, Python, Java, Perl, C#, PHP等赔蒲。YML文件是以數(shù)據(jù)為核心的,比傳統(tǒng)的xml方式更加簡(jiǎn)潔良漱。

YML文件的擴(kuò)展名可以使用.yml或者.yaml舞虱。


4.1.2.2 yml配置文件的語(yǔ)法

4.1.2.2.1 配置普通數(shù)據(jù)
基本語(yǔ)法:
  • 大小寫敏感
  • 數(shù)據(jù)值前邊必須有空格,作為分隔符
  • 使用縮進(jìn)表示層級(jí)關(guān)系
  • 縮進(jìn)時(shí)不允許使用Tab鍵债热, 只許使用空格(各個(gè)系統(tǒng)Tab對(duì)應(yīng)的空格數(shù)目可能不同砾嫉, 導(dǎo)致層次混亂) 。
  • 縮進(jìn)的空格數(shù)目不重要窒篱,只要相同層級(jí)的元素左側(cè)對(duì)齊即可
  • ‘#’ 表示注釋焕刮,從這個(gè)字符一直到行尾舶沿,都會(huì)被解析器忽略
  • ‘’不會(huì)識(shí)別轉(zhuǎn)義符,“”會(huì)識(shí)別轉(zhuǎn)義符
  • ${}可以應(yīng)用文件里的其他參數(shù)
4.1.2.2.2 配置對(duì)象數(shù)據(jù)
  • 示例代碼:
  • person:
      name: haohao
      age: 31
      addr: beijing
    #或者
    person: {name: haohao,age: 31,addr: beijing}
    
  • 注意:key1前面的空格個(gè)數(shù)不限定配并,在yml語(yǔ)法中括荡,相同縮進(jìn)代表同一個(gè)級(jí)別
4.1.2.2.2 配置Map數(shù)據(jù)

同上面的對(duì)象寫法

4.1.2.2.3 配置數(shù)組(List、Set)數(shù)據(jù)
  • 示例代碼:

  • city:
      - beijing
      - tianjin
      - shanghai
      - chongqing
      
    #或者
    city: [beijing,tianjin,shanghai,chongqing]
    
    #集合中的元素是對(duì)象形式
    student:
      - name: zhangsan
        age: 18
        score: 100
      - name: lisi
        age: 28
        score: 88
      - name: wangwu
        age: 38
        score: 90
    
  • 注意:value1與之間的 - 之間存在一個(gè)空格

4.1.3 SpringBoot配置信息的查詢

上面提及過溉旋,SpringBoot的配置文件畸冲,主要的目的就是對(duì)配置信息進(jìn)行修改的,但在配置時(shí)的key從哪里去查詢呢观腊?我們可以查閱SpringBoot的官方文檔

文檔URL:https://docs.spring.io/spring-boot/docs/2.0.1.RELEASE/reference/htmlsingle/#common-application-properties

常用的配置摘抄如下:

# QUARTZ SCHEDULER (QuartzProperties)
spring.quartz.jdbc.initialize-schema=embedded # Database schema initialization mode.
spring.quartz.jdbc.schema=classpath:org/quartz/impl/jdbcjobstore/tables_@@platform@@.sql # Path to the SQL file to use to initialize the database schema.
spring.quartz.job-store-type=memory # Quartz job store type.
spring.quartz.properties.*= # Additional Quartz Scheduler properties.

# ----------------------------------------
# WEB PROPERTIES
# ----------------------------------------

# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.port=8080 # Server HTTP port.
server.servlet.context-path= # Context path of the application.
server.servlet.path=/ # Path of the main dispatcher servlet.

# HTTP encoding (HttpEncodingProperties)
spring.http.encoding.charset=UTF-8 # Charset of HTTP requests and responses. Added to the "Content-Type" header if not set explicitly.

# JACKSON (JacksonProperties)
spring.jackson.date-format= # Date format string or a fully-qualified date format class name. For instance, `yyyy-MM-dd HH:mm:ss`.

# SPRING MVC (WebMvcProperties)
spring.mvc.servlet.load-on-startup=-1 # Load on startup priority of the dispatcher servlet.
spring.mvc.static-path-pattern=/** # Path pattern used for static resources.
spring.mvc.view.prefix= # Spring MVC view prefix.
spring.mvc.view.suffix= # Spring MVC view suffix.

# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.driver-class-name= # Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
spring.datasource.password= # Login password of the database.
spring.datasource.url= # JDBC URL of the database.
spring.datasource.username= # Login username of the database.

# JEST (Elasticsearch HTTP client) (JestProperties)
spring.elasticsearch.jest.password= # Login password.
spring.elasticsearch.jest.proxy.host= # Proxy host the HTTP client should use.
spring.elasticsearch.jest.proxy.port= # Proxy port the HTTP client should use.
spring.elasticsearch.jest.read-timeout=3s # Read timeout.
spring.elasticsearch.jest.username= # Login username.

我們可以通過配置application.poperties 或者 application.yml 來修改SpringBoot的默認(rèn)配置

例如:

application.properties文件

server.port=8888
server.servlet.context-path=demo

application.yml文件

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

4.2 配置文件與配置類的屬性映射方式

讀取配置內(nèi)容

  1. @Value
  2. Environment
  3. @ConfigurationProperties

4.2.1 使用注解@Value & Environment映射

我們可以通過@Value注解將配置文件中的值映射到一個(gè)Spring管理的Bean的字段上

例如:

application.properties配置如下:

person:
  name: zhangsan
  age: 18

或者邑闲,application.yml配置如下:

person:
  name: zhangsan
  age: 18

實(shí)體Bean代碼如下:

@Controller
public class QuickStartController {

    @Value("${person.name}")
    private String name;
    @Value("${person.age}")
    private Integer age;
    @Autowired
    private Environment env;


    @RequestMapping("/quick")
    @ResponseBody
    public String quick(){
        return "springboot 訪問成功! name="+name+",age="+age;
        System.out.println(env.getProperty("person.name")) ;
    }

}

4.2.2 使用注解@ConfigurationProperties映射

通過注解@ConfigurationProperties(prefix="配置文件中的key的前綴")可以將配置文件中的配置自動(dòng)與實(shí)體進(jìn)行映射

application.properties配置如下:

person:
  name: zhangsan
  age: 18

或者梧油,application.yml配置如下:

person:
  name: zhangsan
  age: 18

實(shí)體Bean代碼如下:

@Controller
@ConfigurationProperties(prefix = "person")
public class QuickStartController {

    private String name;
    private Integer age;

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

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

注意:使用@ConfigurationProperties方式可以進(jìn)行配置文件與實(shí)體字段的自動(dòng)映射苫耸,但需要字段必須提供set方法才可以,而使用@Value注解修飾的字段不需要提供set方法

Profile

我們?cè)陂_發(fā)Spring Boot應(yīng)用時(shí)儡陨, 通常同一套程序會(huì)被安裝到不同環(huán)境褪子, 比如:開發(fā)、測(cè)試骗村、生產(chǎn)等嫌褪。其中數(shù)據(jù)庫(kù)地址、服務(wù)器端口等等配置都不同胚股,如果每次打包時(shí)笼痛,都要修改配置文件,那么非常麻煩琅拌。profile功能就是來進(jìn)行動(dòng)態(tài)配置切換的晃痴。

  1. profile配置方式
  • 多profile文件方式
  • yml多文檔方式
  1. profile激活方式
  • 配置文件:再配置文件中配置:spring.profiles.active=dev
  • 虛擬機(jī)參數(shù):在VM options指定:-D spring.profiles.active=dev
  • 命令行參數(shù):java -jar xxx.jar --spring.profiles.active=dev

Profile使用步驟

多profile文件方式

1.首先在項(xiàng)目中配置不同環(huán)境的properties



2.然后在application.properties文件中配置如下參數(shù)即可激活profile
spring.profiles.active=pro

yml多文檔方式

---
server:
 port:8081
spring:
 profiles:dev
--- # 多環(huán)境用---區(qū)分
server:
 port:8082
spring:
 profiles:test
---
server:
 port:8083
spring:
 profiles:pro
---
spring:
 profiles:
  active:pro # 可以指定激活的環(huán)境

虛擬機(jī)參數(shù)

命令行參數(shù)

也可以直接打jar包執(zhí)行指定命令

1.找到j(luò)ar包位置,在空白處按住shift+右鍵财忽,選中'在此處打開Powershell窗口'



2.運(yùn)行命令:java -jar .\jar包名稱
java -jar .\springboot-profi1es-0.0.1-SNAPSHOT.jar --spring.profiles.active=pro


spring配置

內(nèi)部配置加載順序

Spring boot程序啟動(dòng)時(shí), 會(huì)從以下位置加載配置文件:
1.file:./config/:當(dāng)前項(xiàng)目下的/config目錄下
2.file:./ 當(dāng)前項(xiàng)目的根目錄
3.classpath:/config/:classpath的/config目錄
4.classpath:/: classpath的根目錄
加載順序?yàn)樯衔牡呐帕许樞蚱辏邇?yōu)先級(jí)配置的屬性會(huì)生效

外部配置加載順序

命令行加載配置



外部配置文件通過命令行加載配置





五即彪、SpringBoot與整合其他技術(shù)

5.1 SpringBoot整合Mybatis

5.1.1 添加Mybatis的起步依賴

<!--mybatis起步依賴-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>

5.1.2 添加數(shù)據(jù)庫(kù)驅(qū)動(dòng)坐標(biāo)

<!-- MySQL連接驅(qū)動(dòng) -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

5.1.3 添加數(shù)據(jù)庫(kù)連接信息

在application.properties中添加數(shù)據(jù)量的連接信息

#DB Configuration:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root

5.1.4 創(chuàng)建user表

在test數(shù)據(jù)庫(kù)中創(chuàng)建user表

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(50) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'zhangsan', '123', '張三');
INSERT INTO `user` VALUES ('2', 'lisi', '123', '李四');

5.1.5 創(chuàng)建實(shí)體Bean

public class User {
    // 主鍵
    private Long id;
    // 用戶名
    private String username;
    // 密碼
    private String password;
    // 姓名
    private String name;
  
    //此處省略getter和setter方法 .. ..
    
}

5.1.6 編寫Mapper

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

注意:@Mapper標(biāo)記該類是一個(gè)mybatis的mapper接口,可以被spring boot自動(dòng)掃描到spring上下文中

5.1.7 配置Mapper映射文件

在src\main\resources\mapper路徑下加入U(xiǎn)serMapper.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>

5.1.8 在application.properties中添加mybatis的信息

#spring集成Mybatis環(huán)境
#pojo別名掃描包活尊,xml配置中resultType路徑
mybatis.type-aliases-package=com.itheima.domain
#加載Mybatis映射文件隶校,xml配置中namespace路徑
mybatis.mapper-locations=classpath:mapper/*Mapper.xml

5.1.9 編寫測(cè)試Controller

@Controller
public class MapperController {

    @Autowired
    private UserMapper userMapper;

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

}

5.2 SpringBoot整合Junit

5.2.1 添加Junit的起步依賴

<!--測(cè)試的起步依賴-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

5.2.2 編寫測(cè)試類

package com.itheima.test;

import com.itheima.MySpringBootApplication;
import com.itheima.domain.User;
import com.itheima.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApplication.class)
public class MapperTest {

    @Autowired
    private UserMapper userMapper;

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

}

其中,

SpringRunner繼承自SpringJUnit4ClassRunner蛹锰,使用哪一個(gè)Spring提供的測(cè)試測(cè)試引擎都可以

public final class SpringRunner extends SpringJUnit4ClassRunner 

@SpringBootTest的屬性指定的是引導(dǎo)類的字節(jié)碼對(duì)象

5.3 SpringBoot整合Spring Data JPA

5.3.1 添加Spring Data JPA的起步依賴

<!-- springBoot JPA的起步依賴 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

5.3.2 添加數(shù)據(jù)庫(kù)驅(qū)動(dòng)依賴

<!-- MySQL連接驅(qū)動(dòng) -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

5.3.3 在application.properties中配置數(shù)據(jù)庫(kù)和jpa的相關(guān)屬性

#DB Configuration:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root

#JPA Configuration:
spring.jpa.database=MySQL
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy

5.3.4 創(chuàng)建實(shí)體配置實(shí)體

@Entity
public class User {
    // 主鍵
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    // 用戶名
    private String username;
    // 密碼
    private String password;
    // 姓名
    private String name;
 
    //此處省略setter和getter方法... ...
}

5.3.5 編寫UserRepository

public interface UserRepository extends JpaRepository<User,Long>{
    public List<User> findAll();
}

5.3.6 編寫測(cè)試類

@RunWith(SpringRunner.class)
@SpringBootTest(classes=MySpringBootApplication.class)
public class JpaTest {

    @Autowired
    private UserRepository userRepository;

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

}

注意:如果是jdk9深胳,執(zhí)行報(bào)錯(cuò)

原因:jdk缺少相應(yīng)的jar

解決方案:手動(dòng)導(dǎo)入對(duì)應(yīng)的maven坐標(biāo),如下:

<!--jdk9需要導(dǎo)入如下坐標(biāo)-->
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

5.4 SpringBoot整合Redis

5.4.1 添加redis的起步依賴

<!-- 配置使用redis啟動(dòng)器 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

5.4.2 配置redis的連接信息

#Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379

5.4.3 注入RedisTemplate測(cè)試redis操作

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootJpaApplication.class)
public class RedisTest {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void test() throws JsonProcessingException {
        //從redis緩存中獲得指定的數(shù)據(jù)
        String userListData = redisTemplate.boundValueOps("user.findAll").get();
        //如果redis中沒有數(shù)據(jù)的話
        if(null==userListData){
            //查詢數(shù)據(jù)庫(kù)獲得數(shù)據(jù)
            List<User> all = userRepository.findAll();
            //轉(zhuǎn)換成json格式字符串
            ObjectMapper om = new ObjectMapper();
            userListData = om.writeValueAsString(all);
            //將數(shù)據(jù)存儲(chǔ)到redis中铜犬,下次在查詢直接從redis中獲得數(shù)據(jù)舞终,不用在查詢數(shù)據(jù)庫(kù)
            redisTemplate.boundValueOps("user.findAll").set(userListData);
            System.out.println("===============從數(shù)據(jù)庫(kù)獲得數(shù)據(jù)===============");
        }else{
            System.out.println("===============從redis緩存中獲得數(shù)據(jù)===============");
        }

        System.out.println(userListData);

    }

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末轻庆,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子敛劝,更是在濱河造成了極大的恐慌余爆,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件夸盟,死亡現(xiàn)場(chǎng)離奇詭異蛾方,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)上陕,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門桩砰,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人释簿,你說我怎么就攤上這事亚隅。” “怎么了辕万?”我有些...
    開封第一講書人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵枢步,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我渐尿,道長(zhǎng)醉途,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任砖茸,我火速辦了婚禮隘擎,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘凉夯。我一直安慰自己货葬,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開白布劲够。 她就那樣靜靜地躺著震桶,像睡著了一般。 火紅的嫁衣襯著肌膚如雪征绎。 梳的紋絲不亂的頭發(fā)上蹲姐,一...
    開封第一講書人閱讀 51,754評(píng)論 1 307
  • 那天,我揣著相機(jī)與錄音人柿,去河邊找鬼柴墩。 笑死,一個(gè)胖子當(dāng)著我的面吹牛凫岖,可吹牛的內(nèi)容都是我干的江咳。 我是一名探鬼主播,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼哥放,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼歼指!你這毒婦竟也來了爹土?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤东臀,失蹤者是張志新(化名)和其女友劉穎着饥,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體惰赋,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡宰掉,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了赁濒。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片轨奄。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖拒炎,靈堂內(nèi)的尸體忽然破棺而出挪拟,到底是詐尸還是另有隱情,我是刑警寧澤击你,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布玉组,位于F島的核電站,受9級(jí)特大地震影響丁侄,放射性物質(zhì)發(fā)生泄漏惯雳。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一鸿摇、第九天 我趴在偏房一處隱蔽的房頂上張望石景。 院中可真熱鬧世囊,春花似錦竟痰、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)往史。三九已至,卻和暖如春佛舱,著一層夾襖步出監(jiān)牢的瞬間怠堪,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工名眉, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人凰棉。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓损拢,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親撒犀。 傳聞我的和親對(duì)象是個(gè)殘疾皇子福压,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容