Spring boot-(2) Spring Boot使用

1. 構建系統

(1) 使用maven構建

 1) 從Starter Parent繼承

在項目中配置繼承spring-boot-starter-parent,能夠進行以下設置:html

<!-- Inherit defaults from Spring Boot -->
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.0.0.BUILD-SNAPSHOT</version>
</parent>

注意,設置版本號時,只須要在該parent中設置,若是想增長starters,則能夠自動優化這些starters的版本信息。java

在如上配置中,若是想覆蓋獨立的依賴,能夠經過在項目中覆蓋默認屬性便可,以下所示:react

<properties>
	<spring-data-releasetrain.version>Fowler-SR2</spring-data-releasetrain.version>
</properties>
View Code

2) 不使用parent的POM依賴

若是不使用spring-boot-starter-parent, 能夠經過使用scope=import依賴,進而保留依賴管理的好處。以下所示:web

<dependencyManagement>
		<dependencies>
		<dependency>
			<!-- Import dependency management from Spring Boot -->
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-dependencies</artifactId>
			<version>2.0.0.BUILD-SNAPSHOT</version>
			<type>pom</type>
	        <scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>
View Code

上述配置不容許使用property屬性覆蓋獨立的依賴,若是想要實現覆蓋,能夠在項目中的dependencyManagement,做以下設置,且注意獨立的依賴須要在spring-boot-dependencies以前redis

<dependencyManagement>
	<dependencies>
		<!-- Override Spring Data release train provided by Spring Boot -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-releasetrain</artifactId>
			<version>Fowler-SR2</version>
			<scope>import</scope>
			<type>pom</type>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-dependencies</artifactId>
			<version>2.0.0.BUILD-SNAPSHOT</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>
View Code

3) 使用Spring Boot Maven插件

Spring Boot包含Maven插件,可以將項目打包爲可執行的jar包。能夠在<plugins>中設置。以下所示:spring

<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
		</plugin>
	</plugins>
</build>
View Code

一樣說明的是,若是使用parent依賴,則該插件不須要進一步配置。mongodb

(2) Starters

Spring Boot的Starters提供了Spring及其相關技術等方便的依賴描述,例如,若是須要使用Spring和JPA來訪問數據庫,能夠在項目中增長spring-boot-starter-data-jpa依賴便可。目前支持的starters以下:數據庫

