Spring Boot 框架介紹和使用

本文參考自Spring Boot文檔css

Spring Boot 簡介

Spring框架功能很強大,可是就算是一個很簡單的項目,咱們也要配置不少東西。所以就有了Spring Boot框架,它的做用很簡單,就是幫咱們自動配置。Spring Boot框架的核心就是自動配置,只要存在相應的jar包,Spring就幫咱們自動配置。若是默認配置不能知足需求,咱們還能夠替換掉自動配置類,使用咱們本身的配置。另外,Spring Boot還集成了嵌入式的Web服務器,系統監控等不少有用的功,讓咱們快速構建企業及應用程序。html

建立項目

建立項目

建立項目很簡單。若是使用STS的話,新建Spring Starter項目便可。若是使用IDEA的話,新建Spring Initializer項目。若是不想使用IDE的話,從start.spring.io建立項目也能夠。例以下面就是一個Spring Boot項目的build.gradle文件,是我用IDEA建立的項目。因爲我是用了最新的快照版本,所以這裏的倉庫還多了兩個Spring的快找倉庫,能夠直接無視。(由於1.5的穩定版中Thymeleaf的支持纔到2,爲了使用最新Thymeleaf3,只能使用最新的快照版。)java

咱們能夠看到Spring Boot和通常的項目差很少,只不過多應用了Spring Boot插件,它會讓咱們更方便的運行Spring。另外在項目中沒有其餘依賴的引用,只引用了Spring Boot Starter依賴,這些依賴會將可能會使用到的依賴幫咱們引用。例如spring-boot-starter-test會引用JUnit、AssertJ等一些測試框架,咱們不用再引用了。這極大地方便了咱們的開發。並且這些依賴不須要指定具體版本,具體的版本由Spring幫咱們決定。關於詳細的Starter項目和具體jar包的版本號,參考13.5. StartersF. Dependency versionsmysql

buildscript {
    ext {
        springBootVersion = '2.0.0.BUILD-SNAPSHOT'
    }
    repositories {
        mavenCentral()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

jar {
    baseName = 'spring-boot-sample'
    version = '0.0.1-SNAPSHOT'
}

sourceCompatibility = 1.8

repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://repo.spring.io/milestone" }
}


dependencies {
    compile('org.springframework.boot:spring-boot-starter-aop')
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-thymeleaf')
    compile('org.springframework.boot:spring-boot-starter-web')
    runtime('org.springframework.boot:spring-boot-devtools')
    runtime('org.hsqldb:hsqldb')
    runtime('mysql:mysql-connector-java')
    compileOnly('org.projectlombok:lombok')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

項目格式

項目格式相似下圖,和通常的Maven或者Gradle項目相似,只不過多了點東西。資源文件夾下static文件夾用來存放web程序的靜態資源,例如圖片、css、js等。template文件夾存放web程序的視圖模板,html等須要渲染的模板文件就放在這裏。application.properties文件很重要,它是Spring Boot項目的全局配置文件。以往咱們須要編寫層級XML配置文件,如今只須要在這裏使用key=value方式便可指定這些屬性。默認的模板還爲咱們添加了兩個類。一個在main下,是Spring Boot項目的運行類,另外一個在test下,是測試類。web

項目格式

運行類的代碼以下。它是一個簡單的類,包含了主方法,並且類上使用了@SpringBootApplication註解。這是一個慣用註解,它會幫咱們啓用自動配置等特性。spring

@SpringBootApplication
public class SpringBootSampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootSampleApplication.class, args);
    }
}

若是看一下SpringBootApplication的源代碼,相似下面這樣。能夠看到,SpringBootApplication的功能是經過幾個註解實現的。EnableAutoConfiguration註解啓用了自動配置功能。ComponentScan註解會掃描該類所在的包和子包。因此Spring推薦咱們將這個運行類放到項目的根包下,以便咱們不須要任何配置便可掃描到全部配置類。sql

@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 {

Spring Boot項目更喜歡Java配置方式。所以從這裏開始,全部的Spring配置都是用Java方式配置。固然若是你還想使用XML配置文件也能夠,新建一個空的配置類,而後添加@ImportResource註解並傳遞要使用的XML文件路徑便可。數據庫

運行項目

若是使用Maven的話,運行下面的命令。瀏覽器

mvn spring-boot:run

若是使用Gradle的話,使用下面的命令。tomcat

gradle bootRun

而後就會顯示相似下面的輸出,後面會跟一大堆日誌信息。若是是命令行程序的話,日誌信息以後就會顯示程序的運行結果了。若是是Web程序的話,默認狀況下會使用內嵌的Tomcat來運行。咱們使用localhost:8080來訪問便可。

.   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v2.0.0.BUILD-SNAPSHOT)

這個日誌能夠是彩色的。若是你的輸出不是彩色的,能夠在application.properties文件中添加下面一句。

spring.output.ansi.enabled=always

項目配置

自定義 SpringApplication

前面咱們看到了SpringBoot項目的啓動類是這樣的。

@SpringBootApplication()
public class SpringBootSampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootSampleApplication.class, args);
    }
}

其實,咱們能夠自定義它的各類屬性。這時候須要建立SpringApplication對象並設置它的各類屬性。比方說下面不顯示Banner。還有不少配置和用法請查閱官方文檔。

@SpringBootApplication()
public class SpringBootSampleApplication {

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(SpringBootSampleApplication.class);
        application.setBannerMode(Banner.Mode.OFF);
        application.run(args);
    }
}

事件和監聽器

若是有更高級的需求可使用監聽器來管理Spring Boot程序的各個生命週期。監聽器須要實現org.springframework.context.ApplicationListener接口。

public class MyAppListener implements ApplicationListener<ApplicationReadyEvent> {


    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        System.out.println("應用程序準備就緒");
    }
}

在監聽器中能夠設置下面幾種事件。

  • ApplicationStartingEvent

  • ApplicationEnvironmentPreparedEvent

  • ApplicationPreparedEvent

  • ApplicationReadyEvent

  • ApplicationFailedEvent

以後,把監聽器添加到Spring程序中。

@SpringBootApplication()
public class SpringBootSampleApplication {

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(SpringBootSampleApplication.class);
        application.setBannerMode(Banner.Mode.OFF);
        application.addListeners(new MyAppListener());
        application.run(args);
    }
}

Profiles

在Spring Boot中Profiles更簡單了。咱們使用application-{profile}.properties格式來區分不一樣的Profile,例如一個測試profile(application-test.properties),一個生產環境profile(application-product.properties)。

定義好多個Profiles以後,還須要在標準的application.properties中列出和啓用這些Profiles。列出使用spring.profiles.include,激活其中的一個使用spring.profiles.active

spring.output.ansi.enabled=always
spring.thymeleaf.cache=false
spring.profiles.include[0]=test
spring.profiles.include[1]=product
spring.profiles.active[0]=test

使用YAML

YAML也是一種配置文件格式,比方說上面的properties,就能夠改寫爲下面這樣的YAML文件(application.yaml)。

spring:
  output:
    ansi:
      enabled: always
  thymeleaf:
    cache: false
  profiles:
    include:
    - product
    - test
    active: test

若是須要多個Profile,YAML只須要一個文件便可,profiles之間使用---分隔開。

server:
    address: 192.168.1.100
---
spring:
    profiles: development
server:
    address: 127.0.0.1
---
spring:
    profiles: production
server:
    address: 192.168.1.120

使用Properties仍是YAML,根據我的喜愛便可。

自動配置

修改自動配置

Spring Boot的核心就是自動配置,它爲幾乎全部的Spring組件都提供了相應的自動配置類,並且默認是打開的。因此只要相關的jar文件存在,這些自動配置就會被使用。其中有些配置屬於必配的(例如Web模板),自動配置會爲咱們省下很多時間;有些配置(例如數據源)則每每須要咱們修改。Spring的自動配置是非侵入式的,因此若是咱們聲明瞭本身的數據源,那麼Spring自動配置的嵌入式數據源就會取消。

固然若是想要關閉某些自動配置也是能夠的。若是你有本身的主配置類,手動在上排除某些自動配置類便可。

@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}

若是咱們使用了SpringBootApplication註解,那麼上面這種方式須要修改一下。SpringBootApplication註解提供了幾個屬性,能夠控制排除的自動配置和組件搜索的路徑。

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class SpringBootSampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootSampleApplication.class, args);
    }
}

另外還能夠直接修改項目的屬性。咱們能夠編輯application.properties文件,在其中添加spring.autoconfigure.exclude屬性並指定要排除的類便可。

Spring的自動配置類通常在org.springframework.boot.autoconfigure包下,若是咱們須要查看當前使用了多少個自動配置類,能夠在運行程序的時候添加--debug標誌,這樣Spring會打印額外的調試信息。若是須要詳細的自動配置類的列表,能夠參考Spring Boot文檔 附錄C. Auto-configuration classes

Spring Web MVC自動配置

自動配置

MVC自動配置會啓用如下功能。

  • ContentNegotiatingViewResolverBeanNameViewResolver beans.

  • 靜態資源和WebJars的支持.

  • 自動註冊 Converter, GenericConverter, Formatter beans.

  • HttpMessageConverters 的支持.

  • 自動註冊MessageCodesResolver.

  • 靜態index.html的支持.

  • 自定義Favicon(瀏覽器頁面的小圖標) 支持.

  • 自動使用ConfigurableWebBindingInitializer bean.

