- Spring Boot 基礎


>> Spring Boot 簡介

1、Spring Boot 是什麼

隨着動態語言的流行 (Ruby、Groovy、Scala、Node.js),Java 的開發顯得格外的笨重:繁多的配置、低下的開發效率、複雜的部署流程以及第三方技術集成難度大;
.
在上述環境下,Spring Boot 應運而生;它使用“習慣優於配置”(項目中存在大量的配置,此外還內置了一個習慣性的配置,讓你無需手動進行配置)的理念讓你的項目快速的運行起來;使用 Spring Boot 很容易創建一個獨立運行(運行 Jar,內嵌 Servlet 容器)準生產級別的基於 Spring 框架的項目,使用 Spring Boot 你可以不用或者只需很少的 Spring 配置;
.
使用 Spring Boot 很容易創建一個獨立運行的jar包,它內置了servlet容器(tomcat/jboss等),也就是從現在開始不再出現war包,只用jar包來部署了;
.
SpringBoot讓Java具備了開箱即用的特性,減少了大量的配置,加速Java應用程序的開發;

使用Java創建項目的時候,配置文件比較複雜,開發效率低,集成第三方技術的難度大;

SpringBoot簡化了spring應用開發的過程;它使用約定優於配置的開發方式,將Spring、SpringMVC等的一系列模板化的配置文件封裝起來,我們創建Java項目的時候,直接根據項目需要選擇相應的啓動器,就可以快速的啓動一個項目,我們不需要再進行復雜的配置了,或者只需要進行很少的配置來替換SpringBoot提供的默認配置;SpringBoot對主流開發框架也提供了無配置集成;

SpringBoot內置了Tomcat和jetty容器,所以我們創建好的項目不用再打包成war包,然後部署到服務器上去運行,直接打包成jar包獨立運行就可以了;

缺點:
1、版本更新速度快,一些模塊的改動比較大;
2、由於不用自己進行配置了,報錯時,很難定位;


2、Spring Boot 優缺點

優點:

  • 快速構建項目;
  • 對主流開發框架的無配置集成:kafka、Mybatis、Hibernate等;
  • 項目可獨立運行,無需外部依賴 Servlet 容器:不用外部的Tomcat了;
  • 提供運行時的應用監控
  • 極大地提高了開發、部署效率:後期結合Docker效率就更高了;
  • 與雲計算的天然集成

缺點:

  • 版本迭代速度很快,一些模塊改動很大
  • 由於不用自己做配置,報錯時很難定位
  • 網上現成的解決方案比較少

3、約定俗成

1、SpringMVC需要配置<context:component-scan />指定批量掃描路徑;但是使用SpringBoot沒有配置掃描路徑,是因爲SpringBoot能識別到@SpringBootApplication註解,這個註解註釋的類在哪個包下,就掃描哪個包;

2、靜態資源文件都放在resources/static目錄下;

3、頁面都放在resources/templates目錄下;前綴默認就是resources/templates,後綴默認是.html

4、mybatis的mapper.xml放在resources/mapper目錄下;

4、創建一個Spring Boot應用程序

使用Spring初始化器創建一個SpringBoot項目;

  • 創建Spring Starter Project:
    在這裏插入圖片描述

  • 填寫項目信息:
    在這裏插入圖片描述
    在這裏插入圖片描述

  • 項目目錄介紹:圖片來源
    在這裏插入圖片描述

  • 創建完的項目pom文件報錯:
    在這裏插入圖片描述

  • pom.xml 文件中的 properties 加入maven jar 插件的版本號即可;
    在這裏插入圖片描述

  • 程序的入口:只要類上有@SpringBootApplication註解,並且main函數上調用的SpringApplication.run()方法,就表示這個應用程序具備了SpringBoot的核心;這個類就是SpringBoot程序的入口;
    在這裏插入圖片描述

  • 右鍵運行:
    在這裏插入圖片描述

  • 瀏覽器訪問:localhost:8080即可;

  • 神奇之處:
    沒有配置 web.xml
    沒有配置 application.xml,Spring Boot 幫你配置了
    沒有配置 application-mvc.xml,Spring Boot 幫你配置了
    沒有配置 Tomcat,Spring Boot 內嵌了 Tomcat 容器


5、常用配置

https://www.funtl.com/zh/spring-boot/Spring-Boot-常用配置.html#本節視頻

(1)自定義 Banner: 修改 Spring Boot 啓動時的默認的啓動圖案;

(2)Spring Boot 的配置文件:
Spring Boot 項目使用一個全局的配置文件 application.properties 或者是 application.yml(一般使用這個),在 resources 目錄下或者類路徑下的 /config 下,一般我們放到 resources 下;

修改 Tomcat 的端口爲 9090,並將默認的訪問路徑 “/” 修改爲 “boot”,可以在 application.yml 中添加:
在這裏插入圖片描述
瀏覽器訪問:http://localhost:9090/boot/

(3)查看自動配置:
在這裏插入圖片描述
查看web下的ServerProperties類,裏面配置的屬性就是用來在yml配置文件中進行配置的;
@ConfigurationProperties( prefix = "server",ignoreUnknownFields = true)

(4)Starter Pom
Spring Boot 爲我們提供了簡化企業級開發絕大多數場景的 starter pom ,只要使用了應用場景所需要的 starter pom ,相關的技術配置將會消除,就可以得到 Spring Boot 爲我們提供的自動配置的 Bean;

父級的pom是spring-boot-starter-parent,項目若想成爲springboot項目就必須依賴該父pom;spring-boot-starter-parent依賴spring-boot-dependenciesspring-boot-dependencies裏面的維護了各個依賴的版本;

所以依賴了springboot的超級pom:spring-boot-starter-parent的pom中可以不用再指定version;不需要我們再手動維護主流框架的版本號了,只需要修改spring boot的parent的版本號即可,它更新,我們就自動更新;因爲spring會測試這些主流框架和spring之間的兼容性好不好;
在這裏插入圖片描述

(5)日誌配置
Spring Boot 對各種日誌框架都做了支持,我們可以通過配置來修改默認的日誌的配置;

默認情況下,Spring Boot 使用 Logback 作爲日誌框架;

    logging:
      file: ../logs/spring-boot-hello.log   // 日誌地址
      level.org.springframework.web: DEBUG  // 日誌級別

在這裏插入圖片描述

(6)關閉特定配置: 使用@SpringBootApplication註解的exclude屬性;

@SpringBootApplication註解表明當前類是Springboot的引導類;

exclude屬性:排除指定的自動配置;

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
starter啓動器中內容都是自動配置的,自動配置一加載,就一定會生效;比如pom文件中添加了MySQL的啓動器,MySQL就需要配置數據源,不配置的話就會報錯;但是如果創建的是前端項目,雖然添加了MySQL的依賴,但是不需要使用數據庫,這時候就可以使用exclude屬性把數據源的配置給排除掉,表示不要自動配置數據源;
在這裏插入圖片描述


>> Spring Boot 整合Thymeleaf

~ Thymeleaf簡介

Thymeleaf是一個模板引擎,類似Velocity、FreeMarker ,可以完全替代JSP;

Thymeleaf優點:

1、Thymeleaf 在有網絡和無網絡的環境下皆可運行,即它可以讓美工在瀏覽器查看頁面的靜態效果,也可以讓程序員在服務器查看帶數據的動態頁面效果,而JSP必須在servlet容器啓動才能看;
這是由於它支持 html 原型,然後在 html 標籤裏增加額外的屬性來達到模板 + 數據的展示方式;瀏覽器解釋 html 時會忽略未定義的標籤屬性,所以 thymeleaf 的模板可以靜態地運行;當有數據返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示;

.jsp
	${user.name}
.html  // themeleaf支持HTML原型;
	<span th:text="${username}"">zxj</span> //能從服務器讀到數據就顯示th:的模板數據,讀不到就直接顯示zxj;
	th:text="${username}"

2、無縫對接JSP;
Thymeleaf 開箱即用的特性;它提供標準和 Spring 標準兩種方言,可以直接套用模板實現 JSTL、 OGNL 表達式效果,避免每天套模板、改 JSTL、改標籤的困擾;同時開發人員也可以擴展和創建自定義的方言;

3、天然支持SpringMVC;
Thymeleaf 提供 Spring 標準方言和一個與 SpringMVC 完美集成的可選模塊,可以快速的實現表單綁定、屬性編輯器、國際化等功能;

爲什麼使用Themeleaf:
jar包運行不了JSP;

微服務架構,一個服務一個應用進行部署;以應用程序的方式來部署web程序,Java程序要和docker結合,所以最後部署出來的應用應該稱之爲docker-app;要提供web服務,但是又想以jar包的方式發佈,jar包不是web應用程序,要賦予jar包web的能力,程序就要用到內嵌的servlet容器來做到這個效果;