名稱 說明
spring-boot-starter 核心啓動器,包括自動配置支持,日誌記錄和YAML
spring-boot-starter-activemq 使用Apache ActiveMQ的JMS啓動器
spring-boot-starter-amqp 使用Spring AMQP和Rabbit MQ的啓動器
spring-boot-starter-aop 使用Spring AOP和AspectJ進行面向切面編程的啓動器
spring-boot-starter-artemis 使用Apache Artemis的JMS啓動器
spring-boot-starter-batch 使用Spring Batch的啓動器
spring-boot-starter-cache 使用Spring Framework緩存支持的啓動器
spring-boot-starter-cloud-connectors 使用Spring Cloud鏈接器,簡化了與Cloud Foundry和Heroku等雲平臺中的服務鏈接的啓動器
spring-boot-starter-data-cassandra 使用Cassandra分佈式數據庫和Spring Data Cassandra的啓動器
spring-boot-starter-data-cassandra-reactive 使用Cassandra分佈式數據庫和Spring Data Cassandra Reactive的啓動器
spring-boot-starter-data-couchbase 使用Couchbase面向文檔的數據庫和Spring Data Couchbase的啓動器
spring-boot-starter-data-couchbase-reactive 使用Couchbase面向文檔的數據庫和Spring Data Couchbase Reactive的啓動器
spring-boot-starter-data-elasticsearch 使用Elasticsearch搜索和分析引擎和Spring Data Elasticsearch的啓動器
spring-boot-starter-data-jpa 使用Spring數據JPA與Hibernate的啓動器
spring-boot-starter-data-ldap 使用Spring Data LDAP的啓動器
spring-boot-starter-mongodb 使用MongoDB面向文檔的數據庫和Spring Data MongoDB的啓動器
spring-boot-starter-mongodb-reactive 使用MongoDB面向文檔的數據庫和Spring Data MongoDB Recative的啓動器
spring-boot-starter-neo4j 使用Neo4j圖數據庫和Spring Data Neo4j的啓動器
spring-boot-starter-redis Redis key-value 數據存儲與Spring Data Redis和Jedis客戶端啓動器
spring-boot-starter-redis-reactive Redis key-value 數據存儲與Spring Data Redis Reactive和Jedis客戶端啓動器
spring-boot-starter-data-rest 經過使用Spring Data REST在REST上暴露Spring數據庫的啓動器
spring-boot-starter-data-solr 使用Apache Solr搜索平臺與Spring Data Solr的啓動器
spring-boot-starter-freemarker 使用FreeMarker視圖構建MVC Web應用程序的啓動器
spring-boot-starter-groovy-templates 使用Groovy模板視圖構建MVC Web應用程序的啓動器
spring-boot-starter-hateoas 使用Spring MVC和Spring HATEOAS構建基於超媒體的RESTful Web應用程序的啓動器
spring-boot-starter-integration Spring Integration 啓動器
spring-boot-starter-jdbc 使用JDBC與Tomcat JDBC鏈接池的啓動器
spring-boot-starter-jersey 使用JAX-RS和Jersey構建RESTful Web應用程序的啓動器。spring-boot-starter-web的替代方案
spring-boot-starter-jooq 使用jOOQ訪問SQL數據庫的啓動器。 spring-boot-starter-data-jpa或spring-boot-starter-jdbc的替代方案
spring-boot-starter-json 用於讀取和寫入json的啓動器
spring-boot-starter-jta-atomikos 使用Atomikos的JTA事務的啓動器
spring-boot-starter-jta-bitronix 使用Bitronix進行JTA 事務的啓動器
spring-boot-starter-jta-narayana Spring Boot Narayana JTA 啓動器
spring-boot-starter-mail Java Mail和Spring Framework的電子郵件發送支持的啓動器
spring-boot-starter-mustache 使用Mustache視圖構建MVC Web應用程序的啓動器
spring-boot-starter-quartz Spring Boot Quartz啓動器
spring-boot-starter-security 使用Spring Security的啓動器
spring-boot-starter-test 使用JUnit,Hamcrest和Mockito的庫測試Spring Boot應用程序的啓動器
spring-boot-starter-thymeleaf 使用Thymeleaf視圖構建MVC Web應用程序的啓動器
spring-boot-starter-validation 使用Java Bean Validation 與Hibernate Validator的啓動器
spring-boot-starter-web 使用Spring MVC構建Web,包括RESTful應用程序。使用Tomcat做爲默認的嵌入式容器的啓動器
spring-boot-starter-web-services Spring Web Services 啓動器

spring-boot-starter-webflux編程

Starter for building WebFlux applications using Spring Framework’s Reactive Web support
spring-boot-starter-websocket Starter for building WebSocket applications using Spring Framework’s WebSocket support
spring-boot-starter-actuator 使用Spring Boot Actuator提供生產準備功能,可幫助您監控和管理應用程序的啓動器
spring-boot-starter-jetty 使用Jetty做爲嵌入式servlet容器的啓動器。 spring-boot-starter-tomcat的替代方案
spring-boot-starter-log4j2 使用Log4j2進行日誌記錄的啓動器。 spring-boot-start-logging的替代方法
spring-boot-starter-logging 使用Logback進行日誌記錄的啓動器。 默認的日誌啓動器
spring-boot-starter-reactor-netty 使用Reactive Netty做爲嵌入式reactive http服務器
spring-boot-starter-tomcat 使用Tomcat做爲嵌入式servlet容器的啓動器。 spring-boot-starter-web的默認servlet容器啓動器
spring-boot-starter-undertow 使用Undertow做爲嵌入式servlet容器的啓動器。 spring-boot-starter-tomcat的替代方案

2. 構造代碼

Spring Boot不須要任何任何特殊的代碼組織,但有以下一些實踐經驗:json

1) 不要使用"默認"的包

類中不包含"package"聲明,即便用默認包。默認包儘可能避免,在Spring Boot中使用@ComponentScan, @EntityScan或@SpringBootApplication註解時,會致使特殊異常。

2) 定位主應用類

一般建議將主應用類放在其餘類之上根包中,@EnableAutoConfiguration註解常常會放在主類中。以下顯示典型的層級:

com
 +- example
     +- myapplication
         +- Application.java
         |
         +- customer
         |   +- Customer.java
         |   +- CustomerController.java
         |   +- CustomerService.java
         |   +- CustomerRepository.java
         |
         +- order
             +- Order.java
             +- OrderController.java
             +- OrderService.java
             +- OrderRepository.java
View Code

Application.java中應該聲明main方法,以及一些基礎的@Configuration註解等,以下:

package com.example.myapplication;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {

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

}

3. 配置類

Spring Boot一般建議配置時,主source是@Configuration類,一般,定義main方法的類也是做爲主要的@Configuration一個很好的選擇。

1) 導入額外的配置類

不須要將全部的@Configuration放在一個類中,@Import註解用於導入其餘額外的配置類。另外,也可以使用@CompomentScan註解自動選取全部的Spring組件,包含@Configutation類。

2) 導入XML配置

若是必須使用基於XML的配置,建議仍以@Configuration類開始,而後使用@ImportResource註解導入XML配置文件。

4. 自動配置

Spring Boot的自動配置會基於所添加的依賴包進行自動配置Spring應用。例如若HSQDB在classpath中,且沒有手動配置任何數據庫鏈接,Spring Boot會自動配置該內存數據庫。

自動配置時,能夠將@EnableAutoConfiguration或@SpringBootApplication增長到@Configuration類中。注意,應該只在主要的@Configuration類中增長一個@EnableAutoConfiguration註解。

1) 逐漸替代自動配置

自動配置是非侵入式的,你能夠定義本身的配置來替代自動配置。若是想查看當前哪些自動配置在使用,可以使用-debug開關啓動應用程序,這將啓動debug日誌,並將自動配置日誌記錄到控制檯。

2) 禁用指定的自動配置

若是你不想使用一些指定的自動配置類,可使用@EnableAutoConfiguration的exclude屬性,以下例所示: 

import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;

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

若是類不在classpath中,可使用excludeName屬性指定全限定名。最後,也能夠禁用自動配置類列表,經過使用spring.autoconfigure.exclude屬性。

5. Spring Beans和依賴注入

能夠隨意使用標準Spring框架技術定義本身的beans及注入依賴。發現能夠經過使用@ComponentScan註解來查找beans,使用@Autowired構造函數注入效果很好。

若是按照上述建議(將應用類放在根包中)構建代碼,則能夠增長@ComponentScan,且不須要任何參數。全部的應用組件如@Compent, @Service, @Reposity, @Controller等都將自動註冊爲Spring Beans。

下例展現了一個@Service Bean,經過構造函數注入獲取一個RiskAssessor bean。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DatabaseAccountService implements AccountService {

	private final RiskAssessor riskAssessor;

	@Autowired
	public DatabaseAccountService(RiskAssessor riskAssessor) {
		this.riskAssessor = riskAssessor;
	}
}
View Code

若是一個bean只有一個構造函數,則能夠省略@Autowired方法。注意如何使用構造方法注入使得riskAssessor標記爲final, 後續使用該變量時則不可改變。

@Service
public class DatabaseAccountService implements AccountService {

	private final RiskAssessor riskAssessor;

	public DatabaseAccountService(RiskAssessor riskAssessor) {
		this.riskAssessor = riskAssessor;
	}
}
View Code

6. 使用@SpringBootApplication註解

許多Spring Boot開發者常常在主類中加入@Configuration, @EnableAutoConfiguration, @CompomentScan等註解, Spring Boot提供一個更簡潔的選擇@SpringBootApplication。以下所示:

package com.example.myapplication;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {

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

}
View Code

7. 運行程序

1) 運行jar包程序,可使用以下命令:

java -jar target/myapplication-0.0.1-SNAPSHOT.jar

# 以遠程調試的方式運行
java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n -jar target/myapplication-0.0.1-SNAPSHOT.jar

2) 使用Maven插件,直接運行 mvn spring-boot:run,若是想使用MAVEN_OPTS環境參數,可使用 export MAVEN_OPTS=-Xmx1024m

8. 開發工具

spring-boot-devtools模塊可提供額外的開發時功能,能夠經過以下方法加載該依賴:

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

(1) 屬性默認值

