前言
本篇文章主要介紹spring-boot兩種不同的pom.xml
的寫法來構(gòu)建一個簡單的基于SpringMVC的restful形式的微服務(wù)。
使用技術(shù)
spring-boot 1.5.2.RELEASE
springmvc
項目結(jié)構(gòu)
spring-boot的官方推薦了兩種pom.xml的寫法
(1) 利用parent的方式來構(gòu)建
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
通過這樣的方式表示,表示使用spring-boot提供的parent來統(tǒng)一管理具體依賴jar包的版本信息,這樣就可以不需要寫具體依賴項目的jar包版本了饭豹,統(tǒng)一使用spring-boot指定的版本
(2) 利用import的方式來構(gòu)建
<dependencyManagement>
<dependencies>
<dependency>
<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-dependencies
來管理來統(tǒng)一管理具體依賴jar包的版本信息净当。這樣就可以不需要寫具體依賴項目的jar包版本了衙伶,統(tǒng)一使用spring-boot指定的版本。
(3) 引入核心依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
引入了上面的依賴之后叨咖,再加上一個簡單的 Controller
就完成了服務(wù)端的搭建瘩例。這個依賴就是web服務(wù)的核心依賴(基于springmvc構(gòu)成的restful服務(wù)接口)
啟動項目
由于使用了spring-boot的插件
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
<configuration>
<classifier>exec</classifier>
</configuration>
</plugin>
所以會生成一個exec.jar,這個jar包里面包含了所有需要運行的依賴甸各,然后我們可以通過 java -jar import-pom-1.0.0-SNAPSHOT-exec.jar
來啟動服務(wù)垛贤,等待服務(wù)啟動以后,可以執(zhí)行 curl '127.0.0.1:8080/tutorials-01/hello'
來請求服務(wù)的接口趣倾。這樣就算利用spring-boot完成了第一個入門級別的微服務(wù)聘惦。
兩種方式的對比以及分析
對于上面兩種引入spring-boot的方式,傾向于使用第二種 import
的方式儒恋,因為 parent
模式有幾種弊端:
(1) 任何項目只能有一個 parent
善绎,如果使用了spring-boot的 parent
,這樣項目就沒辦法使用其他的 parent
诫尽,但是一般在一個大型項目中禀酱,使用本項目的 parent
是很常見的模式,所以spring-boot的 parent
并不適合牧嫉。
(2) 項目通常不僅僅使用spring-boot的開源組件剂跟,所以可能還會存在使用其他開源組件,也需要使用其他項目的默認jar包酣藻,這個通過 parent
的方式是無法完成的曹洽, 但是 import
的方式可以多個并存,同時通過多個 import
來一起管理項目所使用的jar包辽剧。
相關(guān)代碼的地址
https://github.com/dragontree101/spring-boot-tutorials/tree/master/spring-boot-tutorial-01