SpringBoot使用技巧及原理分析與配置方法
1.1 起步依賴原理分析
1.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.1.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.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>2.0.1.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.1.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)行依賴的傳遞。
1.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.1.RELEASE</version>
</parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.1.RELEASE</version>
<name>Spring Boot Web Starter</name>
<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>
</project>從上面的spring-boot-starter-web的pom.xml中我們可以發(fā)現(xiàn),spring-boot-starter-web就是將web開發(fā)要使用的spring-web、spring-webmvc等坐標(biāo)進(jìn)行了“打包”,這樣我們的工程只要引入spring-boot-starter-web起步依賴的坐標(biāo)就可以進(jìn)行web開發(fā)了,同樣體現(xiàn)了依賴傳遞的作用。
1.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)配置功能開啟
按住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開始的屬性映射到該類的字段中。映射關(guān)系如下:

二、SpringBoot的配置文件
2.1 SpringBoot配置文件類型
2.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)行講解。
2.1.2 application.yml配置文件
2.1.2.1 yml配置文件簡(jiǎn)介
YML文件格式是YAML (YAML Aint Markup Language)編寫的文件格式,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。
2.1.2.2 yml配置文件的語(yǔ)法
2.1.2.2.1 配置普通數(shù)據(jù)
語(yǔ)法: key: value
示例代碼:
name: haohao
注意:value之前有一個(gè)空格
2.1.2.2.2 配置對(duì)象數(shù)據(jù)
- 語(yǔ)法:
- ? key:
- ? key1: value1
- ? key2: value2
- ? 或者:
- ? key:
- 示例代碼:
person:
name: haohao
age: 31
addr: beijing
#或者
person: {name: haohao,age: 31,addr: beijing}注意:key1前面的空格個(gè)數(shù)不限定,在yml語(yǔ)法中,相同縮進(jìn)代表同一個(gè)級(jí)別
2.1.2.2.2 配置Map數(shù)據(jù)
同上面的對(duì)象寫法
2.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è)空格
2.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: /demo2.2 配置文件與配置類的屬性映射方式
2.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é)果如下:
2.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

注意:使用@ConfigurationProperties方式可以進(jìn)行配置文件與實(shí)體字段的自動(dòng)映射,但需要字段必須提供set方法才可以,而使用@Value注解修飾的字段不需要提供set方法
到此這篇關(guān)于SpringBoot使用技巧及原理分析與配置方法的文章就介紹到這了,更多相關(guān)SpringBoot使用原理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot @Schedule的使用注意與原理分析
- SpringBoot?LiteFlow引擎框架使用原理解析
- SpringBoot中Redis自動(dòng)配置的介紹、原理和使用詳解
- SpringBoot中熔斷器的原理和使用詳解
- SpringBoot中@MessageMapping注解的原理及使用詳解
- PageHelper在springboot+mybatis框架中的使用步驟及原理解析
- SpringBoot嵌入式Web容器原理與使用介紹
- SpringBoot Admin使用及心跳檢測(cè)原理分析
- SpringBoot異步使用@Async的原理以及線程池配置詳解
- SpringBoot實(shí)戰(zhàn)之高效使用枚舉參數(shù)(原理篇)案例詳解
相關(guān)文章
Spring中@Controller和@RestController的區(qū)別詳解
這篇文章主要介紹了Spring中@Controller和@RestController的區(qū)別詳解,@RestController?是?@Controller?和?@ResponseBody?的結(jié)合體,單獨(dú)使用?@RestController?的效果與?@Controller?和?@ResponseBody?二者同時(shí)使用的效果相同,需要的朋友可以參考下2023-10-10
詳解Java中NullPointerException異常的原因和解決辦法
本文主要介紹了詳解Java中NullPointerException異常的原因和解決辦法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
Java實(shí)現(xiàn)簡(jiǎn)單學(xué)生信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)簡(jiǎn)單學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
深入探索Spring AOP從原理到實(shí)戰(zhàn)操作
本文詳細(xì)介紹了SpringAOP的基本概念、實(shí)現(xiàn)機(jī)制、核心術(shù)語(yǔ)及實(shí)戰(zhàn)應(yīng)用,SpringAOP通過(guò)動(dòng)態(tài)代理機(jī)制,在運(yùn)行時(shí)為目標(biāo)對(duì)象創(chuàng)建代理,實(shí)現(xiàn)對(duì)方法的增強(qiáng),本文探討了SpringAOP的高級(jí)特性,并列舉了日志記錄、事務(wù)管理、權(quán)限控制和性能監(jiān)控等應(yīng)用場(chǎng)景,感興趣的朋友跟隨小編一起看看吧2025-12-12
java中 Set與Map排序輸出到Writer詳解及實(shí)例
這篇文章主要介紹了 java中 Set與Map排序輸出到Writer詳解及實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-03-03

