SpringBoot學習筆記
一、概述
1.1 Spring優缺點分析
Spring優點
Spring是Javaee的輕量級代替品,無需開發重量級的Enterprise JavaBean(EJB)對象,Spring為企業級Java開發提供了一種相對簡單的方法,通過依賴注入和面向切面編程,用簡單的Java對象(POJO)實現了EJB的功能。
Spring的缺點
雖然Spring是輕量級的,但是Spring的配置卻是重量級的,一開始,SPring用xml配置,Spring2.5引入了基於注解的組件掃描,這消除了大量針對應用程序自身組件的顯式xml配置,Spring3.0引入了基於Java的配置,這是一種類型安全的可重構配置方式,可以代替xml。所有這些配置代表了開發時的損耗。
除此之外,項目的依賴管理也十分耗時耗力,在環境搭建時,需要分析導入那些庫的坐標,而且還需要分析導入與所有依賴關系其他哭的坐標,一旦選錯了依賴的版本,不兼容問題也十分嚴重。
1.2 SpringBoot的概述
SpringBoot解決Spring的缺點
springboot對上述缺點進行改善和優化,基於約定優於配置的思想,可以讓開發人員不必在配置與邏輯業務之間進行思維的切換,大大提高了開發的效率,一定程度縮短了項目周期。
SpringBoot的特點
- 為基於Spring開發提供更快的入門體驗
- 開箱即用,無需xml配置,可以通過默認值開滿足特定的需求。
- 提供了一些大型項目中常見的非功能性的特性,如嵌入式服務器、安全、指標、健康檢測、外部配置等。
- SpringBoot不是對Spring功能上的增強,而是提供了一種快速使用Spring的方式
SpringBoot的核心功能
-
起步依賴
起步依賴本質上是一個Maven項目對象模型(POM),定義了對其他庫的傳遞依賴,這些東西加在一起及支持某項功能。
-
自動配置
springboot的自動配置是一個運行時(應用程序啟動時)的過程
1.3 SpringBoot快速入門
-
創建maven工程
普通java工程即可
-
添加SpringBoot的起步依賴
springboot要求項目要繼承springboor的起步以來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的controller,所以項目要導入web的啟動依賴
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
-
編寫SpringBoot的引導類
通過springboot提供的引導類起步SpringBoot才可以進行訪問
package com.yhr.testspringboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MySpringBootApp { public static void main(String[] args) { SpringApplication.run(MySpringBootApp.class); } }
-
編寫controller
在引導類MySpringBootApp同級包或者子級包中創建QuickStartController
package com.yhr.testspringboot.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 訪問成功"; } }
-
測試
啟動SpringBoot起步類的主方法,控制台日志打印如下,tomcat已經啟動,打開瀏覽器訪問
localhost:8080/quick
2020-11-26 10:10:50.903 INFO 4060 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-11-26 10:10:50.919 INFO 4060 --- [ main] com.yhr.testspringboot.MySpringBootApp : Started MySpringBootApp in 3.077 seconds (JVM running for 3.587)顯示springboot訪問成功
1.4 SpringBoot快速入門解析
SpringBoot代碼解析
- @SpringBootApplication:標注SpringBoot的啟動類,具備多種功能
- SpringApplication.run(MySpringBootApp.class)代表運行SpringBoot的啟動類,參數為SpringBoot啟動類的字節碼對象
SpringBoot工程熱部署
在開發中反復修改類、頁面等資源,每次修改需要重新啟動才生效,這樣每次都需要重新啟動很麻煩,浪費大量部署的時間,在pom.xml中添加如下配置可以實現在修改代碼后不重啟就能生效,我們稱之為熱部署。
<!--熱部署配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
IDEA進行SpringBoot熱部署失敗的原因:
根本原因是因為IDEA默認情況下不會自動編譯,需要對IDEA進行自動編譯的設置。
- 點擊Settings中Build下的Compiler,在右側選中Make project automatically
- 退出Settings,按下Shift+Ctrl+Alt+/,選中Registry,然后在彈出框中勾選compiler.automake.allow.when.app.running
- 重啟IDEA
使用IDEA快速創建SpringBoot項目
在新建中選擇Spring Initializr而不是maven項目
二、SpringBoot原理分析
2.1 起步依賴原理分析
2.1.1 spring-boot-starter-parent
按住CTRL點擊pom中的spring-boot-starter-parent跳轉到了spring-boot-starter-parent中的pom.xml,部分配置如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath>../../spring-boot-dependencies</relativePath>
</parent>
繼續跳轉到spring-boot-dependencies,部分配置如下:
<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>
</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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test-autoconfigure</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
</dependencies>
</dependencyManagement>
可見一部分坐標的版本、依賴管理、插件管理已經定義好,所以我們的SpringBoot工程繼承spring-boot-starter-parent后已經具備版本鎖定等配置了。所以起步依賴的作用就是進行依賴的傳遞。
2.1.2 spring-boot-starter-web
跳轉spring-boot-starter-web的pom中部分配置如下
<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>
spring-boot-starter-web就是將web開發要使用的spring-web、spring-webmvc等坐標進行了“打包”,這樣我們的工程只要引入spring-boot-starter-web起步依賴的坐標就可以進行web開發了,同樣體現了依賴傳遞的作用。
2.2 自動配置原理分析
查看@SpringBootApplication注解的源碼,源碼如下:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
@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
)
Class<?>[] exclude() default {};
@AliasFor(
annotation = EnableAutoConfiguration.class
)
String[] excludeName() default {};
@AliasFor(
annotation = ComponentScan.class,
attribute = "basePackages"
)
String[] scanBasePackages() default {};
@AliasFor(
annotation = ComponentScan.class,
attribute = "basePackageClasses"
)
Class<?>[] scanBasePackageClasses() default {};
}
其中
@SpringBootConfiguration:等同於@Configuration,既標注該類是一個Spring的配置類
@EnableAutoConfiguration:SpringBoot的自動配置功能開啟
查看@EnableAutoConfiguration的源碼
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
Class<?>[] exclude() default {};
String[] excludeName() default {};
}
其中@Import({AutoConfigurationImportSelector.class})導入了AutoConfigurationImportSelector類,點擊查看AutoConfigurationImportSelector的源碼:部分源碼如下:
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!this.isEnabled(annotationMetadata)) {
return NO_IMPORTS;
} else {
AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
//獲取配置
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
configurations = this.removeDuplicates(configurations);
Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
this.checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = this.filter(configurations, autoConfigurationMetadata);
this.fireAutoConfigurationImportEvents(configurations, exclusions);
return StringUtils.toStringArray(configurations);
}
}
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
return configurations;
}
其中SpringFactoriesLoader.loadFactoryNames方法的作用就是從META-INF/spring.factories文件中讀取指定類對應的類名稱列表。
spring.factories有關源碼:
....
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,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
.....
上面配置文件存在大量的以Configuration為結尾的類名稱,這些類就是存有自動配置信息的類,而SpringApplication在獲取這些類名后再加載。
我們以其中ServletWebServerFactoryAutoConfiguration為例,其部分源碼如下:
@Configuration
@AutoConfigureOrder(-2147483648)
@ConditionalOnClass({ServletRequest.class})
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@EnableConfigurationProperties({ServerProperties.class})
@Import({ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class, EmbeddedTomcat.class, EmbeddedJetty.class, EmbeddedUndertow.class})
public class ServletWebServerFactoryAutoConfiguration {
@EnableConfigurationProperties(ServerProperties.class) 代表加載ServerProperties服務器配置屬性類
ServerProperties源碼:
@ConfigurationProperties(
prefix = "server",
ignoreUnknownFields = true
)
public class ServerProperties {
private Integer port;
private InetAddress address;
@NestedConfigurationProperty
private final ErrorProperties error = new ErrorProperties();
private Boolean useForwardHeaders;
private String serverHeader;
private int maxHttpHeaderSize = 0;
。。。。。。
prefix = "server" 表示SpringBoot配置文件中的前綴,SpringBoot會將配置文件中以server開始的屬性映射到該類
的字段中。
例如在spring-configuration-metadata.json文件中某段以server前綴加上屬性server.port配置了默認值:
{
"sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties",
"defaultValue": 8080,
"name": "server.port",
"description": "Server HTTP port.",
"type": "java.lang.Integer"
},
以上為默認值,且可以覆蓋,如果在yml文件中設置配置即可修改配置。
在spring-boot-starter-parent的pom.xml中如下
<resource>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources</directory>
<includes>
<include>**/application*.yml</include>
<include>**/application*.yaml</include>
<include>**/application*.properties</include>
</includes>
</resource>
以上代表在resources中如果設置了配置文件即可覆蓋默認配置。
三、SpringBoot的配置文件
3.1 SpringBoot配置文件類型
springboot是基於約定的,所以很多配置都有默認值,如果想替換默認配置的話,就可以使用application.properties或者application.yml進行設置。
SpringBoot默認會從resources目錄下加載application.properties或者application.yml文件。
其中properties是以鍵值對的方式,下面詳細介紹yml配置方式
3.1.1 application.yml配置文件
yml是以YMAL(YAML Aint Markup Language)編寫的文件格式,是一種直觀的能被電腦識別的數據序列化格式,且易被閱讀,易與腳本語言交互,yml是以數據為核心的,比xml更簡潔。
3.1.2 yml配置文件的語法
配置普通數據
key: value
name : haha
注意value前有一個空格
配置對象數據
key:
key1: value1
key2: value2
或者
key: {key1: value,key2: value2}
persion:
name: haha
age: 10
addr: beijing
#或者
persion: {name: haha,age: 10,addr: beijing}
注意:在yml語法中相同縮進代表同一個級別
配置map數據
與上相同
配置數組(List、Set)數據
key:
- value
- value
或者key: [value1,value2]
city:
- beijing
- nanjing
- tianjing
#或者
city: [beijing,nanjing,tianjing]
#集合的元素是對象形式
student:
-name: haha
age: 18
score: 80
-name: lala
age: 19
score: 60
注意:value1與之間的- 之間存在一個空格
3.1.3 SpringBoot配置信息的查詢
可以通過修改application.properties或者application.yml來修改springboot的默認配置,例如:
properties
server.port=8081
server.servlet.context-path=demp
yml
server:
port: 8081
servlet:
context-path: /demo
3.2 配置文件與配置類的屬性映射方式
3.2.1 使用注解@Value映射
我們可以通過@Value將配置文件中的值映射到一個Spring管理的Bean上,此時使用的是${}
ps:
@Value("#{}") 表示SpEl表達式通常用來獲取bean的屬性,或者調用bean的某個方法。當然還有可以表示常量
通過@Value("${}") 可以獲取對應屬性文件中定義的屬性值。假如我有一個sys.properties文件 里面規定了一組值: web.view.prefix =/WEB-INF/views/
#properties
persion:
name: haha
age: 18
#yml
persion:
name: haha
age: 18
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 訪問成功 name="+name +"age="+age;
}
}
3.2.2 使用注解@ConfigurationProperties映射
通過注解@ConfigurationProperties(prefix="配置文件中的key的前綴")可以將配置文件中的配置自動與實體進行映射
@Controller
@ConfigurationProperties(prefix="person")
public class QuickStartController {
private String name;
private Integer age;
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
@RequestMapping("/quick")
@ResponseBody
public String quick(){
return "SpringBoot 訪問成功 name="+name +"age="+age;
}
}
使用@ConfigurationProperties方式可以進行配置文件與實體字段的自動映射,但需要字段必須提供set方法才可以,而使用@Value注解修飾的字段不需要提供set方法
四、SpringBoot整合其他技術
4.1 整合Mybatis
mysql8.0以上版本
添加依賴
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--MYSQL驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
配置文件
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/taotaostore?useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=manager
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
數據庫建表並創建實體類
//建表略
public class User{
private Long id;
private String username;
private String password;
private String name;
//get set方法略
}
編寫mapper
接口
@Mapper
public interface UserMapeer {
public List<User> queryUserList();
}
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>
Controller
@Controller
public class QuickStartController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/queryUser")
@ResponseBody
public List<User> queryUser(){
List<User> users = userMapper.queryUserList();
return users;
}
}
測試成功
4.2 整合Junit
添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
測試類
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApp.class)
public class TestMapper {
@Autowired
private UserMapper userMapper;
@Test
public void test(){
List<User> users = userMapper.queryUserList();
System.out.println(users);
}
}
@SpringBootTest的屬性指定的是引導類的字節碼對象
4.3 整合Spring Data JPA
添加依賴
<!--springboot JPA依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--MYSQL驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
配置
#JPA
#DB Configuration 同上
#JPA Configuration
spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
實體類
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User_JPA {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private Integer age;
private String username;
private String password;
private String email;
private String sex;
//get set方法
}
接口
public interface UserRepository extends JpaRepository<User_JPA,Integer>{
public List<User_JPA> findAll();
}
測試
@Test
public void test1(){
List<UserJPA> users = userRepository.findAll();
System.out.println(users);
}
如果是jdk9需要以下坐標
<dependency> <groupId>javax.xml.bind</groupId> <artifactId>javax-api</artifactId> <version>2.3.0</version> </dependency>
4.4 整合Redis
添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置信息
#redis配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
注入RedisTemplate操作測試