如果希望以 Jar 形式發佈模塊則儘量不要使用 JSP 相關知識,這是因爲 JSP 在內嵌的 Servlet 容器上運行有一些問題 (內嵌 Tomcat、 Jetty 不支持 Jar 形式運行 JSP,Undertow 不支持 JSP)

~ 第一個Themeleaf模板頁

參考鏈接

1、添加依賴:thymeleaf啓動器和nekohtml的依賴;

nekohtml:正常情況下配置文件中的spring.thymeleaf.mode=HTML5,使用HTML5就要使用嚴格的HTML模式:一定要符合w3c標準:每個標籤必須要有結束符;

<dependency>
	<groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
	<groupId>net.sourceforge.nekohtml</groupId>
	<artifactId>nekohtml</artifactId>
	<version>1.9.22</version>
</dependency>

2、添加配置:application.yml

spring:
  thymeleaf:
    cache: false  # 開發時關閉緩存,不然沒法看到實時頁面
    mode: HTML    # 用非嚴格的 HTML
    encoding: UTF-8
    servlet:
      content-type: text/html

3、創建一個HTML文件,在文件頭部加入標籤引入thymeleaf引擎,聲明當前頁面是一個thymeleaf模板引擎頁面;
所有的thymeleaf模板引擎頁面使用thymeleaf的時候,都要使用th:開頭;

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head></head> 
<body>
	<span th:text="${user.username}">張三</span>
</body>  
</html>

4、創建Controller

@Controller
public class MainController {
	@RequestMapping(value = {"", "index"}, method = RequestMethod.GET)
	public String index(Model model) {
		User user = new User();
		user.setUsername("zxj");
		model.addAttribute("user", user);
		return "index";
	}
}
------
public class User implements Serializable {
	private String username;
	public String getUsername() { return username;}
	public void setUsername(String username) { this.username = username;}
}

5、啓動項目,瀏覽器訪問:http://localhost:9090/thymeleaf/index

~ 整合mybatis

參考鏈接

1、Spring Boot 整合 數據庫連接池 - Druid:

Druid 是目前最好的數據庫連接池,在功能、性能、擴展性方面,都超過其他數據庫連接池,包括
DBCP、C3P0、BoneCP、Proxool、JBoss DataSource;

(1)在 pom.xml 文件中引入 druid-spring-boot-starter 依賴和數據庫連接依賴;

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

(2)在 application.yml 中配置數據庫連接:

spring:
  datasource:
    druid:
      url: jdbc:mysql://ip:port/dbname?useUnicode=true&characterEncoding=utf-8&useSSL=false
      username: root
      password: 123456
      initial-size: 1
      min-idle: 1
      max-active: 20
      test-on-borrow: true
      # MySQL 8.x: com.mysql.cj.jdbc.Driver
      driver-class-name: com.mysql.jdbc.Driver

2、Spring Boot 整合 tk.mybatis :

tk.mybatis 是在 MyBatis 框架的基礎上提供了很多工具,可以簡化我們對Mybatis的操作,讓開發更加高效;

(1)添加依賴:

<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.0.2</version>
</dependency>

(2)添加配置:

mybatis:
    type-aliases-package: 實體類的存放路徑,如:com.funtl.hello.spring.boot.entity
    mapper-locations: classpath:mapper/*.xml  

(3)創建一個通用的父級接口:主要作用是讓 DAO 層的接口繼承該接口,以達到使用 tk.mybatis 的目的;

注意:該接口不能被spring掃描到,否則會出錯!就是說,這個接口不能放在啓動類所在包下;

public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
}

3、Spring Boot 整合 PageHelper

PageHelper 是 Mybatis 的分頁插件,支持多數據庫、多數據源,可以簡化數據庫的分頁查詢操作,整合過程也極其簡單,只需引入依賴即可;

pom.xml 文件中引入 pagehelper-spring-boot-starter 依賴

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.5</version>
</dependency>

4、使用 MyBatis 的 Maven 插件生成代碼:

我們無需手動編寫 實體類DAOXML 配置文件,只需要使用 MyBatis 提供的一個 Maven 插件就可以自動生成所需的各種文件便能夠滿足基本的業務需求,如果業務比較複雜只需要修改相關文件即可;

pom.xml 文件中增加 mybatis-generator-maven-plugin 插件:

<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.5</version>
            <configuration>
                <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                <overwrite>true</overwrite>
                <verbose>true</verbose>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>${mysql.version}</version>
                </dependency>
                <dependency>
                    <groupId>tk.mybatis</groupId>
                    <artifactId>mapper</artifactId>
                    <version>3.4.4</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

<configurationFile>指定自動生成所需的配置文件路徑;

5、自動生成的配置:generatorConfig.xml

src/main/resources/generator/ 目錄下創建 generatorConfig.xml 配置文件,指定數據源等信息;
完整配置案例

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!-- 引入數據庫連接配置 -->
    <properties resource="jdbc.properties"/>

    <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        
        <!-- 配置 tk.mybatis 插件,讓所有自動生成的mapper實現通用父級MyMapper接口 -->
        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="com.funtl.utils.MyMapper"/>
        </plugin>

        <!-- 配置數據庫連接 -->
        <jdbcConnection
                driverClass="${jdbc.driverClass}"
                connectionURL="${jdbc.connectionURL}"
                userId="${jdbc.username}"
                password="${jdbc.password}">
        </jdbcConnection>

        <!-- 配置實體類存放路徑 -->
        <javaModelGenerator targetPackage="com.funtl.hello.spring.boot.entity" targetProject="src/main/java"/>

        <!-- 配置 XML 存放路徑 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>

        <!-- 配置 DAO 存放路徑 -->
        <javaClientGenerator
                targetPackage="com.funtl.hello.spring.boot.mapper"
                targetProject="src/main/java"
                type="XMLMAPPER"/>

        <!-- 配置需要指定生成的數據庫和表,% 代表所有表 -->
        <table catalog="myshop" tableName="%">
            <!-- mysql 配置:所有表的主鍵都是id,identity表示支持自動生成 -->
            <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>

6、jdbc.properties 數據源配置

src/main/resources 目錄下創建 jdbc.properties 數據源配置;

# MySQL 8.x: com.mysql.cj.jdbc.Driver
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://ip:port/dbname?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=123456

7、插件自動生成命令:

mvn mybatis-generator:generate
在這裏插入圖片描述

8、使用 tk.mybatis 測試mybatis操作數據庫

(1)修改入口類:在類上增加註解@MapperScan來指定mapper接口的包路徑;

@SpringBootApplication
@MapperScan(basePackages = "com.funtl.hello.spring.boot.mapper")
public class HelloSpringBootApplication {
    public static void main(String[] args) { SpringApplication.run(HelloSpringBootApplication.class, args); }
}

(2)創建測試類:

@RunWith(SpringRunner.class)
// 指定啓動類,爲了讓測試類能裝載到SpringBoot的配置文件application.yml;
@SpringBootTest(classes = HelloSpringBootApplication.class)
@Transactional  // 加入事務
@Rollback       // 加入事務
public class MyBatisTests {
    @Autowired // 注入數據查詢接口
    private TbUserMapper tbUserMapper;
    @Test      // 測試插入數據
    public void testInsert() {
        // 構造一條測試數據
        TbUser tbUser = new TbUser();
        tbUser.setUsername("Lusifer");  // ......
        tbUserMapper.insert(tbUser);
    }
    @Test       // 測試刪除數據
    public void testDelete() {
        // 構造條件,等同於 DELETE from tb_user WHERE username = 'Lusifer'
        Example example = new Example(TbUser.class);
        example.createCriteria().andEqualTo("username", "Lusifer");
        tbUserMapper.deleteByExample(example);
    } 
    @Test      // 測試修改數據
    public void testUpdate() {
        // 構造條件
        Example example = new Example(TbUser.class);
        example.createCriteria().andEqualTo("username", "Lusifer");
        // 構造一條測試數據
        TbUser tbUser = new TbUser();
        tbUser.setUsername("LusiferNew");  // ......
        tbUserMapper.updateByExample(tbUser, example);
    } 
    @Test    // 測試查詢集合
    public void testSelect() {
        List<TbUser> tbUsers = tbUserMapper.selectAll();
        for (TbUser tbUser : tbUsers) {
            System.out.println(tbUser.getUsername());
        }
    } 
    @Test    // 測試分頁查詢
    public void testPage() {
        // PageHelper 使用非常簡單,只需要設置頁碼和每頁顯示筆數即可
        PageHelper.startPage(0, 2);
        // 設置分頁查詢條件  
        Example example = new Example(TbUser.class);
        PageInfo<TbUser> pageInfo = new PageInfo<>(tbUserMapper.selectByExample(example));
        // 獲取查詢結果
        List<TbUser> tbUsers = pageInfo.getList();
        for (TbUser tbUser : tbUsers) {
            System.out.println(tbUser.getUsername());
        }
    }
}

文章參考博客視頻教程

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章