Spring Boot入門
目錄
1. Spring Boot概述 4
1.1. Spring Boot是什么 4
1.2. Spring Boot框架出現的背景 4
1.3. Spring Boot的作用是什么 5
1.4. Spring Boot的特點 5
1.5. Spring Boot學習的前提 5
1.6. Spring Boot准備工具 6
1.7. 參考資料 6
2. Spring Boot的入門 6
2.1. 簡單配置入門 6
2.1.1. 配置流程 6
2.1.2. 注意事項 13
2.2. 使用@SpringBootApplication注解配置 13
2.2.1. 配置流程 14
2.2.2. 注意事項 16
2.3. 熱啟動 17
3. SpringBoot常見基礎包說明 17
4. 常用API說明 18
4.1. SpringApplication類 18
4.1.1. 說明 18
4.1.2. 示例代碼 18
4.2. @EnableAutoConfiguration注解 18
4.2.1. 注解的聲明 18
4.2.2. 作用 19
4.2.3. 屬性說明 19
4.3. @SpringBootApplication注解 20
4.3.1. 注解聲明 20
4.3.2. 屬性說明 20
4.4. @AutoConfigureBefore注解 21
4.4.1. 注解說明 21
4.4.2. 示例代碼 21
4.5. @AutoConfigureAfter注解 24
4.6. @SpringBootTest注解 24
4.6.1. 注解說明 24
4.6.2. 示例代碼 24
5. SpringBoot配置流程(重點) 25
5.1. 概述 25
5.2. 配置流程說明 25
5.3. 配置流程圖 27
6. 配置文件 28
6.1. application.propertie配置文件 28
6.1.1. application.propertie說明 28
6.1.2. application.propertie多配置文件支持 28
6.2. application.yml配置文件 29
6.2.1. application.yml說明 29
6.2.2. application.yml多配置文件支持 30
6.3. 配置示例-Spring數據源配置 30
6.4. 獲得自定義application.properties聲明的屬性值 33
7. Spring Boot視圖 35
7.1. 視圖概述 35
7.2. FreeMarker模板引擎的配置 36
7.2.1. 配置流程 36
7.2.2. 注意事項 37
7.3. Thymeleaf模板引擎的配置 39
7.3.1. 配置流程 39
7.3.2. 注意事項 40
7.4. JSP視圖配置(極不推薦) 40
7.4.1. 配置流程 40
7.4.2. 注意事項 41
7.5. 默認讀取的靜態資源路徑 41
8. SpringBoot整合 42
8.1. 使用的數據庫SQL 42
8.2. SpringBoot整合Mybatis 42
8.2.1. 整合說明 42
8.2.2. 配置流程 43
8.3. Spring Boot整合Spring-Data-JPA 49
8.3.1. 配置步驟 49
8.3.2. 注意事項 56
9. 打包部署 57
9.1. 使用jar發布應用 57
9.1.1. 配置步驟 57
9.1.2. 修改內嵌Tomcat的參數 59
9.2. 使用war發布應用 59
9.2.1. 配置流程 59
9.2.2. 注意事項 62
1. Spring Boot概述
1.1. Spring Boot是什么
Spring Boot是一套基於Spring框架的微服務框架。
1.2. Spring Boot框架出現的背景
由於Spring是一個輕量級的企業開發框架,主要的功能就是用於整合和管理其他框架。
但隨着整合的框架越來越多,Spring的整合配置也日益繁瑣。在這個情況下,Spring團體有了一個想法:就是將平時主流使用到的框架的整合配置預先寫好,然后通過簡單的幾個參數就可以實現框架的快速整合。
這個想法催生Spring boot框架。
我們將這個實現了各種主流框架與Spring的自動整合的框架。
1.3. Spring Boot的作用是什么
就是大大減少了Spring與其他框架整合的代碼,也實現了Spring開發的Web應用的快速部署。(使用jar發布web應用)
1.4. Spring Boot的特點
1.實現了各種主流的框架的快速整合
2.實現了Spring的應用的快速部署,使用Spring Boot的Web應用可以以Jar的方式部署。
Spring是如何實現使用jar發布web 應用的呢?
答:就是通過直接將tomcat服務器打包到我們的web應用里面實現了。
1.5. Spring Boot學習的前提
1.由於Spring Boot的最小配置都是基於SpringMVC框架的,所以學習Spring Boot先要有Spring和SpringMVC框架的基礎。
2.SpringBoot默認不推薦使用JSP視圖,官方推薦使用Thymeleaf或者Freemarker模板引擎。本文檔沒有對這兩個模板引擎作詳細介紹。
3.SpringBoot使用了Maven 或者Gradle管理需要的jar包,沒有提供zip壓縮包的發布形式,所以學習SpringBoot必須要學習Maven或者Gradle構建工具,現在主流使用的是Maven,所以學習Maven就可以了。
4.Spring Boot中可以使用Spring框架的所有注解。如果沒有學過純注解Spring框架配置,需要先學習Spring純注解的配置。
所謂的純注解:就是一個Spring配置文件都沒有的配置。
涉及Spring框架的純注解配置類常用注解如下:
注解名 |
說明 |
@Configuration |
聲明一個配置類,配置類的功能等同spring的配置文件(重點) |
@Bean |
將沒有聲明 @Component/@Controller/@Serivce/@Repository的類加入到Spring容器
等同於Spring配置文件的<bean>標簽 |
@PropertySource |
在Spring的配置里讀取,增加的這個注解,可以使用@Value注解獲得properties文件的內容
|
@Value |
獲得上下文中,Properties文件的內容 等同與Spring配置文件的 ${key} |
@ComponentScan |
用於掃描類,創建對象到Spring容器中 等同Spring配置文件 <context:component-scan>
|
@ConditionalOnMissingBean(Spring Boot) |
表示如果Spring容器已經有該類的對象就不執行創建對象的方法再創建一次了。 |
1.6. Spring Boot准備工具
學習Spring Boot建議使用Eclipse安裝STS插件或者直接使用STS開發工具。
下載官網:https://spring.io/tools/sts
1.7. 參考資料
本文檔編寫參考了
1.Spring官方的示例代碼,地址如下:
https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples
2.SpringBoot官方參考文檔,地址如下:
https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started
3.spring boot自動配置的框架,路徑如下:
https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters
2. Spring Boot的入門
2.1. 簡單配置入門
2.1.1. 配置流程
1.新建一個maven項目
|
2.填寫創建項目的信息,注意使用jar的方式創建項目就可以
|
--編寫項目信息
|
3.到spring boot官方復制pom的依賴到pom.xml文件
網站地址為:http://projects.spring.io/spring-boot/
|
--選擇參數
|
pom.xml文件內容如下:
<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>cn.gzsxt</groupId> <artifactId>spring-boot-demo-01</artifactId> <version>1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.4.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project> |
注意:如果復制spring boot依賴到pom.xml報以下錯誤
|
更新一下項目即可.如下圖
|
4.編寫一個簡單的Java類
package hello; import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; import org.springframework.stereotype.*; import org.springframework.web.bind.annotation.*;
//聲明@Controller存儲類型注解,表示SampleController類啟動是,對象會加載到Spring容器 @Controller //聲明@EnableAutoConfiguration,表示程序使用Springboot默認的配置 @EnableAutoConfiguration public class SampleController { /** * 表示如果訪問路徑/,返回字符串Hello World! */ @RequestMapping("/") @ResponseBody String home() { return "Hello World!"; } public static void main(String[] args) throws Exception { //啟動Spring Boot程序 SpringApplication.run(SampleController.class, args);
} } |
5.啟動Spring Boot程序
|
6.啟動成功,控制台提示我們使用8080端口訪問
|
7.使用瀏覽器訪問8080端口
|
2.1.2. 注意事項
maven是需要聯網下載的jar包的。注意一下網絡是否暢通。
因為SpringBoot是通過jar發布的。而jar的程序的入口是main方法。所以SpringBoot必須要提供一個類,可以從main方法啟動項目。這個類就是SpringApplication
SpringBoot框架是基於Spring框架的。我們知道Spring框架是通過加載配置類或者配置文件,創建容器,在將創建的對象放在容器里面。意味着SpringBoot也是必須需要配置類的。只是配置類已經內置實現了!!使用SpringApplication類啟動程序,需要通過@EnableAutoConfiguration,表示自動加載默認的配置類。。
2.2. 使用@SpringBootApplication注解配置
上面的示例有一個問題,一個Controller需要手工配置一次,代碼如下:
SpringApplication.run(SampleController.class, args); |
問題:啟動的Controller只有一個,如果一個項目需要將多個類掃描到Spring的容器中如何解決呢?
答:使用@SpringBootApplication注解來配置。
入口類使用@SpringBootApplication注解,啟動項目時,SpringBoot框架會掃描入口類的加了@SpringBootApplication注解的入口類的同級目錄和子目錄的組件類的對象到Spring容器。
2.2.1. 配置流程
1.創建一個Maven項目
|
2.將Spring boot的依賴復制到pom.xml文件
<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>cn.gzsxt</groupId> <artifactId>spring-boot-demo-02</artifactId> <version>1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.4.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project> |
3.將項目簡單分層
|
4.在cn.gzsxt文件夾下創建一個入口類Application.java
package cn.gzsxt; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
//使用SpringBoot自動配置程序 @SpringBootApplication public class Application {
public static void main(String[] args) { //執行當前類,根據@SpringBootApplication的配置,啟動SpringBoot程序 SpringApplication.run(Application.class, args); } }
|
5.創建一個Controller,業務控制器
package cn.gzsxt.controller;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;
@Controller public class HelloController {
@RequestMapping(value="/") @ResponseBody public String say(){ //返回字符串 return "HelloWorld!"; } }
|
6.啟動項目,控制台返回訪問端口
|
7.使用瀏覽器訪問
|
2.2.2. 注意事項
1.為什么放在cn.gzsxt包下呢?
答:@SpringBootApplication的配置默認根據入口類的所在位置掃描包以及入口類所在位置以及子包范圍。
根據以上配置,使用@SpringBootApplication配置Spring boot項目。會自動掃描cn.gzsxt.*下面HelloController類。
從而可以得出使用@SpringBootApplication可以實現將多個類掃描到Spring容器里面。
根據代碼分析得到@SpringBootApplication做了三件事情:
- 聲明當前類允許自動配置
@EnableAutoConfiguration |
- 聲明當前類是一個配置類,因為掃描組件注解只能放在配置類上面
@SpringBootConfiguration 等同 @Configuration |
- 聲明一個掃描組件注解,將所有組件類創建對象到容器
@ComponentScan |
2.3. 熱啟動
使用spring-boot:run命令啟動項目,每次修改完成代碼都要重新啟動。是非常麻煩的。
我們就有那么一個想法,能不能修改完代碼,程序不用重啟直接自動編譯了?
我們將修改完代碼開發工具自動編譯的過程稱為,熱啟動。
Spring boot是支持熱啟動的。只有加入以下依賴就可以
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <!-- optional=true,依賴不會傳遞,該項目依賴devtools; 之后依賴該項目的項目如果想要使用devtools,需要重新引入 --> <optional>true</optional> </dependency> |
3. SpringBoot常見基礎包說明
|
1.spring-boot-starter-web-1.5.4.RELEASE.jar:僅僅存放web項目需要的jar包的pom.xml
2.spring-boot-starter-1.5.4.RELEASE.jar:僅僅存放springboot最小核心需要的jar包的pom.xml
3.spring-boot-starter-logging-1.5.4.RELEASE.jar:僅僅存放日志輸出需要的jar包的pom.xml
4.spring-boot-1.5.4.RELEASE.jar:springboot框架核心包
spring-boot-autoconfigure-1.5.4.RELEASE.jar:默認支持的自動配置的框架的配置包(重點)
重點是spring-boot-autoconfigure包,因為spring boot的所有內置的自動配置的類都在里面!
4. 常用API說明
4.1. SpringApplication類
4.1.1. 說明
作用:用於啟動Spring Boot的程序,根據傳入的類聲明的注解來決定不同的啟動方式。
4.1.2. 示例代碼
package cn.gzsxt; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
//使用SpringBoot自動配置程序 @SpringBootApplication public class Application {
public static void main(String[] args) { //執行當前類,根據@SpringBootApplication的配置,啟動SpringBoot程序 SpringApplication.run(Application.class, args); } } |
4.2. @EnableAutoConfiguration注解
4.2.1. 注解的聲明
@SuppressWarnings("deprecation") @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import(EnableAutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration { String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; Class<?>[] exclude() default {}; String[] excludeName() default {}; } |
4.2.2. 作用
@EnableAutoConfiguration注解的作用是:啟動程序時,告訴SpringApplication啟動對象使用SpringBoot的默認配置。
只要在SpringBoot項目的入口類配置了@EnableAutoConfiguration,在SpringBoot框架啟動是就會自動根據你導入的jar包來加載spring-boot-autoconfigure-1.5.4.RELEASE-sources.jar中的xxxAutoconfiguration配置類,使用其默認配置。
|
4.2.3. 屬性說明
exclude屬性:使用Class格式的方式,排除默認自動啟動中不需要的配置類
excludeName屬性:使用類的限制名的方式,排序默認自動啟動中不需要的配置類
4.3. @SpringBootApplication注解
4.3.1. 注解聲明
@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, attribute = "exclude") Class<?>[] exclude() default {}; @AliasFor(annotation = EnableAutoConfiguration.class, attribute = "excludeName") String[] excludeName() default {}; @AliasFor(annotation = ComponentScan.class, attribute = "basePackages") String[] scanBasePackages() default {}; @AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses") Class<?>[] scanBasePackageClasses() default {}; } |
根據注解的聲明可以得出:@SpringBootApplication注解也是啟動Springboot的默認配置。只是在@EnableAutoConfiguration注解的基礎上增加了掃描包@ComponentScan的這個注解。實現了並且掃描指定范圍的類創建對象到容器里面。
4.3.2. 屬性說明
1.basePackages屬性
@SpringBootApplication默認掃描的范圍是使用該注解的當前的類的包以及子包,如果要指定其他范圍的包,可以是basePackages指定。
2.basePackageClasses屬性
用於精確指定哪些類需要創建對象加載到Spring容器里面。
3.exclude屬性
通過Class的方式排除不掃描的類,就是該類不創建對象。
4.excludeName屬性
通過類的全限制名的方式,排除不掃描的類,指定的類不會在容器中創建對象。
4.4. @AutoConfigureBefore注解
4.4.1. 注解說明
指定在SpringBoot框架自動配置的配置類執行完成之前,執行指定的自定義的配置類。
如果放在Application入口類,表示在所有自動配置的配置類還沒有可以就先加載自定義的配置類。
@AutoConfigureBefore注解屬性:
value:使用類的方式指定自動配置類
name:使用類的全限制名(字符串)類指定配置類
4.4.2. 示例代碼
1.創建一個普通的類,沒有任何注解
package cn.gzsxt.utils;
/** * 創建一個沒有掃描注入容器注解的類 * @author ranger * */ public class TestUtils { /** * 返回測試信息 * @return */ public String test(){ return "-測試注入對象成功-"; }
}
|
2.創建一個自定義配置類,注入普通的類到Spring容器
package cn.gzsxt.config;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
package cn.gzsxt.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
import cn.gzsxt.utils.TestUtils;
/** * 創建一個自定義的配置類 * @author ranger * */ @Configuration public class MyConfiguration { /** * 返回一個對象到容器 * @return */ @Bean(name="testUtils") //表示如果Spring容器有TestUtils的對象就不執行這個方法在創建一次了。 @ConditionalOnMissingBean(TestUtils.class) public TestUtils getTestUtils(){ TestUtils testUtils=new TestUtils(); return testUtils; }
}
|
3.在入口類配置加入自定義配置類
package cn.gzsxt;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.SpringBootApplication;
import cn.gzsxt.config.MyConfiguration;
//使用SpringBoot自動配置程序 @SpringBootApplication //在自動配置的配置類之前啟動自定義的配置類 @AutoConfigureBefore(value=MyConfiguration.class) public class Application {
public static void main(String[] args) { //執行當前類,根據@SpringBootApplication的配置,啟動SpringBoot程序 SpringApplication.run(Application.class, args);
}
}
|
4.在Controller里面使用這個注入的對象
package cn.gzsxt.controller;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;
import cn.gzsxt.utils.TestUtils;
@Controller public class HelloController {
@Autowired private TestUtils testUtils;
@RequestMapping(value="/") @ResponseBody public String say(){ System.out.println(testUtils.test()); return testUtils.test(); }
}
|
5.測試,成功
|
4.5. @AutoConfigureAfter注解
指定在SpringBoot框架自動配置的配置類執行完成之后,然后執行指定的自定義的配置類。
4.6. @SpringBootTest注解
4.6.1. 注解說明
用於使用JUnit測試SpringBoot程序,啟動SpringBoot框架。測試SpringBoot一定要加上。
4.6.2. 示例代碼
package cn.gzsxt.test;
import java.sql.SQLException;
import javax.sql.DataSource;
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.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
//如果不加該注解,無法啟動SpringBoot @SpringBootTest public class DataSourceTest {
@Autowired private DataSource dataSource;
@Test public void dataSource() { try { System.out.println(dataSource.getConnection()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
}
|
5. SpringBoot配置流程(重點)
5.1. 概述
Spring Boot框架是一個將整合框架的整合代碼都寫好了的框架。所以我們要知道它的工作原理才能夠,找到各種整合框架可以配置的屬性,以及屬性對應的屬性名。
本章主要講述如何在SpringBoot框架代碼中找到application.properties配置文件的屬性值。
5.2. 配置流程說明
1.SpringBoot的spring-boot-autoconfigure-1.5.4.RELEASE.jar中編寫了所以內置支持的框架的自動整合代碼
2.所以支持的框架根據功能類型來划分包,每個包都有一個XxxxAutoConfiguration配置類,都是一個基於純注解的配置類,是各種框架整合的框架代碼。如圖所示:
|
3.如果配置的框架有默認的配置參數,都放在一個命名為XxxxProperties的屬性,如圖所示
|
4.通過項目的resources下的application.properties文件可以修改每個整合框架的默認屬性,從而實現了快速整合的目的。
|
5.3. 配置流程圖
第一步:配置一個內置整合框架的參數,先到spring-boot-autoconfigure-1.5.4.RELEASE.jar找到對應的模塊。
第二步:如果該框架有可以配置的參數,那么對應的整合模塊中一定有一個XxxxProperties類,在里面可以找可以設置的參數。
第三部:在resources源目錄下的application.properties文件里面可以修改XxxxProperties類中默認的參數。
配置流程如下:
|
6. 配置文件
Spring Boot的參數配置文件支持兩種格式。分別為application.propertie,application.yml。
配置Spring Boot時可以二選一。
application.propertie:是鍵值對風格
application.yml:是層級鍵值對風格
6.1. application.propertie配置文件
6.1.1. application.propertie說明
默認情況下,Spring Boot會加載resources目錄下的application.properties來獲得配置的參數。
6.1.2. application.propertie多配置文件支持
1.在application.properties配置文件下,增加多個application-xxx.properties文件名的配置文件,其中xxx是一個任意的字符串。
例如:
application-database.properties application-mvc.properties application-freemarker.properties |
2.在application.properties總配置文件指定,加載的多個配置文件
例如:要同時使用,四個配置文件
application.properties、 application-database.properties application-mvc.properties application-freemarker.properties |
那么在application.properties其他配置文件指定為:
spring.profiles.active=database,mvc,freemarker |
6.2. application.yml配置文件
6.2.1. application.yml說明
SpringBoot支持一種由SpringBoot框架自制的配置文件格式。后綴為yml。yml后綴的配置文件的功能和properties后綴的配置文件的功能是一致的。配置時可以二選一。
例如:配置文件:application.properties
#配置數據源 spring.datasource.url=jdbc:mysql://localhost:3306/school spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.username=root spring.datasource.password=123456 spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource #spring-data-jpa配置 #顯示SQL語句 spring.jpa.show-sql=true #表示是否需要根據view的生命周期來決定session是否關閉 spring.jpa.open-in-view=true |
可以修改為配置文件:application.yml,內容為:
#配置數據源 spring: datasource: url: jdbc:mysql://localhost:3306/school driverClassName: com.mysql.jdbc.Driver username: root password: 123456 #配置連接池 type: org.apache.commons.dbcp2.BasicDataSource #配置JPA的屬性 jpa: show-sql: true open-in-view: true |
其實application.yml配置文件就是將原來application.properties使用(.)分割的方式,改為樹狀結構,使用(:)分割。
注意:key的字段與值之間的冒號(:)后面一定要有一個空格。
6.2.2. application.yml多配置文件支持
1.在application.yml配置文件下,增加多個application-xxx.yml文件名的配置文件,其中xxx是一個任意的字符串。
例如:
application-database.yml application-mvc.yml application-freemarker.yml |
2.在application.yml總配置文件指定,加載的多個配置文件
例如:要同時使用,四個配置文件
application.yml application-database.yml application-mvc.yml application-freemarker.yml |
那么在application.yml其他配置文件指定為:
spring: profiles: active: database,mvc,freemarker |
6.3. 配置示例-Spring數據源配置
配置Spring數據源,並支持DBCP2數據源
1.在pom.xml加入支持數據源的類庫
<!-- 數據庫驅動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- dbcp2連接池 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> </dependency> <!-- Springboot測試包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> |
2.找到數據源的配置類
|
3.數據源的配置類的屬性如下
//注意這里 @ConfigurationProperties(prefix = "spring.datasource") public class DataSourceProperties implements BeanClassLoaderAware, EnvironmentAware, InitializingBean {
private ClassLoader classLoader; private Environment environment; private String name = "testdb"; private boolean generateUniqueName; //注意這里 private Class<? extends DataSource> type; private String driverClassName; private String url; private String username; private String password; private String jndiName; private boolean initialize = true; private String platform = "all"; private List<String> schema; private String schemaUsername; private String schemaPassword; private List<String> data; private String dataUsername; private String dataPassword; private boolean continueOnError = false; private String separator = ";"; private Charset sqlScriptEncoding; private EmbeddedDatabaseConnection embeddedDatabaseConnection = EmbeddedDatabaseConnection.NONE; private Xa xa = new Xa(); private String uniqueName; |
3.application.properties配置文件修改數據源參數:
#datasource spring.datasource.url=jdbc:mysql://localhost:3306/school spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.username=root spring.datasource.password=123456 #support dbcp2 datasource spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource |
1.spring.datasource這個前綴就是DataSourceProperties的@ConfigurationProperties(prefix = "spring.datasource")注解聲明的前綴
2.屬性就是DataSourceProperties對應的屬性
4.測試代碼
package cn.gzsxt.test; import java.sql.SQLException; import javax.sql.DataSource; 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.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) //SpringBoot測試要加上這個注解 @SpringBootTest public class DataSourceTest {
@Autowired private DataSource dataSource;
@Test public void dataSource() { try { System.out.println(dataSource.getConnection()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
注意事項:
<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>cn.gzsxt.springboot</groupId> <artifactId>springboot-demo-06-dbcp2</artifactId> <version>1.0</version>
<!-- 設置項目信息 --> <properties> <!-- 設置源代碼的編碼 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- 輸出的字節碼的編碼 --> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- 設置JDK的版本 --> <java.version>1.8</java.version> </properties> <!-- Spring Boot依賴的父包,包括框架基礎包的配置 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.4.RELEASE</version>
</parent>
<dependencies> <!-- 導入依賴的Web模塊SpringMVC的配置 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <!-- optional=true,依賴不會傳遞,該項目依賴devtools; 之后依賴該項目的項目如果想要使用devtools,需要重新引入 --> <optional>true</optional> </dependency>
<!-- dbcp2依賴包 -->
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId>
</dependency> <!-- mysql driver -->
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <!-- jdbc --> <!-- SpringBoot配置jdbc模塊,必須導入JDBC包的 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency>
</dependencies>
</project> |
6.4. 獲得自定義application.properties聲明的屬性值
使用@ConfigurationProperties注解可以直接獲得application.properties配置的屬性值。
@ConfigurationProperties屬性說明:
prefix屬性:表示獲得application.properties時忽略的指定的前綴,如:
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false) |
ignoreUnknownFields屬性:忽略未知的字段值。如果為true時,就是當application.properties設置的輸入找不到對應的字段時,就忽略它。
@ConfigurationProperties的使用:
1.在pom.xml導入支持的依賴包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> |
2.自定義一個TestProperties 屬性類
package cn.gzsxt.utils;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix="cn.gzsxt" ) public class TestProperties { private String path;
public String getPath() { return path; }
public void setPath(String path) { this.path = path; } } |
3.自定義一個application-test.properties文件
cn.gzsxt.path=demo-03 |
4.在application.properties指定application-test.properties配置文件
spring.datasource.url=jdbc:mysql://localhost:3306/school spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.username=root spring.datasource.password=123456 spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource spring.profiles.active=test |
5.啟動支持TestProperties類自動配置
在入口類Application增加EnableConfigurationProperties注解支持
package cn.gzsxt;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import cn.gzsxt.utils.TestProperties;
@SpringBootApplication @EnableConfigurationProperties(value=TestProperties.class) public class Application {
public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
|
6.調用配置的屬性path
package cn.gzsxt.controller; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;
import cn.gzsxt.service.StudentService; import cn.gzsxt.utils.TestProperties;
@Controller public class StudentController {
@Autowired private TestProperties testProperties;
@RequestMapping(value="/path") public String path(){ System.out.println(testProperties.getPath()+"=============="); return "index"; } } |
7.測試結果
|
7. Spring Boot視圖
7.1. 視圖概述
由於SpringBoot建議使用jar的方式發布web程序。所以不建議使用jsp視圖,也不對jsp視圖做默認的支持。
如果確實要使用JSP視圖發布Spring Boot的應用,那么需要使用war的方式發布。
Spring Boot默認自動配置支持視圖是以下的模板引擎:
7.2. FreeMarker模板引擎的配置
7.2.1. 配置流程
1.在pom.xml導入FreeMarker模板引擎依賴的包
<!-- freemarker支持包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> |
2.Spring Boot的模板引擎的默認路徑是resources/templates,所以在resources下創建一個templates文件夾。將視圖頁面放在里面
|
3.這樣Spring Boot直接就支持了返回freemarker的ftl視圖了。
@RequestMapping(value="/index") public String index(Model model,HttpSession session){ System.out.println("-測試插入數據-"); Map<String, Object> entity=new HashMap<String, Object>(); //插入數據 entity.put("sname", "test3"); studentService.insert(entity); //返回index就會跳到index.ftl return "index"; } |
4.根據需要可以在resources的application.properties配置文件,修改freemarker視圖的默認屬性。
|
例如:
1.application.properties配置文件增加以下配置
#setting freemarker encoding spring.freemarker.charset=UTF-8 |
7.2.2. 注意事項
注意Freemarker的自動配置的屬性類為:spring-boot-autoconfigure-1.5.4.RELEASE.jar包的
org.springframework.boot.autoconfigure.freemarker.FreeMarkerProperties類。
freemarker視圖的默認屬性配置在里面
如下:
package org.springframework.boot.autoconfigure.freemarker;
import java.util.HashMap; import java.util.Map;
import org.springframework.boot.autoconfigure.template.AbstractTemplateViewResolverProperties; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "spring.freemarker") public class FreeMarkerProperties extends AbstractTemplateViewResolverProperties { //默認的視圖的存放路徑 public static final String DEFAULT_TEMPLATE_LOADER_PATH = "classpath:/templates/"; //默認的前綴 public static final String DEFAULT_PREFIX = ""; //默認的后綴 public static final String DEFAULT_SUFFIX = ".ftl"; private Map<String, String> settings = new HashMap<String, String>(); private String[] templateLoaderPath = new String[] { DEFAULT_TEMPLATE_LOADER_PATH }; private boolean preferFileSystemAccess = true;
public FreeMarkerProperties() { super(DEFAULT_PREFIX, DEFAULT_SUFFIX); }
public Map<String, String> getSettings() { return this.settings; }
public void setSettings(Map<String, String> settings) { this.settings = settings; }
public String[] getTemplateLoaderPath() { return this.templateLoaderPath; }
public boolean isPreferFileSystemAccess() { return this.preferFileSystemAccess; }
public void setPreferFileSystemAccess(boolean preferFileSystemAccess) { this.preferFileSystemAccess = preferFileSystemAccess; }
public void setTemplateLoaderPath(String... templateLoaderPaths) { this.templateLoaderPath = templateLoaderPaths; }
}
|
2.查看Spring Boot內置的FreeMarkerProperties類的屬性,發現application.properties里面可以設置的屬性竟然比FreeMarkerProperties定義的屬性多,為什么呢?
答:因為Spring Boot直接引用了FreeMarker框架原來內部定義的屬性,只是在前面加一個前綴。
所以導致有一些沒有默認值的屬性不在FreeMarkerProperties類里面。
7.3. Thymeleaf模板引擎的配置
7.3.1. 配置流程
1.導入Thymeleaf的支持包
<!-- thymeleaf支持包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> |
2.Spring Boot的Thymeleaf模板引擎的默認路徑是resources/templates,所以在resources下創建一個templates文件夾。將視圖頁面放在里面
|
內容為:
<!DOCTYPE HTML> <!-- 注意Thymeleaf模板引擎一定要引入xmlns:th="http://www.thymeleaf.org"命名空間 --> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>hello</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <!-- ${name}用於獲得Controller返回的Request的取值范圍的值,${}一定要在th:開頭的標簽里才有效 --> <p th:text="'Hello!, ' + ${name} + '!'" >3333</p> </body> </html> |
3.這樣Spring Boot直接就支持了返回Thymeleaf的html視圖了。
@RequestMapping(value="/index") public String index(Model model){ System.out.println("-測試數據-"); model.addAttribute("name", "張三"); return "index"; }
|
4.根據需要可以在resources的application.properties配置文件,增加Thymeleaf視圖的默認屬性。
spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html #開發時關閉緩存,不然沒法看到實時頁面 spring.thymeleaf.cache=false |
7.3.2. 注意事項
具體的application-thymeleaf.properties配置文件能夠配置的屬性,根據自身實際的情況,可以查看spring-boot-autoconfigure-1.5.4.RELEASE.jar設置。
Thymeleaf的屬性類為:org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties
|
7.4. JSP視圖配置(極不推薦)
Spring Boot在默認自動配置已經不支持JSP視圖。如果非要使用JSP視圖。需要我們手工配置。
7.4.1. 配置流程
7.4.2. 注意事項
1.因為JSP是JavaWEB技術,依賴Servlet-API。所以如果使用jsp視圖發布包格式為war包
2.也是因為JSP是依賴Servlet-API的,所以一定要實現一個SpringBootServletInitializer類的子類作為項目的入口,功能類似於web項目的web.xml
不管使用任何的模板引擎代替JSP。其實就可以認為它是類似於JSP的動態頁面技術。
就是將原來JSP實現的功能,換一種方式來編寫。。。
7.5. 默認讀取的靜態資源路徑
Spring Boot默認讀取CSS、JavaScript、html、圖片等靜態資源的根目錄為:
classpath:/META-INF/resources/
classpath:/resources
classpath:/static/
classpath:/public/
也就是說html使用到的CSS、image等靜態資源可以放到以上目錄文件夾
例如:
|
注意:具體查看org.springframework.boot.autoconfigure.web.ResourceProperties類的配置,如果要修改,在appplication.properties修改默認的路徑。
|
8. SpringBoot整合
8.1. 使用的數據庫SQL
框架整合統一使用一下SQL。
-- 導出 表 school.student 結構 DROP TABLE IF EXISTS `student`; CREATE TABLE IF NOT EXISTS `student` ( `SID` int(11) NOT NULL AUTO_INCREMENT COMMENT '編號', `SNAME` varchar(50) DEFAULT NULL COMMENT '姓名', `SEX` char(3) DEFAULT NULL COMMENT '性別', `BIRTHDAY` date DEFAULT NULL COMMENT '生日', `AGE` int(11) DEFAULT NULL COMMENT '年齡', PRIMARY KEY (`SID`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='學生表';
-- 正在導出表 school.student 的數據:~5 rows (大約) DELETE FROM `student`; /*!40000 ALTER TABLE `student` DISABLE KEYS */; INSERT INTO `student` (`SID`, `SNAME`, `SEX`, `BIRTHDAY`, `AGE`) VALUES (1, '張三', '男', '1990-03-05', 27), (2, '李四', '男', '1993-10-13', 24), (3, '王五', '女', '1998-02-01', 19), (4, '趙六', '男', '2000-04-02', 17), (5, '陳七', '女', '1985-01-16', 32);
|
8.2. SpringBoot整合Mybatis
8.2.1. 整合說明
Spring Boot默認沒有對mybatis支持,而是Mybatis對springboot進行了支持。所以Spring Boot整合Mybatis的整合包要去Mybatis的的官方尋找。
路徑為:https://github.com/mybatis/spring-boot-starter
Maven路徑在:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
8.2.2. 配置流程
1.創建一個Maven項目
|
2.在pom.xml導入需要的依賴包
<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>cn.gzsxt</groupId> <artifactId>spring-boot-demo-01</artifactId> <version>1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.4.RELEASE</version> </parent> <dependencies> <!-- freemarker支持包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <!--mybatis支持包 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> <!-- 數據庫驅動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- dbcp2連接池 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> </dependency> <!-- Springboot測試包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies> </project> |
3.創建包結果,並且創建三個類
|
4.編寫Application.Java類的內容
package cn.gzsxt;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages="cn.gzsxt") public class Application {
public static void main(String[] args) { SpringApplication.run(Application.class, args); }
}
|
5.編寫配置文件application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/school spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.username=root spring.datasource.password=123456 #dbcp2 datasource spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource
|
6.測試數據源
package cn.gzsxt.test;
import java.sql.SQLException;
import javax.sql.DataSource;
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.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class DataSourceTest {
@Autowired private DataSource dataSource;
@Test public void dataSource() { try { System.out.println(dataSource.getConnection()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
}
|
7.測試數據源正確后,編寫StudentMapper.Java接口
package cn.gzsxt.mapper; import java.util.Map; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper;
//注意,使用的Mapper而不是@Repository @Mapper public interface StudentMapper {
@Insert(value="INSERT INTO student (SNAME, SEX, BIRTHDAY, AGE) VALUES (#{sname}, #{sex},#{birthday}, #{age})") public int insert(Map<String,Object> entity);
}
|
8.編寫一個Service類
package cn.gzsxt.service; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.gzsxt.mapper.StudentMapper;
@Service public class StudentService {
@Autowired private StudentMapper studentMapper; public int insert(Map<String,Object> entity){ return studentMapper.insert(entity); } }
|
9.編寫一個Controller類
package cn.gzsxt.controller;
import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import cn.gzsxt.service.StudentService;
@Controller public class StudentController { @Autowired private StudentService studentService; @RequestMapping(value="/index") public String index(Model model,HttpSession session){ System.out.println("-測試插入數據-"); Map<String, Object> entity=new HashMap<String, Object>(); //插入數據 entity.put("sname", "test3"); studentService.insert(entity); return "index"; } } |
10.啟動程序測試
|
啟動成功:提示使用8080端口訪問。
|
11.在瀏覽器執行訪問
|
12.查看數據庫結果,成功!
|
8.3. Spring Boot整合Spring-Data-JPA
8.3.1. 配置步驟
1.創建一個maven項目
|
2.復制依賴的包到pom.xml文件
<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>cn.gzsxt</groupId> <artifactId>spring-boot-demo-05-data-jpa</artifactId> <version>1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.4.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 增加springboot 整合data-jpa的包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- 數據庫驅動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- dbcp2連接池 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> </dependency> <!-- SpringBoot測試包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies> </project> |
3.創建一個入口類,用於啟動SpringBoot
package cn.gzsxt;
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); }
}
|
4.編寫application.properties.注意文件名不要寫錯,配置數據源
#配置數據源 spring.datasource.url=jdbc:mysql://localhost:3306/school spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.username=root spring.datasource.password=123456 spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource #spring-data-jpa配置 #顯示SQL語句 spring.jpa.show-sql=true #表示是否需要根據view的生命周期來決定session是否關閉 spring.jpa.open-in-view=true |
5.編寫一個測試類測試數據源是否連接數據庫成功
package cn.gzsxt.test; import java.sql.SQLException;
import javax.sql.DataSource;
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.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class DataSourceTest { @Autowired private DataSource dataSource;
@Test public void dataSource(){ try { System.out.println(dataSource.getConnection()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
}
|
如果出現以下信息表示測試成功
|
6.創建一個實體類
package cn.gzsxt.pojo;
import java.io.Serializable; import java.util.Date;
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table;
@Entity @Table(name="student") public class Student implements Serializable{
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long sid;//BIGINT(20) NOT NULL AUTO_INCREMENT, private String sname;//VARCHAR(255) NULL DEFAULT NULL, private String sex;//VARCHAR(255) NULL DEFAULT NULL, private Integer age;//INT(11) NULL DEFAULT NULL, private Date birthday;//DATETIME(6) NULL DEFAULT NULL, public Long getSid() { return sid; } public void setSid(Long sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; }
}
|
7.創建一個操接口
package cn.gzsxt.repository;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository;
import cn.gzsxt.pojo.Student;
@Repository public interface StudentRepository extends JpaRepository<Student, Long> {
}
|
8.創建一個Service
package cn.gzsxt.service;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
import cn.gzsxt.pojo.Student; import cn.gzsxt.repository.StudentRepository;
@Service public class StudentService {
@Autowired private StudentRepository studentRepository;
@Transactional public void save(Student entity){ studentRepository.save(entity); } }
|
9.創建一個Controller
package cn.gzsxt.controller;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
import cn.gzsxt.pojo.Student; import cn.gzsxt.service.StudentService;
@RestController public class StudentController {
@Autowired private StudentService studentService;
@RequestMapping(value="/") public String save(){ Student entity=new Student(); entity.setSname("jpa用戶"); studentService.save(entity); return entity.getSid().toString(); }
}
|
10.啟動項目
|
啟動成功信息,提示使用8080端口訪問
|
成功信息
后台輸出的語句
|
8.3.2. 注意事項
1.Spring-data-jpa只要Maven導入spring-boot-starter-data-jpa模塊已經自動整合了。只要配置好Spring數據源就可以直接使用。如果需要連接池,可以再加一個連接池
<!-- 增加springboot 整合data-jpa的包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- 數據庫驅動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> |
2.查看spring-boot-autoconfigure-1.5.4.RELEASE.jar可以獲得整合的信息。
|
(1).可以配置的參數查看org.springframework.boot.autoconfigure.orm.jpa.JpaProperties類
(2).需要了解整合的代碼查看
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
9. 打包部署
SpringBoot支持使用Jar內嵌Web服務器(Tomcat)的方式發布,也支持生成war包放在外置的web服務器運行。
9.1. 使用jar發布應用
9.1.1. 配置步驟
1.pom.xml要顯示加入插件org.springframework.boot,否則無法產生jar清單文件,導致打出來的jar無法使用命令運行。
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <!-- 排除重新打包 --> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions>
</plugin> </plugins> </build> |
2.使用里面package打包
|
3.打包成功,產生spring-boot-demo-01-1.0.jar文件
|
4.將spring-boot-demo-01-1.0.jar復制到一個文件夾下,在同一級目錄編寫一個bat文件。
|
內容格式:#java -jar <jar名>,如下:
java -jar spring-boot-demo-01-1.0.jar |
5.雙擊bat文件startup.bat
|
9.1.2. 修改內嵌Tomcat的參數
在application.properties設置相關參數即可,如:
#設置Tomcat端口 server.port=80 #設置Tomcat路徑編碼 server.tomcat.uri-encoding=UTF-8 #設置超時時間 server.connection-timeout=1000 |
9.2. 使用war發布應用
9.2.1. 配置流程
1.修改pom.xml文件去掉嵌入式的Tomcat服務器,以及增加serlvet-api依賴包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- 移除嵌入式tomcat服務器 --> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency>
<!-- 加入servlet-api的支持 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> |
2.修改pom.xml文件的打包方式為war
|
3.增加一個web程序的WEB入口類要和Application同一級目錄
package cn.gzsxt;
import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; /** * 如果項目需要使用war發布,需要創建這個類,作為web程序的入口 * @author ranger * */ public class ServletInitializer extends SpringBootServletInitializer {
@Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { //表示獲得web的請求時,調用Application類的實現 return builder.sources(Application.class); } } |
4.打包生成war文件
|
5.復制spring-boot-demo-01-1.0.war放在Tomcat的webapps下
|
6.啟動Tomcat,Tomcat控制台提示SpringBoot信息
|
7.瀏覽器訪問,成功
http://localhost:8080/spring-boot-demo-01-1.0/index
|
9.2.2. 注意事項
9.2.2.1. 第1點
web網站入口類一定要繼承SpringBootServletInitializer類,而且必須要給SpringBoot入口類Application同一級目錄。
9.2.2.2. 第2點
<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>cn.gzsxt.platform</groupId> <artifactId>basic_platform_spring_boot</artifactId> <version>1.0</version> <packaging>war</packaging>
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.13.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent>
<!-- 設置自定義屬性 --> <properties>
<project.build.sourceEncoding>GBK</project.build.sourceEncoding> <project.reporting.outputEncoding>GBK</project.reporting.outputEncoding>
<java.version>1.8</java.version> <servlet.version>3.0.1</servlet.version> <jsp.version>2.2.1</jsp.version> </properties>
<!-- 依賴 --> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <!-- 排除掉內置的tomcat使用我們外置tomcat --> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- 移除嵌入式tomcat服務器 --> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> </dependency> <!-- jsp --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.2.1</version> </dependency>
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> </dependency>
<!-- jstl -->
<dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId>
</dependency>
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version>
</dependency>
</dependencies>
<!-- 構建項目使用Tomcat7插件 --> <build>
<plugins>
<!-- 配置isntall安裝時,不要執行JUnit測試代碼 -->
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId>
<configuration> <!-- 跳過打包安裝時自動執行Junit的測試代碼 --> <skipTests>true</skipTests> </configuration> </plugin> <!-- 配置編譯的時候使用1.8 的JDK -->
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId>
<configuration> <!-- 源碼檢查時使用1.8的JDK --> <source>1.8</source> <!-- 源碼打包成目標程序時,使用1.8JDK --> <target>1.8</target> </configuration> </plugin>
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId>
<configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build>
</project> |
9.2.2.3. 第3點:將映射接口使用@Mapper
@Mapper public interface ModularMapper
|
9.2.2.4. 第4點,關閉thymeleaf模板引擎
注意,關閉thymeleaf模板引擎
#忽略默認的模板引擎 spring.thymeleaf.cache=false spring.thymeleaf.enabled=false |
9.2.2.5. 第5點,啟動的是WebApplicationInitializer類
所以直接啟動頁面就可以
package cn.gzsxt.platform;
import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer;
public class WebApplicationInitializer extends SpringBootServletInitializer {
@Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class); }
}
|
10. 總結
SpringBoot是什么
答:是一個Spring團隊開發的微服務框架。 You just run
SpringBoot的作用是什么
- 一鍵打包,直接運行。。它可以實現使用jar發布我們的項目!!
- 將主流的框架全部先寫好配置的代碼,只有我們配置簡單的幾個必要的參數就可以整合成功。
SpringBoot為什么可以通過jar運行!!
因為SpringBoot在打包的時候,已經將web服務器(tomcat)內嵌在jar程序里面了。
SpringBoot可以使用war發布嗎?
答:jar發布只是默認的打包方式,SpringBoot同時也支持war打包。
注意:war打包的三個必須條件
- 必須要移除默認內嵌的tomcat模塊
- 必須要加入servlet-api的支持
- 必須要war一個網站的入口,通過繼承SpringBootServletInitializer 來說實現 (web.xml)
SpringBoot使用jar發布,是如何啟動項目的呢?
- 必須要啟動默認自動配置 @EnableAutoConfiguraiton
- 在main方法使用SpringApplication類的靜態方法run方法啟動
@EnableAutoConfiguration public class SampleController {
public static void main(String[] args) throws Exception { //啟動Spring Boot程序 SpringApplication.run(SampleController.class, args); } } |
以上使用@EnableAutoConfiguration配置啟動的問題是什么
答:就是如果使用@EnableAutoConfiguration啟動的問題是,每個組件類都要配置一次。很麻煩!!
如何解決@EnableAutoConfiguration的麻煩呢?
SpringBoot引用了一個@SpringBootApplication來解決。
@SpringBootApplication處理了哪些操作?
- @EnableAutoConfiguration (默認加載XxxxxAutoConfiuration的)
- @SpringConfiguration ==@Configuration (將當前類聲明為一個配置類)
- @ComponentScan 掃描了當前類所在的包以及子包的所有組件類。
通過這個注解,我們只有配置一次就可以,加載所以自動配置的內置配置類,而且掃描了所有的組件類對象放在容器!!!
技巧,如果找陌生代碼的Spring入口,直接搜索@SpringBootApplication
Spring主要使用的常見類與注解有哪些
1.@EnableAutoConfiguration 實現將各個模塊的自動配置類加載,執行。
2.@SpringBootApplication 用於標記是一個SpringBoot入口
3.@AutoConfigureBefore 用於在沒加載內置的模塊之前加入自定義的配置類
4.@AutoConfigureAfter 用於在加載完所有的自動配置類之后加入自定義的配置類
--Spring要求我們要對Spring以及SpringMVC的純注解配置,要理解。
要學習SpringBoot框架。我們如何理解它的加載流程呢?
答:
第一步:SpringBoot提供了很多jar包。我們只有抓住這個格式(xxxxx-autoconfigure-*.jar)的jar就可以了。因為所以的自動加載模塊,不管是內置,或者第三方的都是這個命名。
|
第二步:我們需要找到這包里面對應的模塊的兩個類。就可以找到對應的配置信息。
XxxxxAutoConfiuration
XxxxxProperties
|
注意,SpringBoot 1.5.10以后命名規范是
如:方法名setDriverClassName --> properties文件屬性名 driver-class-name
當然,屬性名使用driverClassName也沒有錯 (不建議使用了)
|
SpringBoot支持的哪些視圖?
答:
- thymeleaf (推薦使用)
- freemaker
- jsp (默認內置步支持,可以通過配置支持,不建議使用)
Spring的打包安裝
- jar打包
- war打包