一、准備工作
- jdk1.8
- apache maven 3.3.9
- ide : eclipse | idea
- spring官網:https://spring.io/
二、創建基礎web項目
1. maven配置
編寫M2_HOME/conf/setting.xml
1. 指定本地maven倉庫
<localRepository>D:\APP\repository</localRepository>
2. 配置遠程倉庫鏡像(以阿里雲為例)
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
3. 配置全局jdk版本
<profile>
<id>jdk-1.8</id>
<activation>
<activeByDefault>true</activeByDefault>
<jdk>1.8</jdk>
</activation>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
</profile>
2.創建maven項目、配置pom.xml為web基礎項目
1. web項目基礎依賴
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
3.編寫啟動類
啟動類需要與service、controller、dao等包同級,便於后面自動掃描
1.啟動類
- @SpringBootApplication
- @SpringBootConfiguration------表示是一個springboot配置類
- @Configuration------表示是一個spring配置類,等價於spring中的配置文件xml
- @Component------容器中的一個組件
- @Configuration------表示是一個spring配置類,等價於spring中的配置文件xml
- @EnableAutoConfiguration------開啟自動配置
- @AutoConfigurationPackage------自動配置包,將主配置類所在包及旗下所有子包里面所有的組件掃描到springboot容器中,所以啟動類需要和service等包同級
- @Import({AutoConfigurationImportSelector.class})------給容器導入一個組件,導入的組件由AutoConfigurationImportSelector.class決定,該類會給容器導入大量的自動配置類(格式類似:xxxAutoConfiguraion),這些自動配置類來源於:spring-boot-configure/META-INF/spring.factories文件中
- @ComponentScan------自動掃包配置
- @SpringBootConfiguration------表示是一個springboot配置類
@SpringBootApplication
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class,args);
}
}
2.接口類
當@ResponseBody加在方法上表示該方法返回的對象之間返回給瀏覽器,如果加載在類上,表示當前類下的所有方法都把返回對象之間返回給瀏覽器
@RestController == @Controller + @ResponseBody
@Controller
public class Helloword {
@RequestMapping("/hello")
@ResponseBody
public String hello() {
return "Hello World";
}
}
4.使用maven打包
1.配置pom.xml文件,默認打成jar包
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
點擊idea左下角的圖標,點擊maven projects => spring-boot-helloword =>
lifecycle => package
5.使用命令java -jar xxx.jar運行
取target文件夾下的spring-boot-helloword-1.0-SNAPSHOT.jar,
運行java -jar spring-boot-helloword-1.0-SNAPSHOT.jar
5.快捷生成
1.使用IDE生成
2.使用spring官網地址:https://start.spring.io
三、springboot配置文件
1.application.properties
- 語法
- lv1.lv2=value
- lv1.lv2.lv3=false
- lists=1,2,3
2.application.yml
- 語法
- key: value (注意冒號和value直接需要空格)
- 用空格縮進來表示處於同一層級
- 值范圍
- 字面值(普通值)直接用 k: v 來寫
- 字符串不用加上單引號或雙引號
- "":雙引號里的特殊字符會表達,例如name: "zhang \n wang" 輸出:zhang 換行 wang
- '':單引號里的特殊字符不會表達,例如name: 'zhang \n wang' 輸出:zhang \n wang
- 對象、map
#1.普通寫法 student: name: song age: 1 #2.行內寫法 student: {name: song,age: 1}
- 數組list、set
#1.普通寫法 pets: - cat - dog - pig #2.行內寫法 pets: {cat,dog,pig}
- 字面值(普通值)直接用 k: v 來寫
3.獲取配置文件內容到javabean
- 需要借助@Component注解
- 使用 @ConfigurationProperties(prefix="beanName") 注解來關聯獲取配置文件內容,其中beanName表示配置文件中屬性的前綴,適用於application.properties、application.yml配置文件的內容獲取
4.@ConfigurationProperties與@Value賦值的異同
- @ConfigurationProperties:支持批量賦值、支持松散綁定(last-name等價於lastName)、不支持表達式計算、支持jsr303數據校驗、支持復雜類型封裝(object、map類型)
- @Value:支持單個賦值、支持表達式計算
5.@PropertySource
- 含義:@ConfigurationProperties加載的是系統默認的全局配置文件(application.properties、application.yml),而@PropertySource可以讀取自定義的配置文件
- 語法:@PropertySource(value = {"classpath:person.properties"}),value可以是數組
6.@ImportResource
我們自己編寫的xxx.xml配置文件,不會被spring和springboot識別,可以使用以下方法把xxx.xml中的bean引入到spring容器中
- 方法一:可以在啟動類(也是配置類)上,比如SpringbootApplication.java啟動類上加@ImportResource(locations = {"calsspath:xxx.xml"})
- 自定義一個配置類,標注上@Configuration,使用@Bean的方法引入組件到spring中
7.配置文件占位符
- 隨機數
\({random.value}、\){random.int} - 占位符獲取之前配置的值,如果沒有可以用的:指定默認值
name=aaa
address=${name}_bbb
8.profile環境配置
- 方式一:多profile文件(application-{profile}.properties)
- application-dev.properties
- application-sit.properties
- application-prd.properties
#application.properties
#激活dev環境的配置
spring.profiles.active=dev
#application-dev.properties
server.port=8081
#application-prd.properties
server.port=8082
- 方式二:yml文檔快指定配置環境方式
#application.yml
#激活dev環境的配置
server
port: 8080
spring
profiles
active: dev
---
server
port: 8081
spring
profiles: dev
---
server
port: 8082
spring
profiles: prd
- 方式三:命令行方式
1.虛擬機指定
VM options: -Dspring.profiles.active=dev
2.java命令指定
java -jar xxx.jar --spring.profiles.active=dev
9.配置文件加載位置
- sprigboot啟動會掃描以下位置的application.properties和application.yml來作為springboot的默認配置文件
- 優先級(./config/ > ./),所以配置文件都會被加載
- 對應重復的配置屬性:高優先級會覆蓋低優先級的文件配置屬性
- 對於不重復的配置屬性:多文件的多屬性會互補加載(都加載到springboot中)
- 我們也可以通過配置spring.config.location來改變默認配置,僅是指定的文件優先級為最高,但是所有的配置文件還是會被一起加載到springboot,參考上面
file類型
./config/
./
classpath類型
./config/
./
10.配置文件加載順序
優先級由高到低:
- 命令行
- 例如:java -jar xxx.jar --server.port=8085 --server.context-path=/abc
- jar包外,帶profile的
- application-dev.properties
- application-dev.yml
- jar包內,帶profile的
- application-dev.properties
- application-dev.yml
- jar包外,不帶profile的
- application.properties
- application.yml
- jar包內,不帶profile的
- application-dev.properties
- application-dev.yml
11.配置文件的屬性來源
用好springboot配置文件的精髓
0. 尋找配置文件和class之間關聯
- 啟動類注解@SpringBootApplication
- 1的依賴注解@EnableAutoConfiguration
- 2的依賴導入@Import({AutoConfigurationImportSelector.class}),導入自動配置選擇器類
- AutoConfigurationImportSelector.selectImports
- AutoConfigurationImportSelector.getAutoConfigurationEntry
- AutoConfigurationImportSelector.getCandidateConfigurations()
- 6方法內的SpringFactoriesLoader.loadFactoryNames()
- SpringFactoriesLoader.loadFactoryNames()
- SpringFactoriesLoader.loadSpringFactories()
- classLoader.getResources("META-INF/spring.factories")
- 找到maven依賴中的spring-boot-autoconfigure2.1.7.RELEASE.jar中META-INF/spring.factories
在spring.factories中以 org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,/ 為例:
0. WebMvcAutoConfiguration.class
@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {
...
}
- 進入DispatcherServletAutoConfiguration.class
@AutoConfigureOrder(-2147483648)
@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({DispatcherServlet.class})
@AutoConfigureAfter({ServletWebServerFactoryAutoConfiguration.class})
public class DispatcherServletAutoConfiguration {
...
}
- 進入ServletWebServerFactoryAutoConfiguration.class
@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 {
...
}
- 進入和ServletWebServerFactoryAutoConfiguration綁定的ServerProperties.class中
@ConfigurationProperties(
prefix = "server",
ignoreUnknownFields = true
)
public class ServerProperties {
private Integer port;
private InetAddress address;
public Integer getPort() {
return this.port;
}
public void setPort(Integer port) {
this.port = port;
}
public InetAddress getAddress() {
return this.address;
}
public void setAddress(InetAddress address) {
this.address = address;
}
//...
}
-
控制台判斷哪些自動配置類生效
application.properties中配置:debug=true -
總結:通過ServerProperties.class中的屬性可以設置application.properties中的一些關於服務器的配置文件屬性,例如:server.port,同樣根據其他的xxx.properties也可以學習配置springboot的配置文件