435
技術社區[雲棲]
Spring Cloud連載(3)Spring Boot簡介與配置
本站小福利 點我獲取阿裏雲優惠券
原文作者:楊大仙的程序空間
3 Spring Boot簡介與配置
3.1 Spring Boot
Spring Cloud基於Spring Boot搭建,本小節將對Spring Boot作一個大致的講解,讀者知道Spring Boot作用即可。
3.1.1 Spring Boot簡介
開發一個全新的項目,需要先進行開發環境的搭建,例如要確定技術框架以及版本,還要考慮各個框架之間的版本兼容問題,完成這些繁瑣的工作後,還要對新項目進行配置,測試能否正常運行,最後才將搭建好的環境提交給項目組的其他成員使用。經常出現的情形是,表麵上已經成功運行,但部分項目組成員仍然無法運行,項目初期浪費大量的時間做這些工作,幾乎每個項目都會投入部分工作量來做這些固定的事情。
受Ruby On Rails、Node.js等技術的影響,JavaEE領域需要一種更為簡便的開發方式,來取代這些繁瑣的項目搭建工作。在此背景下,Spring推出了Spring Boot項目,該項目可以讓使用者更快速的搭建項目,使用者可以更專注、快速的投入到業務係統開發中。係統配置、基礎代碼、項目依賴的jar包,甚至是開發時所用到的應用服務器等,Spring Boot已經幫我們準備好,隻要在建立項目時,使用構建工具加入相應的Spring Boot依賴包,項目即可運行,使用者無需關心版本兼容等問題。
Spring Boot支持Maven和Gradle這兩款構建工具。Gradle使用Groovy語言進行構建腳本的編寫,與Maven、Ant等構建工具有良好的兼容性。鑒於筆者使用Maven較多,因此本書使用Maven作為項目構建工具。筆者成書時,Spring Boot最新的正式版本為1.5.4,要求Maven版本為3.2或以上。
3.1.2 新建Maven項目
在新建菜單中選擇新建“Maven Project”,填寫的項目信息如圖2-5所示。
圖2-5 新建Maven項目
為了測試項目的可用性,加入Spring Boot的web啟動模塊,讓該項目具有Web容器的功能,pom.xml文件內容如代碼清單2-1所示。
代碼清單2-1:codes\02\env-test\pom.xml
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.crazyit.cloud</groupId>
<artifactId>env-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.4.RELEASE</version>
</dependency>
</dependencies>
</project>
配置完依賴後,該依賴會自動幫我們的項目加上其他的Spring模塊以及所依賴的第三方包,例如spring-core、sprin-beans、spring-mvc等,除了這些模塊外,還加入了嵌入式的Tomcat。
3.1.3 編寫啟動類
加入了依賴後,隻需要編寫一個簡單的啟動類,即可啟動Web服務,啟動類如代碼清單2-2所示。
代碼清單2-2:codes\02\env-test\src\main\java\org\crazyit\cloud\MyApplication.java
package org.crazyit.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
MyApplication類使用了@SpringBootApplication注解,該注解聲明了該類是一個Spring Boot應用,該注解具有“@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan”等注解的功能。直接運行MyApplication的main方法,看到以下輸出信息後,證明成功啟動:
2017-08-02 20:53:05.327 INFO 1976 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-02 20:53:05.530 INFO 1976 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-08-02 20:53:05.878 INFO 1976 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-08-02 20:53:05.885 INFO 1976 --- [ main] org.crazyit.cloud.MyApplication : Started MyApplication in 5.758 seconds (JVM running for 6.426)
根據輸出信息可知,啟動的Tomcat端口為8080,打開瀏覽器訪問:https://localhost:8080,可以看到錯誤頁麵,表示應用已經成功啟動。
3.1.4 編寫控製器
在前麵小節加入的spring-boot-starter-web模塊,默認集成了SpringMVC,因此隻需要編寫一個Controller,即可實現一個最簡單的HelloWord程序,代碼清單2-3為控製器。
代碼清單2-3:codes\02\env-test\src\main\java\org\crazyit\cloud\MyController.java
package org.crazyit.cloud;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@Controller
public class MyController {
@GetMapping("/hello")
@ResponseBody
public String hello() {
return "Hello World";
}
}
代碼清單2-3中使用了@Controller注解來修飾MyController,由於啟動類中使用了@SpringBootApplication注解,該注解含有@ComponentScan的功能,因此@Controller會被掃描並注冊。在hello方法中使用了@GetMapping與@ResponseBody注解,聲明hello方法的訪問地址以及返回內容。重新運行啟動類,打開瀏覽器並訪問以下地址:https://localhost:8080/hello,可以看到控製器的返回。
3.1.5 發布REST WebService
Spring MVC支持直接發布REST風格的WebService,新建測試的對象Person,如代碼清單2-4所示。
代碼清單2-4:codes\02\env-test\src\main\java\org\crazyit\cloud\Person.java
package org.crazyit.cloud;
public class Person {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
修改控製器類,修改後如代碼清單2-5。
代碼清單2-5:codes\02\env-test\src\main\java\org\crazyit\cloud\MyController.java
package org.crazyit.cloud;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello World";
}
@RequestMapping(value = "/person/{personId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Person findPerson(@PathVariable("personId") Integer personId) {
Person p = new Person();
p.setId(personId);
p.setName("Crazyit");
p.setAge(30);
return p;
}
}
MyController類中,將原來的@Controller注解修改為@RestController,原來的hello方法也不需要再使用@ResponseBody進行修飾,@RestController已含有@ResponseBody注解。新建findPerson方法,該方法將會根據參數id來創建一個Person實例並返回,訪問該方法將會得到JSON字符串。運行啟動類,在瀏覽器中輸入:https://localhost:8080/person/1,可看到接口返回以下JSON字符串:
{"id":1,"name":"Crazyit","age":30}
調用REST服務的方式有很多,此部分內容將在後麵章節中講述。
3.2 Spring Boot配置文件
Spring Cloud基於Spring Boot構建,很多模塊的配置均放在Spring Boot的配置文件中,因此有必要了解一下Spring Boot的配置文件規則,為學習後麵的章節打下基礎。
3.2.1 默認配置文件
Spring Boot會按順序讀取各種配置,例如命令行參數、係統參數等,本章隻講述配置文件的參數讀取。默認情況下,Spring Boot會按順序到以下目錄讀取application.properties或者application.yml文件:
項目根目錄的config目錄。
項目根目錄。
項目classpath下的config目錄。
項目classpath根目錄。
如對以上描述有疑問,可參看圖2-6。
圖2-6 配置文件讀取順序
圖2-6中的數字為文件的讀取順序,本小節使用的boot-config-file項目依賴了spring-boot-starter-web項目,為pom.xml加入以下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.4.RELEASE</version>
</dependency>
3.2.2 指定配置文件位置
如果想自己指定配置文件,可以在Spring容器的啟動命令中加入參數,例子如代碼清單2-6所示。
代碼清單2-6:codes\02\boot-config-file\src\main\java\org\crazyit\boot\TestDefaultFile.java
package org.crazyit.boot;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class TestDefaultFile {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(
TestDefaultFile.class)
.properties(
"spring.config.location=classpath:/test-folder/my-config.properties")
.run(args);
// 輸出變量
System.out.println(context.getEnvironment().getProperty("jdbc.user"));
}
TestDefaultFile類,在使用SpringApplicationBuilder時,配置了spring.config.location屬性來設定需要讀取的配置文件。
3.2.3 yml文件
YAML語言使用一種方便的格式的來進行數據配置,通過配置分層、縮進,在很大程度上增強了配置文件的可讀性,使用YAML語言的配置文件以“.yml”作為後綴。代碼清單2-7為一份yml配置文件。
代碼清單2-7:codes\02\boot-config-file\src\main\resources\my-config.yml
jdbc:
user:
root
passwd:
123456
driver:
com.mysql.jdbc.Driver
在此,需要注意的是,每一行配置的縮進要使用空格,不要使用tab鍵進行縮進。代碼清單2-7對應的properties文件內容如下:
jdbc.user=root
jdbc.passwd=123456
jdbc.driver=com.mysql.jdbc.Driver
3.2.4 運行時指定profiles配置
如果在不同的環境下激活不同的配置,可以使用profiles,代碼清單2-8中配置了兩個profiles。
代碼清單2-8:codes\02\boot-config-file\src\main\resources\test-profiles.yml
spring:
profiles: mysql
jdbc:
driver:
com.mysql.jdbc.Driver
---
spring:
profiles: oracle
jdbc:
driver:
oracle.jdbc.driver.OracleDriver
定義了mysql與oracle兩個profiles,profiels間使用“---”進行分隔,在Spring容器啟動時,使用spring.profiles.active來指定激活哪個profiles,如代碼清單2-9所示。
代碼清單2-9:codes\02\boot-config-file\src\main\java\org\crazyit\boot\TestProfiles.java
package org.crazyit.boot;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class TestProfiles {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(
TestProfiles.class)
.properties(
"spring.config.location=classpath:/test-profiles.yml")
.properties("spring.profiles.active=oracle").run(args);
// 輸出變量
System.out.println(context.getEnvironment().getProperty("jdbc.driver"));
// 啟動第二個Spring容器,指定端口為8081
ConfigurableApplicationContext context2 = new SpringApplicationBuilder(
TestProfiles.class)
.properties(
"spring.config.location=classpath:/test-profiles.yml")
.properties("spring.profiles.active=mysql").properties("server.port=8081").run(args);
// 輸出變量
System.out.println(context2.getEnvironment().getProperty("jdbc.driver"));
}
}
對Spring Boot的配置文件有一定了解後,對後麵章節Spring Cloud的配置內容就不會陌生。
3.2.5 熱部署
每次修改Java後,都需要重新運行Main方法才能生效,這樣的會降低開發效果,我們可以使用Spring Boot提供的開發工具來實現熱部署,為項目加上以下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
當Java文件修改後,容器會重新加載本項目的Java類。
3.3 小結
本文主要講述了本書基礎環境的搭建,讀者主要掌握Maven的使用,本書的案例幾乎都是Maven項目。Spring Cloud項目以Spring Boot作為基礎進行構建,本書的大部分案例也是基於Spring Boot,本章對Spring Boot作了大致的講解,並且配合一個Hello World例子來演示Spring Boot的便捷,學習完本章後,讀者知道Spring Boot的大致功能,即可達到目標。
我的CSDN地址https://blog.csdn.net/chenjianandiyi
我的簡書地址https://www.jianshu.com/u/9b5d1921ce34
我的githubhttps://github.com/javanan
我的碼雲地址https://gitee.com/jamen/
最後更新:2017-11-03 09:33:59