自動註冊指的是,只須要在Spring中註冊相應類型的Bean。Spring Web MVC會自動識別和使用這些Bean。例如,咱們要添加新的HttpMessageConverter,只須要向下面這樣。

@Configuration
public class MyConfiguration {

    @Bean
    public HttpMessageConverters customConverters() {
        HttpMessageConverter<?> additional = ...
        HttpMessageConverter<?> another = ...
        return new HttpMessageConverters(additional, another);
    }

}

靜態資源

靜態資源默認放在resources文件夾的/static (或 /public/resources/META-INF/resources下面。若是須要配置位置的話,在屬性文件中添加spring.mvc.static-path-pattern=/resources/**

若是須要靜態主頁,直接在resources/static/下放入一個index.html便可。

favicon.ico

若是須要配置本身的favicon.ico,只須要將本身的favicon.ico直接放到resources文件夾下便可。

視圖模板

Spring會對Thymeleaf、Freemarker、Groovy和mustache四種模板進行自動配置。默認的模板路徑爲resources/templates

錯誤處理

錯誤處理和通常的Spring Web MVC相似,使用@ControllerAdvice

自定義錯誤頁面放在下面的路徑。

src/
 +- main/
     +- java/
     |   + <source code>
     +- resources/
         +- public/
             +- error/
             |   +- 404.html
             +- <other public assets>

若是錯誤頁面也須要使用模板引擎動態生成,那麼放在下面的路徑。

src/
 +- main/
     +- java/
     |   + <source code>
     +- resources/
         +- templates/
             +- error/
             |   +- 5xx.ftl
             +- <other templates>

SQL數據庫自動配置

嵌入式數據庫

若是類路徑中包含HSQL、Derby或H2的相應jar包,那麼Spring就會自動配置這些嵌入式數據庫的實例和數據源。它們會將數據保存在內存中,當程序結束以後數據會丟失。這很是適合開發和測試。

在不一樣的測試中Spring默認會重用這些嵌入式數據庫。假如不一樣測試之間的數據不一樣,你可能但願每次測試都使用新的數據庫。這時候能夠在屬性文件中指定spring.datasource.generate-unique-name=true

生產數據庫

Spring會自動選擇帶鏈接池的數據源,遵循如下規則:

  • 若是存在tomcat-jdbc數據源,則使用它。

  • 不然,若是存在HikariCP,則使用它。

  • 若是前兩個都不存在,而存在DBCP2,則使用它。

這時候咱們須要提供數據源的額外配置信息。

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

JdbcTemplate

JdbcTemplateNamedParameterJdbcTemplate會由上面的數據源自動配置。咱們直接使用@Autowire注入到程序中便可。

JPA自動配置

實體類

JPA Entity類(標記了@Entity的類)默認在persistence.xml中配置。在Spring Boot中,@EnableAutoConfiguration@SpringBootApplication包下的實體類會被自動掃描到。若是但願自定義實體類的位置,可使用@EntityScan註解,添加到配置類上便可。

Spring Data JPA

繼承了 Repository的接口會被自動掃描到,咱們不須要作任何配置。若是須要配置,設置spring.jpa.*屬性。例以下面指定了數據的生成策略。

spring.jpa.hibernate.ddl-auto=update

H2的web控制檯

H2嵌入式數據庫提供了一個基於web界面的控制檯。這個控制檯也能夠由Spring自動配置。當(1:存在H2相關jar包,2:當前程序是一個web程序,3:devtoos存在)的狀況下,Spring便會自動配置H2控制檯。

web控制檯的訪問路徑默認爲/h2-console。咱們可使用spring.h2.console.path屬性修改它。

H2 web控制檯

如圖,這是一個完整的交互界面,咱們能夠方便的在這裏處理數據。若是須要設置訪問控制權限,添加下面的屬性。

  • security.user.role

  • security.basic.authorize-mode

  • security.basic.enabled

若是不想使用該控制檯,可使用spring.h2.console.enabled=false關閉它。在生產環境中記得把它關掉。

最後我要說一點,Spring Boot文檔包含了不少其餘Spring項目的自動配置,這裏不可能全寫完。因此若是須要詳細信息的話仍是直接啃文檔吧。

其餘配置

調試工具(devtools)

若是使用Maven,添加下面的依賴。

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

若是使用Gradle,添加下面的依賴。

dependencies {
    compile("org.springframework.boot:spring-boot-devtools")
}

這樣就能夠將調試工具添加到項目中。調試工具添加了熱更新、自動重啓等幾個很是有用的調試功能。自動重啓須要Spring檢測到類路徑上有更改,在Spring Tool Suite中,簡單的保存文件便可達到效果。若是在Intellij IDEA中,只能選擇Build Project。

輸出日誌

Spring Boot默認使用Logback來打印日誌。不過咱們直接使用slf4j提供的接口就能夠了。slf4j和Logback也都由Spring自動配置好了。咱們只須要在屬性文件中設置日誌級別便可。

logging.level.yitian.study=debug

而後在代碼中調用slf4j的日誌接口並打印日誌便可。

@Controller
public class MainController {
    private Logger logger = LoggerFactory.getLogger(MainController.class);

    @RequestMapping("/")
    public String index(@RequestParam(defaultValue = "苟") String name, Model model) {
        model.addAttribute("name", name);
        logger.debug("訪問了主頁");
        return "index";
    }
}

日誌信息和Spring的輸出格式同樣。另外隨着日誌級別的變化,日誌的顏色也會在綠、黃和紅之間變化,很是方便。

2017-03-16 23:50:19.628  INFO 17220 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 4 ms
2017-03-16 23:50:19.632 ERROR 17220 --- [nio-8080-exec-1] yitian.study.controller.MainController   : 訪問了主頁

自定義Banner

這個Banner也是能夠定製的。在類路徑(也就是resource文件夾下)添加banner.txt,Banner就會使用你的文本。Banner甚至能夠是一張圖片,支持gif、jpg、png等格式。Spring會將圖片轉換成字符形式。

Servlet容器

默認狀況下Spring使用Tomcat做爲嵌入式容器。

端口號

端口號使用server.port設置。若是但願在運行時隨機分配一個未使用的端口號,能夠將端口號設置爲0:server.port=0

使用Jetty

spring-boot-starter-web包默認使用Tomcat,若是咱們但願使用Jetty,就須要排除Tomcat的包。使用Maven的話,這麼作。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

若是使用Gradle的話,這麼作。

configurations {
    compile.exclude module: "spring-boot-starter-tomcat"
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:2.0.0.BUILD-SNAPSHOT")
    compile("org.springframework.boot:spring-boot-starter-jetty:2.0.0.BUILD-SNAPSHOT")
    // ...
}

響應壓縮

使用server.compression.enabled=true啓用HTTP的響應壓縮。默認狀況下要壓縮的響應體至少須要2048字節,可使用server.compression.min-response-size修改這個值。

打包和運行

Spring Boot項目默認打包爲jar文件。咱們可使用Maven或Gradle的打包命令來打包項目。打包好以後,就能夠和通常jar文件同樣,使用java命令來運行了。若是但願打包爲war文件的話也能夠,不過因爲篇幅所限就不介紹了。直接看源文檔吧。

系統監控(Actuator)

Actuator我沒理解怎麼翻譯,因此憑個人感受就叫作系統監控吧。這些功能能夠幫助咱們監控正在運行的Spring Boot項目。要啓用監控功能,須要添加spring-boot-starter-actuator。使用Maven的話,添加下面的依賴。

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

若是使用Gradle的話,添加下面的依賴。

dependencies {
    compile("org.springframework.boot:spring-boot-starter-actuator")
}

端點(Endpoints)

每一個端點就是一個監控項。Spring包含了不少端點,詳細列表在這裏47. Endpoints。除了health以外,其他端點都屬於敏感信息,在沒有設置Spring Security的狀況下沒法訪問。爲了簡單的在本地訪問,咱們能夠設置management.security.enabled=false。注意該選項在生產環境中務必打開,保證服務器信息不會泄露。

端點的訪問路徑默認是/端點名,例如health的訪問路徑就是/health。比較有用的幾個端點是beans(列出當前全部已註冊的Spring Beans)、mappings(全部的控制器映射路徑)、trace(最近100個HTTP鏈接的信息)、health(服務器當前的運行狀態和磁盤剩餘空間以及數據庫的運行狀態)。還有一個有趣的端點是shutdown,當咱們向/shutdown發送post請求時服務器就會關閉,不過該功能是默認關閉的。

端點能夠在屬性文件中設置,每一個端點敏感性和是否啓用都是能夠定製的。

endpoints.beans.sensitive=false
endpoints.shutdown.enabled=true

端點的訪問也是能夠定製的。

management.port=8081
management.address=127.0.0.1

好了,Spring Boot框架的介紹到此爲止。咱們已經基本看到了Spring Boto的使用方法。固然官方文檔還有不少內容這裏沒有列出。這裏也不可能徹底列出來。若是須要更詳細的介紹仍是直接看官方文檔吧。沒有比這個更全面的了。

相關文章
相關標籤/搜索