Spring boot-(2) Spring Boot使用


1. 構建系統

(1) 使用maven構建

 1) 從Starter Parent繼承

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

<!-- 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的版本信息。

在如上配置中,如果想覆蓋獨立的依賴,可以通過在項目中覆蓋默認屬性即可,如下所示:

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

2) 不使用parent的POM依賴

如果不使用spring-boot-starter-parent, 可以通過使用scope=import依賴,進而保留依賴管理的好處。如下所示:

<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之前

<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>中設置。如下所示:

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

同樣說明的是,如果使用parent依賴,則該插件不需要進一步配置。

(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不需要任何任何特殊的代碼組織,但有如下一些實踐經驗:

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設置時,服務端部分自動可用。客戶端部分則必須手動啟動。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM