一、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í)代替品。無(wú)需開(kāi)發(fā)重量級(jí)的Enterprise JavaBean(EJB)渊迁,Spring為企業(yè)級(jí)Java開(kāi)發(fā)提供了一種相對(duì)簡(jiǎn)單的方法,通過(guò)依賴注入和面向切面編程,用簡(jiǎn)單的Java對(duì)象(Plain Old Java Object座每,POJO)實(shí)現(xiàn)了EJB的功能。
1.1.2 Spring的缺點(diǎn)分析
雖然Spring的組件代碼是輕量級(jí)的摘悴,但它的配置卻是重量級(jí)的峭梳。一開(kāi)始,Spring用XML配置,而且是很多XML配置葱椭。Spring 2.5引入了基于注解的組件掃描捂寿,這消除了大量針對(duì)應(yīng)用程序自身組件的顯式XML配置。Spring 3.0引入了基于Java的配置孵运,這是一種類型安全的可重構(gòu)配置方式秦陋,可以代替XML。
所有這些配置都代表了開(kāi)發(fā)時(shí)的損耗治笨。因?yàn)樵谒伎糞pring特性配置和解決業(yè)務(wù)問(wèn)題之間需要進(jìn)行思維切換驳概,所以編寫(xiě)配置擠占了編寫(xiě)應(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ò)了依賴的版本,隨之而來(lái)的不兼容問(wèn)題就會(huì)嚴(yán)重阻礙項(xiàng)目的開(kāi)發(fā)進(jìn)度绳瘟。
1.2 SpringBoot的概述
1.2.1 SpringBoot解決上述Spring的缺點(diǎn)
SpringBoot對(duì)上述Spring的缺點(diǎn)進(jìn)行的改善和優(yōu)化雕憔,基于約定優(yōu)于配置的思想,可以讓開(kāi)發(fā)人員不必在配置與邏輯業(yè)務(wù)之間進(jìn)行思維的切換糖声,全身心的投入到邏輯業(yè)務(wù)的代碼編寫(xiě)中斤彼,從而大大提高了開(kāi)發(fā)的效率,一定程度上縮短了項(xiàng)目周期蘸泻。
1.2.2 SpringBoot的特點(diǎn)
- 為基于Spring的開(kāi)發(fā)提供更快的入門體驗(yàn)
- 開(kāi)箱即用琉苇,沒(méi)有代碼生成,也無(wú)需XML配置悦施。同時(shí)也可以修改默認(rèn)值來(lái)滿足特定的需求
- 提供了一些大型項(xiàng)目中常見(jiàn)的非功能性特性并扇,如嵌入式服務(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)單的說(shuō),起步依賴就是將具備某種功能的坐標(biāo)打包到一起,并提供一些默認(rèn)的功能鸦做。-
自動(dòng)配置
Spring Boot的自動(dòng)配置是一個(gè)運(yùn)行時(shí)(更準(zhǔn)確地說(shuō)璧疗,是應(yīng)用程序啟動(dòng)時(shí))的過(guò)程,考慮了眾多因素馁龟,才決定Spring配置應(yīng)該用哪個(gè)崩侠,不該用哪個(gè)。該過(guò)程是Spring自動(dòng)完成的坷檩。注意:起步依賴和自動(dòng)配置的原理剖析會(huì)在第三章《SpringBoot原理分析》進(jìn)行詳細(xì)講解
二却音、SpringBoot快速入門
2.1 代碼實(shí)現(xiàn)
2.1.1 創(chuàng)建Maven工程
使用idea工具創(chuàng)建一個(gè)maven工程,該工程為普通的java工程即可
2.1.2 添加SpringBoot的啟動(dòng)器
SpringBoot要求矢炼,項(xiàng)目要繼承SpringBoot的起步依賴spring-boot-starter-parent
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
指定使用的jdk版本
<properties>
<java.version>1.8</java.version>
</properties>
SpringBoot要集成SpringMVC進(jìn)行Controller的開(kāi)發(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 編寫(xiě)SpringBoot引導(dǎo)類
要通過(guò)SpringBoot提供的引導(dǎo)類起步SpringBoot才可以進(jìn)行訪問(wèn)
package com.test;
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 編寫(xiě)Controller
在引導(dǎo)類MySpringBootApplication同級(jí)包或者子級(jí)包中創(chuàng)建QuickStartController
package com.test.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 訪問(wèn)成功!";
}
}
2.1.5 測(cè)試
啟動(dòng)方式一:?jiǎn)?dòng)MySpringBootApplication類中的main方法
啟動(dòng)方式二:使用Maven命令spring-boot:run執(zhí)行即可
控制臺(tái)打印日志如下:
通過(guò)日志發(fā)現(xiàn),Tomcat started on port(s): 8080 (http) with context path ''
tomcat已經(jīng)起步句灌,端口監(jiān)聽(tīng)8080夷陋,web應(yīng)用的虛擬工程名稱為空
打開(kāi)瀏覽器訪問(wèn)url地址為:http://localhost:8080/quick
三、SpringBoot深度體驗(yàn)
3.1 整合Spring Data JPA
3.1.1 添加Spring Data JPA的啟動(dòng)器
<!-- springBoot JPA的起步依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
3.1.2 添加數(shù)據(jù)庫(kù)驅(qū)動(dòng)依賴
<!-- MySQL連接驅(qū)動(dòng) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
3.1.3創(chuàng)建數(shù)據(jù)庫(kù)
創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)胰锌,并在數(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', '李四');
3.1.4 創(chuàng)建配置文件
在maven工程的man/java/resources目錄下創(chuàng)建名為“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
3.1.5 創(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方法... ...
}
3.1.6 編寫(xiě)UserDao
public interface UserDao extends JpaRepository<User, Long> {
}
3.1.7 編寫(xiě)Controller
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/user/{id}")
private User getUserById(@PathVariable long id) {
User user = userService.getUserById(id);
return user;
}
}
3.2 添加頁(yè)面
Springboot中不推薦使用jsp。所以表現(xiàn)層頁(yè)面可以使用模板引擎實(shí)現(xiàn)资昧。Spring Boot支持的模板類型有: velocity酬土、freemarker、Thymeleaf等 其中對(duì)velocity的支持以及設(shè)置成過(guò)期狀態(tài)格带,也就意味中springboot已經(jīng)拋棄的velocity撤缴,所以在springboot中如果要編寫(xiě)頁(yè)面的話應(yīng)該使用freemarker或者Thymeleaf,本教程中使用freemarker叽唱。
3.2.1添加freemarker的依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
3.2.2編寫(xiě)freemarker模板
注意:模板必須放到src/main/resources/templates目錄下屈呕。并且模板擴(kuò)展名必須為ftl。
<html>
<head>
<title>hello springboot</title>
</head>
<body>
用戶列表:<br>
<table border="1">
<tr>
<th>id</th>
<th>username</th>
<th>password</th>
<th>name</th>
</tr>
<#list userList as user>
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.password}</td>
<td>${user.name}</td>
</tr>
</#list>
</table>
</body>
</html>
3.2.3訪問(wèn)靜態(tài)資源
網(wǎng)頁(yè)中可能會(huì)用到棺亭,圖片虎眨、css、js等靜態(tài)資源侦铜。
需要把靜態(tài)資源放到src/main/resources下的static目錄下
訪問(wèn)靜態(tài)資源:
四专甩、SpringBoot原理分析
4.1 起步依賴原理分析
4.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.2.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.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>2.0.2.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.2.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)行依賴的傳遞。
4.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.2.RELEASE</version>
</parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.2.RELEASE</version>
<name>Spring Boot Web Starter</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.0.2.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
<version>2.0.2.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>2.0.2.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開(kāi)發(fā)要使用的spring-web狠怨、spring-webmvc等坐標(biāo)進(jìn)行了“打包”约啊,這樣我們的工程只要引入spring-boot-starter-web起步依賴的坐標(biāo)就可以進(jìn)行web開(kāi)發(fā)了,同樣體現(xiàn)了依賴傳遞的作用佣赖。
4.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)配置功能開(kāi)啟
按住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為例來(lái)分析源碼:
@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開(kāi)始的屬性映射到該類的字段中奥洼。映射關(guān)系如下:
五、SpringBoot的配置文件
5.1 SpringBoot配置文件類型
5.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)文件
其中瓷患,application.properties文件是鍵值對(duì)類型的文件,之前一直在使用遣妥,所以此處不在對(duì)properties文件的格式進(jìn)行闡述擅编。除了properties文件外,SpringBoot還可以使用yml文件進(jìn)行配置箫踩,下面對(duì)yml文件進(jìn)行講解爱态。
5.1.2 application.yml配置文件
5.1.2.1 yml配置文件簡(jiǎn)介
YML文件格式是YAML (YAML Aint Markup Language)編寫(xiě)的文件格式,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磁椒。
5.1.2.2 yml配置文件的語(yǔ)法
5.1.2.2.1 配置普通數(shù)據(jù)
- 語(yǔ)法: key: value
- 示例代碼:
name: haohao
- 注意:value之前有一個(gè)空格
5.1.2.2.2 配置對(duì)象數(shù)據(jù)
- 語(yǔ)法:
key:
key1: value1
key2: value2
或者:
key: {key1: value1,key2: value2} - 示例代碼:
person:
name: haohao
age: 31
addr: beijing
#或者
person: {name: haohao,age: 31,addr: beijing}
- 注意:key1前面的空格個(gè)數(shù)不限定堤瘤,在yml語(yǔ)法中,相同縮進(jìn)代表同一個(gè)級(jí)別
5.1.2.2.2 配置Map數(shù)據(jù)
同上面的對(duì)象寫(xiě)法
5.1.2.2.3 配置數(shù)組(List浆熔、Set)數(shù)據(jù)
-
語(yǔ)法:
? key:
? - value1
? - value2
或者:
? key: [value1,value2]
示例代碼:
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è)空格
5.1.3 SpringBoot配置信息的查詢
上面提及過(guò)本辐,SpringBoot的配置文件,主要的目的就是對(duì)配置信息進(jìn)行修改的医增,但在配置時(shí)的key從哪里去查詢呢慎皱?我們可以查閱SpringBoot的官方文檔
常用的配置摘抄如下:
# 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.
我們可以通過(guò)配置application.poperties 或者 application.yml 來(lái)修改SpringBoot的默認(rèn)配置
例如:
application.properties文件
server.port=8888
server.servlet.context-path=demo
application.yml文件
server:
port: 8888
servlet:
context-path: /demo
5.2 配置文件與配置類的屬性映射方式
5.2.1 使用注解@Value映射
我們可以通過(guò)@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;
@RequestMapping("/quick")
@ResponseBody
public String quick(){
return "springboot 訪問(wèn)成功! name="+name+",age="+age;
}
}
瀏覽器訪問(wèn)地址:http://localhost:8080/quick 結(jié)果如下:
5.2.2 使用注解@ConfigurationProperties映射
通過(guò)注解@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 訪問(wèn)成功! name="+name+",age="+age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
}
瀏覽器訪問(wèn)地址:http://localhost:8080/quick 結(jié)果如下:
注意:使用@ConfigurationProperties方式可以進(jìn)行配置文件與實(shí)體字段的自動(dòng)映射宝冕,但需要字段必須提供set方法才可以,而使用@Value注解修飾的字段不需要提供set方法
六邓萨、SpringBoot整合其他技術(shù)
6.1 SpringBoot整合Mybatis
6.1.1 添加Mybatis的啟動(dòng)器
<!--mybatis起步依賴-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
6.1.2 創(chuàng)建實(shí)體Bean
public class User {
// 主鍵
private Long id;
// 用戶名
private String username;
// 密碼
private String password;
// 姓名
private String name;
//此處省略getter和setter方法 .. ..
}
6.1.3 編寫(xiě)Mapper
@Mapper
public interface UserMapper {
public List<User> queryUserList();
}
注意:@Mapper標(biāo)記該類是一個(gè)mybatis的mapper接口地梨,可以被spring boot自動(dòng)掃描到spring上下文中
6.1.4 配置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.test.mapper.UserMapper">
<select id="queryUserList" resultType="user">
select * from user
</select>
</mapper>
6.1.5 在application.properties中添加mybatis的信息
#spring集成Mybatis環(huán)境
#pojo別名掃描包
mybatis.type-aliases-package=com.test.domain
#加載Mybatis映射文件
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
6.1.6 編寫(xiě)測(cè)試Controller
@Controller
public class MapperController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/queryUser")
@ResponseBody
public List<User> queryUser(){
List<User> users = userMapper.queryUserList();
return users;
}
}
6.1.7 測(cè)試
6.1.8Mapper接口和映射文件在同一目錄下
此種情況下需要在maven的配置文件中添加如下信息:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
并且無(wú)需在application.properties中配置mapper路徑,只需要在引導(dǎo)類上添加@MapperScan注解即可
@SpringBootApplication
@MapperScan("com.test.mapper")
public class Application1 {
public static void main(String[] args) {
SpringApplication.run(Application1.class, args);
}
}
6.2 SpringBoot整合Junit
6.2.1 添加Junit的啟動(dòng)器
<!--測(cè)試的起步依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
6.2.2 編寫(xiě)測(cè)試類
package com.test.test;
import com.test.MySpringBootApplication;
import com.test.domain.User;
import com.test.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ì)象