SpringBoot
簡介
微框架,與 Spring4 一起誕生,基於約定、生來為了簡化 spring 的配置
優點
- 可以快速的上手,整合了一些子項目(開源框架或者第三方開源庫)
- 可以依賴很少的配置快速的搭建項目
- 基於 spring 使開發者快速入門,門檻很低。
- 可以創建獨立運行的應用而不需要依賴容器
- 提供很多 maven 極簡配置,缺點是會引入很多不需要的包
- 提供可視化的相關功能,方便監控
- 簡化配置
使用場景
- 有 Spring 的地方都行
- J2EE/web 項目
- 微服務的基礎
需要的Java版本:1.8+
核心功能
起步依賴
起步依賴實際上就是一個 Maven 項目對象模型,定義了對其他庫的傳遞依賴。這些東西加在一起支持某項功能。從一定程度上規避了依賴沖突問題
自動配置
對於一些約定的屬性,springboot 在 spring-boot-autoconfigure 包下 META-INF/spring-configuration-metadata.json 文件中進行了默認屬性配置。如果我們不通過配置文件覆蓋這個配置,在應用程序啟動時,如果應用程序啟動條件符合注解的要求,就會采用這些默認配置來完成應用的初始化配置。如果我們覆蓋這個配置,就會采用我們定義的配置
原理分析:
@SpringBootConfiguration // 相當於 @Configuration
@EnableAutoConfiguration // 開啟自動配置
@ComponentScan( // 配置注解掃描。掃描該包及其子包的注解
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {}
快速搭建
使用IDEA可以快速的創建 springboot 項目,當然也可以通過創建 Maven 工程並導入依賴來新建 springboot 項目
快速創建的工程只能選擇最新的幾個版本,如果想使用老版本可以在工程搭建完成后手動更改版本號
配置文件
SpringBoot使用一個全局的配置文件,並且名稱是固定的,配置文件有兩種(截圖自來自spring-boot-starter-parent-1.5.9.RELEASE.pom):
由該 pom 文件也可以得出一個結論,當同時存在 .yml 和 .properties 配置文件且配置了相同的參數時,會因為后加載 properties 而導致 yml 里面的相同配置配覆蓋。當然實際開發也幾乎不會有人這么做
application.properties 就是常規的 key=value 格式配置文件,當要配置的參數比較多就會發現他的層次不是那么清晰,不便於閱讀
application.yml
yml(也叫yaml):是一種以數據為中心的配置文件, 比 json,xml 等更適合做配置文件
yml基本語法:
key:(空格)value ---> 鍵和值中間用冒號空格!!!連接,記住是冒號空格,缺一不可
不同層級的關系用空格表示,只要是左對齊的一列數據,都是同一層級的:
server:
port: 8888
字符串
默認不用加引號,
如果加上 “” 雙引號,雙引號內的特殊字符將作為本身的意思展示
如果加上 ‘’ 單引號,單引號內的特殊字符將會被轉義
對象、Map
在下一行來寫對象的屬性和值的關系;注意縮進
user:
name: yaya
age: 18
address: xian
firends: {name: zhangsan, age: 18}
# map里面的 冒號后面也得有 空格
數組 List、Set
用 - 值表示數組中的一個元素
arr:
- 1
- 2
- 3
例:用yml構造一個對象
person: # 前綴名
name: yaya
age: 18
address: 西安
arr:
- 1
- 2
- 3
friend: {name: zs,age: 13}
son:
name: 張三
age: 13
@Component // 配置 Bean 被 Spring 容器管理
@ConfigurationProperties(prefix = "person") // 配置文件和實體進行映射,配置前綴,這里對應 yml 文件中的對象名
public class User {
private String name;
private int age;
private String address;
private List<Integer> arr;
private Map<String, Object> friend;
private Son son; // 引入一個外部類
setter/getter ...
}
public class Son{ // 該類不用加任何注解,框架還是會將 yml 中的屬性映射到該類的屬性上
private String name;
private int age;
}
@Value 獲取值和 @ConfigurationProperties 獲取值的比較:
@ConfigurationProperties | @Value | |
---|---|---|
功能 | 批量注入配置文件中的屬性 | 一個個指定 |
松散綁定(松散語法) | 支持 | 不支持 |
SpEL | 不支持 | 支持 |
JSR303數據校驗 | 支持 | 不支持 |
復雜類型封裝 | 支持 | 不支持 |
Bean對Json映射處理
@JsonIngore
@JsonFormat
public class Person {
private String name;
@JsonIgnore // 轉換時忽略該字段
private Integer age;
// Json格式化
@JsonFormat(pattern = "yyyy年MM月dd日 HH:mm:ss", locale = "zh", timezone = "GMT+8")
private Date birthday;
}
@RequestMapping("/person")
public Person person(){
Person p = new Person();
p.setName("張三");
p.setAge(23);
p.setBirthday(new Date());
System.out.println(p);
return p;
}
這時,返回的JSON數據中就不會出現 age 屬性,並且對 birthday 進行了格式化
{"name":"張三","birthday":"2019年08月07日 15:34:45"}
@JsonInclude
忽略null屬性
如果前端需要將 null 返回為空串/不返回,我們可以使用。
@JsonInclude(content = JsonInclude.Include.NON_NULL) // 如果該屬性為 null,則它不參與序列化
注意:在 spring-boot 1.5.9 版本中, @JsonInclude 注解沒有對 value 和 content 關聯(沒有在 content 上配置 @AliasFor 注解),所以剛剛上面的配置是無效的。采用下面的配置:
@JsonInclude(JsonInclude.Include.NON_NULL)
也可以在 yml 文件中配置全局忽略,配置方法如下:
spring:
jackson:
default-property-inclusion: non_null
Devtools熱部署
- 在pom.xml中添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<!-- 關閉此項的依賴傳遞,即別的項目依賴該項目時,不會傳遞依賴此jar -->
<optional>true</optional>
</dependency>
- 配置IDEA自動編譯
- 按 Ctrl+Shift+Alt+/ , 打開 Registry .配置IDEA運行時自動編譯
一些額外的配置
spring:
freemarker:
cache: true # 關閉thymeleaf的頁面緩存
devtools:
remote:
restart:
enabled: false # 熱部署開關
restart:
additional-paths: springboot-demo/src/main/java # 設置重啟的目錄,對那個目錄的文件進行修改后需要重啟
exclude: static/** # 設置classpath下 static 目錄內容修改后不重啟。一般設置為靜態資源目錄
資源文件屬性配置
配置資源文件屬性讀取
有時我們采用一些自己定義的資源文件(非 application.xxx )想要獲取里面的屬性值時,需要采用以下配置
<!-- 配置文件處理器依賴,配置后可以進行資源配置文件的加載 -->
<!-- 配置這個依賴后,書寫yml文件時自定義的屬性會有提示 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
@Configuration // 也是一個 @Component 語義化注解
@ConfigurationProperties(value = "admin") // 配置文件中共有的前綴名
@PropertySource(value = "classpath:user.properties") // 資源文件的位置
public class Admin implements Serializable {
private String username;
private String password;
}
配置tomcat
server:
port: 8888 # 端口號
session-timeout: 60 # session 超時時間/分鍾,默認是30
context-path: /demo # 全局虛擬路徑
error:
path: /error.html # 錯誤跳轉頁
tomcat:
uri-encoding: utf-8 # 設置tomcat編碼
整合模板引擎
整合FreeMarker
導入FreeMarker啟動器
<!-- freemarker -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
配置 freemarker
spring:
freemarker:
cache: false # 關閉freemarker緩存。即時刷新。上線環境建議修改為 true
template-loader-path: classpath:/template # 模板文件的路徑
charset: UTF-8 # 編碼,默認也是u8
check-template-location: true # 檢查模板路徑
content-type: text/html # 默認也是 text/html
整合 mybatis
添加 mybatis 起步依賴,mysql 數據庫依賴
<!-- mybatis起步依賴 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- mysql數據庫依賴 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
在 yml 文件中配置數據源
spring:
datasource:
username: keats
password: 521
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
# 對於mysql數據庫連接版本 v6+ 這個驅動要修改成 com.mysql.cj.jdbc.Driver。當然也可以什么都不寫用默認的
MyBatis相關配置
mybatis:
mapper-locations: classpath:mapping/*Mapping.xml # 配置 mapper 文件所在的路徑
type-aliases-package: cn.keats.mybatisdemo.pojo # 配置這個包下的所有類起別名
創建實體類
public class User implements Serializable {
private Integer id;
private String username;
private String password;
private Date birthday;
setter/getter ...
}
創建映射關系接口
接口要添加 @Mapper 注解,這樣容器中才會有接口的實現類
@Mapper //
public interface UserMapper {
@Select("select * from user where id = #{id}")
User selectById(Integer id); // 采用注解的方式書寫SQL語句
void insert(User user); // 采用mapper配置文件的方式書寫SQL語句
}
Mapper映射文件,四個要求
namespace 等於 UserMapper 接口的全限定名
id 等於 方法名
parameterType 等於方法的參數類型
resaultType 等於方法的返回值類型
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="cn.keats.mybatisdemo.mapper.UserMapper">
<insert id="insert" parameterType="user">
insert into user values (null , #{username}, #{password}, #{birthday})
</insert>
</mapper>
整合 Redis
導入Redis啟動器
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置host和端口
其實從圖中可以看出,springboot默認對Redis的配置就是 localhost:6379 所以如果Redis也是這個路徑,可以不用自行配置