本文介紹如何使用 Spring Boot CLI 快速創建一個 Web 應用,使用 Groovy 語言編寫一個簡單的 「Hello World」,使用 Gradle 構建並運行起來。

Groovy 是一種在 JVM 上運行的動態類型語言。 由於 Groovy 的語法非常接近 Java,因此 Java 開發人員很容易開始使用 Groovy。可以使用 Groovy 語言開發 Spring Boot 應用程序,而且使用 Groovy 可以大大提高開發效率。

Spring Boot 目前已經支持 Groovy 編程語言,你可以通過 Spring Initializer 在 http://start.spring.io 或者 IDE(STS、IDEA) 中創建基於 Groovy 語言開發的 Spring Boot 應用程序。

1. 介紹

內容簡介: 一個簡單的 Spring Boot Web 應用示例

語言框架: Groovy、Spring Boot、Spring MVC

難度級別: L1閱讀時間: 10 分鐘

2. 工具準備

  • Java SDK : 8.0+
  • Spring Boot CLI : 2.1.2
  • Gradle : 4.10.2
  • IntelliJ IDEA : 2018.3
  • Curl / HTTPie

3. 實現步驟

3.1. 創建項目

首先,通過 Spring CLI 創建一個空白工程: Hello World 應用。使用 Spring CLI 創建一個新工程

$ spring init --name hello-world --artifactId spring-boot-hello-world-groovy
--groupId org.springdev.guides --package-name org.springdev.guides.helloworld
--language groovy --build gradle
--dependencies web --extract

3.2. 打開項目

打開 IDEA,點擊菜單 File Open,選擇項目所在目錄 spring-boot-hello-world-groovy 下的 build.gradle,打開。

3.3. 項目結構

此時創建的新工程的目錄結構如下:

├── build.gradle
├── gradle
│ └── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
├── main
│ ├── groovy
│ │ └── org
│ │ └── springdev
│ │ └── guides
│ │ └── helloworld
│ │ └── HelloWorldApplication.groovy
│ └── resources
│ ├── application.properties
│ ├── static
│ └── templates
└── test
└── groovy
└── org
└── springdev
└── guides
└── helloworld
└── HelloWorldApplicationTests.groovy

在工程根目錄打開 build.gradle,其內容如下:

buildscript {
ext {
springBootVersion = 2.1.2.RELEASE // <1>
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}

apply plugin: groovy // <2>
apply plugin: org.springframework.boot
apply plugin: io.spring.dependency-management

group = org.springdev.guides
version = 0.0.1-SNAPSHOT
sourceCompatibility = 1.8

repositories {
mavenCentral()
}

dependencies { // <3>
implementation org.springframework.boot:spring-boot-starter-web
implementation org.codehaus.groovy:groovy
testImplementation org.springframework.boot:spring-boot-starter-test
}

代碼說明如下:

  1. Spring Boot 版本使用 2.1.2.RELEASE
  2. 使用 Gradle 插件: groovyorg.springframework.boot
  3. 項目的起步依賴:webtest 以及 groovy SDK;

打開應用的主程序文件: HelloWorldApplication.groovy,可以看到這個文件代碼非常簡單。

package org.springdev.guides.helloworld

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

@SpringBootApplication
class HelloWorldApplication {

static void main(String[] args) {
SpringApplication.run(HelloWorldApplication, args)
}

}

3.4. 編寫代碼

3.4.1. 編寫 Controller

接下來我們開始編寫 Controller。在 src/main/groovy/org/springdev/guides/helloworld/目錄中新增一個 HelloController.groovy,內容如下:src/main/groovy/org/springdev/guides/helloworld/HelloController.groovy

package org.springdev.guides.helloworld

import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController // <1>
class HelloController {

@GetMapping("/hello") // <2>
String hello() {
"Hello, World!" // <3>
}

}

代碼說明如下:

  1. Spring MVC 提供了@RestController註解,這是一個 REST 介面類;
  2. 設置 Get 請求,請求地址為/hello
  3. 響應成功,並返回內容為:Hello, World!

3.5. 單元測試

3.5.1. 編寫測試用例

src/test/groovy/org/springdev/guides/helloworld/HelloControllerTests.groovy

package org.springdev.guides.helloworld

// import ...

@RunWith(SpringRunner.class)
@SpringBootTest // <1>
@AutoConfigureMockMvc
class HelloControllerTests {
@Autowired
MockMvc mockMvc

@Test
void hello() throws Exception {
this.mockMvc.perform(get("/hello")) // <2>
.andDo(print())
.andExpect(status().isOk()) // <3>
.andExpect(content().string("Hello, World!")) // <4>
}

}

代碼說明如下:

  1. Spring Boot 提供了@SpringBootTest註解,該註解簡化了 Spring Boot 應用的測試,提供了對應 spring-test 中@ContextConfiguration的功能,用於創建ApplicationContext
  2. 自動配置MockMvc實例,用於模擬執行請求/hello
  3. 驗證響應狀態碼為200,表示成功;
  4. 驗證返回內容為:Hello, World!

3.5.2. 執行單元測試

$ gradle test
$ open build/reports/tests/test/index.html

報告顯示測試執行成功,說明功能實現正確。

4. 構建運行

你可以先打包成可執行的 JAR

或者,直接執行命令gradle bootRun:

$ gradle bootRun

> Task :bootRun

. ____ _ __ _ _
/\ / ____ __ _ _(_)_ __ __ _
( ( )\___ | _ | _| | _ / _` |
\/ ___)| |_)| | | | | || (_| | ) ) ) )
|____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.2.RELEASE)

2019-01-14 20:21:37.228 INFO 72960 --- [ main] o.s.g.helloworld.HelloWorldApplication : Starting HelloWorldApplication on Michaels-MBP.lan with PID 72960 (/Users/rain/Development/springdev/guides/spring/spring-boot-hello-world-groovy/complete/build/classes/groovy/main started by rain in /Users/rain/Development/springdev/guides/spring/spring-boot-hello-world-groovy/complete)
2019-01-14 20:21:37.231 INFO 72960 --- [ main] o.s.g.helloworld.HelloWorldApplication : No active profile set, falling back to default profiles: default
2019-01-14 20:21:38.465 INFO 72960 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-01-14 20:21:38.509 INFO 72960 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-01-14 20:21:38.509 INFO 72960 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.14]
2019-01-14 20:21:38.521 INFO 72960 --- [ main] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/rain/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
2019-01-14 20:21:38.621 INFO 72960 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-01-14 20:21:38.622 INFO 72960 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1330 ms
2019-01-14 20:21:38.901 INFO 72960 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService applicationTaskExecutor
2019-01-14 20:21:39.126 INFO 72960 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path
2019-01-14 20:21:39.129 INFO 72960 --- [ main] o.s.g.helloworld.HelloWorldApplication : Started HelloWorldApplication in 2.251 seconds (JVM running for 3.054)

5. 測試驗證

打開瀏覽器,訪問地址: localhost:8080/hello 會看到下圖所示的界面:

或者,通過 curl 來驗證:

$ curl -v http://localhost:8080/hello
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /hello HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 200
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 13
< Date: Mon, 14 Jan 2019 12:21:50 GMT
<
* Connection #0 to host localhost left intact
Hello, World!

或者,通過 HTTPie 驗證:

$ http :8080/hello
HTTP/1.1 200
Content-Length: 13
Content-Type: text/plain;charset=UTF-8
Date: Mon, 14 Jan 2019 12:21:55 GMT

Hello, World!

6. 小結

恭喜,你已經學會了使用 Spring Boot CLI 創建一個 Web 應用,用 Groovy 語言編寫一個 Hello World 程序,並且使用 Gradle 構建運行成功。

7. 相關文章

  • Spring Boot: 編寫一個 Hello World 應用(Java & Maven)
  • Spring Boot: 編寫一個 Hello World 應用(Kotlin & Gradle)

8. 參考資料

  • Groovy Documentation
  • Building Groovy Libraries

推薦閱讀:

相关文章