參考資料
Spring Boot簡介
Spring Boot使創建基於Spring的應用程序變得輕松,只需要做到“just run”就能創建一個獨立的、產品級別的Spring應用程序。官方為Spring平台及第三方庫提供了相對固定的搭配,所以開始的時候會輕松很多。大部分的SpringBoot應用程序都只需要很少的Spring配置。
可以使用SpringBoot創建應用程序,通過java -jar命令或者傳統的war包部署方式來啟動它。也提供了一個命令行工具來運行“spring腳本”。
SpringBoot的目標是:
- 從根本上提供更加快速和簡便的Spring開發體驗。
- 開箱即用,但定制開發也很便捷。
- 提供一些大型項目常用的非功能性特性(例如:嵌入式服務、安全、監控、健康檢查、外部配置)。
- 不用生成代碼,沒有xml配置。
使用Maven進行配置
Spring Boot依賴的groupId是org.springframework.boot。通常情況下,MavenPOM文件繼承自spring-boot-starter-parent項目,並且聲明一些“Starters”。Spring Boot也提供了一些創建可執行jar文件的Maven插件。
繼承spring-boot-starter-parent項目是不錯的使用Spring Boot的方式,但是有時候可能還是有不適配的問題。有些時候您可能需要繼承子不同的父POM,或者僅僅是和我們的默認配置有所區別。查看Section 13.2.2, “Using Spring Boot without the parent POM”,這是使用了導入方式的一種解決方案。
經典的pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<dependencies>
<!--web應用基本環境配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
java代碼
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
@SpringBootApplication
public class MainApplicion {
public static void main(String[] args) throws Exception {
SpringApplication.run(MainApplicion.class, "--server.port=8081");
}
}
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
@Controller
public class SampleController {
@ResponseBody
@RequestMapping(value = "/")
String home() {
return "Hello World!";
}
}
運行
直接執行main方法。
或者生成可執行的jar包,如果要生成可執行的jar包,需要把spring-boot-maven-plugin添加到pom.xml
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
打包mvn package,運行java -jar target/myproject-0.0.1-SNAPSHOT.jar
打開瀏覽器http://localhost:8081/,即可看到Hello World!
附:不使用parent POM的配置方式
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
使用Spring Boot CLI
介紹
Spring Boot CLI是一個命令行工具,如果想要快速獲取一個Spring樣品程序,可以使用到它。Spring Boot CLI是一個命令行工具,如果想要快速獲取一個Spring樣品程序,可以使用到它。有了它,您可以運行Groovy腳本,這意味着您可以使用熟練的類Java語法,而不是超多的樣板代碼。
使用CLI這個命令行工具來做Spring Boot開發並不是必須的,但它確實是一個開發Spring應用程序最快捷的方式。
下載地址
http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/
使用
windows的話,下載解壓即可。
快速開始Spring CLI實例
新建一個文件,文件名是app.groovy:
@RestController
class ThisWillActuallyRun {
@RequestMapping("/")
String home() {
"Hello World!"
}
}
運行
spring run app.groovy
打開瀏覽器http://localhost:8080,即可看到Hello World!
使用 @SpringBootApplication注解
許多使用Spring Boot的開發者總是有帶有@Configuration, @EnableAutoConfiguration 和 @ComponentScan 注解的主類。由於這些注解很頻繁地被用在一起,基於最佳實踐,Spring Boot提供了一個方便的注解@SpringBootApplication 來替代。
@SpringBootApplication 等價於使用@Configuration, @EnableAutoConfiguration 和 @ComponentScan默認屬性的情況。
Starters
Starters是Spring boot提供的便利,可以一站式的對依賴進入引入,命名格式為“spring-boot-starter-*”,如“spring-boot-starter-test”則集成了JUnit跟Mockito,用於跑測試用例。
開發工具
Spring Boot 包含一系列工具,可以使應用開發的過程更方便一點。spring-boot-devtools模塊可以包含進任何工程,用來提供額外的程序調試特性。為了添加工具支持,簡單的添加模塊依賴到你的構建系統中:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
當classpath中的文件修改時,使用spring-boot-devtools的應用會自動重啟。當使用IDE開發時,這是一個很有用的功能,因為代碼改變時它能快速的進行反饋。默認情況下,會監控classpath指向的文件夾中任何條目的變化。注意某些資源例如靜態資源和視圖模板不需要重啟應用。作為DevTools監視器classpath中的資源,觸發重啟的唯一方式是更新classpath。
Spring Boot 提供的restart技術是通過兩個類加載器進行工作的。加載進基類加載器的類不能改變(例如,那些第三方jar包)。那些你正在開發的類加載進重啟類加載器中。當應用重啟時,丟棄舊的重啟類加載器並創建一個新的。這種方法意味着應用重啟是比“cold starts” 更快,因為基類加載器已經存在並可用。
某些資源當它們改變時不一定需要觸發重啟。默認不觸發重啟的有/META-INF/maven, /META-INF/resources ,/resources ,/static ,/public or /templates。修改默認行為,可修改配置spring.devtools.restart.exclude=static/**,public/**;如果是在默認的基礎上進行添加不觸發行為,可使用spring.devtools.restart.additional-exclude
啟動失敗
如果你的應用啟動失敗,注冊FailureAnalyzers有可能會提供專門的錯誤信息和解決這個問題的具體行動。例如,如果你啟動一個8080端口的web應用並且這個端口已經被占用,你應該會看到類似於下面的內容:
***************************
APPLICATION FAILED TO START
***************************
Description:
Embedded servlet container failed to start. Port 8080 was already in use.
Action:
Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.
如果沒有任何失敗分析器的話,可以開啟debug(默認的
日志級別是INFO),屬性名為“org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer”,如果是通過java -jar運行的,還可以使用--debug進行開啟,如java -jar myproject-0.0.1-SNAPSHOT.jar --debug
自定義Banner
默認情況下,Spring Boot的打印內容如下
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.2.RELEASE)
如果要修改,可在classpath下創建一個文件,名稱為“banner.txt”,編寫自己要的內容即可。
關閉banner
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MySpringConfiguration.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
應用事件與監聽器
在ApplicationContext創建之前實際上會觸發一些事件,因此你不能使用@Bean來注冊這些監聽器。你可以通過SpringApplication.addListeners()或SpringApplicationBuilder.listeners()來注冊這些監聽器。
如果你想自動注冊這些監聽器,不管上下文的創建方式,你可以在你的工程中添加META-INF/spring.factories文件,並通過org.springframework.context.ApplicationListener作為key來引用你的監聽器。
當應用運行時,運用的發送順序
- ApplicationStartingEvent
- ApplicationEnvironmentPreparedEvent
- ApplicationPreparedEvent
- ApplicationReadyEvent
- ApplicationFailedEvent
web環境
SpringApplication將試圖創建一個正確類型的ApplicationContext。如果是web應用,創建一個AnnotationConfigEmbeddedWebApplicationContext ,否則創建一個AnnotationConfigApplicationContext。
訪問應用參數
啟動應用時,我們會通過SpringApplication.run(args)添加啟動參數args,我們可通過注入org.springframework.boot.ApplicationArguments來獲取啟動參數。
在應用啟動過程中做一些事
實現ApplicationRunner或CommandLineRunner接口。
應用退出攔截
使用@PreDestroy注解或實現org.springframework.boot.ExitCodeGenerator接口
可變配置
可通過“application.properties”(或YAML 變量)對默認配置進行修改。
通過命令行對配置進行修改,即SpringApplication.run(MainApplicion.class, args)中的args參數,如--server.port=9000則啟動端口變成了9000。
配置隨機數
my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}
把配置文件中的配置綁定到Bean中,可使用@value,還可以使用@ConfigurationProperties,如下
my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com
@ConfigurationProperties(prefix="my")
public class Config {
private List<String> servers = new ArrayList<String>();
public List<String> getServers() {
return this.servers;
}
}
profile(不同環境讀取不同配置)
不同環境的配置設置一個配置文件,例如:dev環境下的配置配置在application-dev.properties中;pro環境下的配置配置在application-pro.properties中。
各個環境公共的配置寫在application.properties中。
各個模塊獨有的配置配置在自己的application-{xxx}.properties文件中。
指定某一環境運行,使用spring.profiles.active進行配置
SpringApplication.run(MainApplicion.class, "--spring.profiles.active=dev");
日志
說明
默認日志框架是“Commons Logging”,但如果是用“Starters”,那么默認日志框架是“Logback”
默認打印級別是INFO,若要開啟,有兩種方式
java -jar myapp.jar --debug
在application.properties中添加debug=true
文件輸出
默認是只打打印在控制台上,不輸出到文件,可配置。
可在application.properties中配置logging.file或 logging.path
日志級別
格式:logging.level.*=LEVEL,LEVEL的取值有(TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF)
自定義日志格式
根據不同的日志框架,編寫不同的配置文件
| Logging System | Customization |
|---|---|
| Customization | logback-spring.xml, logback-spring.groovy, logback.xml or logback.groovy |
| Log4j2 | log4j2-spring.xml or log4j2.xml |
| JDK (Java Util Logging) | logging.properties |
開發web應用
Spring MVC框架
使用HttpMessageConverter轉換HTTP中的requests 和 responses
使用@JsonComponent注解來實現JSON的序列號跟反序列化
import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import org.springframework.boot.jackson.*;
@JsonComponent
public class Example {
public static class Serializer extends JsonSerializer<SomeObject> {
// ...
}
public static class Deserializer extends JsonDeserializer<SomeObject> {
// ...
}
}
靜態資源
默認配置的 /** 映射到 /static (或/public、/resources、/META-INF/resources),上面的 static、public、resources 等目錄都在 classpath: 下面(如 src/main/resources/static)。
優先級順序為:META/resources > resources > static > public
如:src/main/resources/static/js/test.js的訪問路徑為http://localhost:8080/js/test.js
注意:不要使用src/main/webapp文件夾,因為打成jar包時,這個文件夾不會被打包進去。
當我們的資源內容發生改變時,由於瀏覽器緩存,用戶本地的資源還是舊資源,為了防止這種情況發生導致的問題。Spring在解決這種問題方面,提供了2種解決方式:資源名稱md5方式、資源名稱md5方式。
錯誤處理
自定義錯誤頁面
src/
+- main/
+- java/
| + <source code>
+- resources/
+- static/
+- error/
| +- 404.html
| +- 5xx.ftl
+- <other public assets>
嵌入的Servlet容器支持
可使用@WebServlet, @WebFilter, @WebListener注解,還有@ServletComponentScan注解掃描來支持Servlet、Filter、Listener
JSP支持
1、打包方式需要改成war。
2、添加必要的依賴
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- Provided -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
3、新建文件夾src/main/webapp/WEB-INF/jsp/。
4、application.properties文件添加配置
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
5、創建Controller跟jsp文件
其他特性
- Security
- SQL databases
- NoSQL technologies
- Caching
- Messaging
- Validation
- Sending email
- JTA
- JMX
- Testing