緩存在生產中很是有益,但在開發過程當中可能產生反效果。spring-boot-devtools將默認禁用緩存選項。緩存選項一般在application.properties中設置,而spring-boot-devtools模塊不須要手動設置這些屬性,而是自動應用更加合理的development-time配置。

(2) 自動重啓

使用spring-boot-devtools的應用程序將在類路徑上的文件發生更改時自動重啓。且默認狀況下,將監視指向文件夾的類路徑上的任何條目。注意,靜態資源和視圖模板不須要從新啓動應用程序。

Spring boot提供的從新啓動技術使用兩個類加載器。不會更改的類如第三方的jar被加載到基類加載器中。正在開發的類被加載到從新啓動類加載器中。當應用程序從新啓動時,從新啓動類加載器將被丟棄,並建立一個新的類加載器

1) 排除資源

在類路徑下,某些資源更改時不必定須要觸發從新啓動。默認狀況下,有一些排除項,如/META-INF/maven, /META-INF/resources, /resources/, /static, /public或/templates中的資源不會觸發啓動,但會重發實施從新加載。若是要自定義排除項,可使用spring.devtools.restart.exclude屬性。如要僅排除/static和/public,能夠設置:spring.devtools.restart.exclude=static/**,public/**。若是要保留這些默認值並添加其餘排除項,可以使用spring-devtools.restart.additional-exclude屬性

2) 監視額外路徑

有時須要監視不在類路徑中的文件更改,進而從新啓動或從新加載應用程序,可以使用spring.devtools.restart.additional-paths屬性配置其餘路徑。可使用上述的spring.devtools.restart.exclude屬性控制附加路徑下的更改是否會觸發徹底從新啓動或只是實施從新加載。

3) 禁用重啓

若是不想使用從新啓動功能,可使用spring.devtools.restart.enabled屬性來禁用。如須要徹底禁用從新啓動,在調用SpringApplication.run以前設置System屬性。

public static void main(String[] args) {
	System.setProperty("spring.devtools.restart.enabled", "false");
	SpringApplication.run(MyApp.class, args);
}
View Code

4) 使用觸發文件

如使用IDE編寫代碼或更改文件,你可能但願僅在特定時間觸發從新啓動,可使用"觸發文件"。可以使用spring.devtools.restart.trigger-file屬性。

5) 自定義從新啓動類加載器

如上所述,IDE默認狀況下打開的項目將使用"從新啓動"類加載器加載,任何常規jar將使用基類加載器加載。若在多模塊項目中工做,則可能須要自定義事件。爲此,能夠建立一個META-INF/spring-devtools.properties。spring-devtools.properties文件能夠包含restart.exclude和restart.include.prefixed屬性。如:

restart.exclude.companycommonlibs=/mycorp-common-[\\w-]+\.jar
restart.include.projectcommon=/mycorp-myproj-[\\w-]+\.jar
View Code

(3) LiveReload

spring-boot-devtools包含一個嵌入式LiveReload服務器,能夠在資源更改時用於觸發瀏覽器更新。若是不想在應用程序中啓動LiveReload服務器,可將spring.devtools.livereload.enabled屬性設爲false。

(4) 全局設置

能夠向$HOME文件夾添加名爲.spring-boot-devtools.properties的文件配置全局devtools設置(注意以"."開頭)。添加到此文件的任何屬性將適用於所在計算機上使用devtools的全部spring boot應用程序。例如:要配置從新啓動以始終使用觸發器文件,能夠在~/.spring-boot-devtools.properties中添加:spring.devtools.reload.trigger-file=.reloadtrigger。

(5) 遠程調用

spring boot不只限於本地開發,也支持遠程運行。遠程支持是可選的,若是想使用該功能,首先須要確保devtools包含在從新打包存檔中,以下所示:

<build>
  <plugins>
    <plugin>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-maven-plugin</artifactId>
	<configuration>
		<excludeDevtools>false</excludeDevtools>
	</configuration>
    </plugin>
  </plugins>
</build>
View Code

而後須要設置spring.devtools.remote.secret屬性,如:spring.devtools.remote.secret=mysecret。注意:生產環境禁用遠程調用

遠程devtools支持包含兩部分:接收鏈接的服務端和運行在IDE上的客戶端程序。當spring.devtools.remote.secret設置時,服務端部分自動可用。客戶端部分則必須手動啓動。

相關文章
相關標籤/搜索