一、介紹:使用Spring Boot我們可以很容易的創建一個可獨立運行的Rest web服務,其中內嵌tomact,我們只需“run”就可以查看效果了。
Spring Boot利用Gradle或Maven構建引入第三方庫的方式,所以我么不需要去擔心我們改引入哪些庫,而且使用Spring Boot省去了很多繁瑣的配置。
接下來,我們將用Spring Boot實現和c# mvc一樣的Rest Web服務。
二、效果:經典的Hello World。
這將是我么最終的效果,毋須配置部署tomact,我們只需一“run”,Rest Web服務就完成了。
三、准備工作:
- 一個自己稱心的IDE,我選的是Eclipse Luna。可以到官網自己去下。
- JDK1.8或更高
- Gradle2.3+或Maven3.0+
這里我將采用Gradle的構建方式,也是我選Luna的原因,它里邊集成了Gradle的工程創建。
四、開始創建,我們打開Eclipse Luna;如果打不開,查看是否安裝了jdk及是否在環境變量中配置了JAVA_HOME.
至於配置jdk的方式,網上一大堆,百度或谷歌就能搜到。
首先打開Eclipse Luna,創建一個Gradle Project。
選擇New-Other-Gradle-Gradle Project。
在這里我起名為GradleTestOne。創建完畢后,大概是這個樣子的:
我們以上的工作僅僅是創建了一個Gradle Project,我們的目標是構建一個Spring的web程序啊,接下來,好戲登場。
五、在項目中加入spring的相關支持。
請看下邊的代碼:我們將一下代碼替換GradleTestOne中的build.gradle文件。
buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.1.RELEASE") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' apply plugin: 'spring-boot' jar { baseName = 'gs-rest-service' version = '0.1.0' } repositories { mavenCentral() } sourceCompatibility = 1.8 targetCompatibility = 1.8 dependencies { compile("org.springframework.boot:spring-boot-starter-web") testCompile("junit:junit") } task wrapper(type: Wrapper) { gradleVersion = '2.3' }
里邊都是什么意思,我們先不去管它。
六、利用Gradle自動加入spring 依賴的jar包。
我們在我們新建的項目上右擊找到Gradle 選擇 refresh All,打開Eclipse Luna的Console視圖,我們觀察發現,它正在下載相關的jar包,這里不要心急,需要等會,當我們
看到“successful”,輸出時,我們可以我們的操作了。我們先來驗證spring相關的jar是否加載了。
你構建成功了嗎!
七、加入代碼,
1、在src org.gradle包下,建立Greeting類。
package org.gradle; public class Greeting { private final long id; private final String content; public Greeting(long id, String content) { this.id = id; this.content = content; } public long getId() { return id; } public String getContent() { return content; } }
2、創建資源控制器。好戲登場。
package hello; import java.util.concurrent.atomic.AtomicLong; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class GreetingController { private static final String template = "Hello, %s!"; private final AtomicLong counter = new AtomicLong(); @RequestMapping("/greeting") public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) { return new Greeting(counter.incrementAndGet(), String.format(template, name)); } }
3、引導Spring Application啟動。
package hello; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
八、Gradle Build。
在項目中右擊找到Gradle選中Gradle Build 在Task參數中該選擇build.構建,待構建成功后。
在項目中找到我們創建的Application,點擊鼠標右鍵選擇“Run” -“Java application”接下來將是見證奇跡的時刻:
當你看到這樣的輸出時,你的應用構建成功了,仔細閱讀輸出:
Tomact已經啟動,端口是8080,如果端口被占,把端口占用的應用程序關掉就可以了。
九、瀏覽器看效果。
十、歡迎技術交流討論。參照資料:http://spring.io/guides/gs/rest-service/