創建一個基於Thymeleaf
的示例專案,以演示Spring CLI的功能。 按照下麵提到的步驟創建一個示例專案 -
第1步
在D:/worksp/springboot-cli/
目錄下,創建一個名稱為TestApplication
的檔夾,並在這個檔中創建兩個子目錄:static
和templates
。
第2步
在TestApplication
檔夾中創建message.groovy
檔,在templates
檔夾中創建message.html
,在static
檔夾中創建index.html
,如下所述。
第3步
編譯並運行應用程式以驗證實現的邏輯的結果。
檔:TestApplication/message.groovy -
@Controller
@Grab('spring-boot-starter-thymeleaf')
class MessageController {
@RequestMapping("/message")
String getMessage(Model model) {
String message = "Welcome to xuhuhu.com!";
model.addAttribute("message", message);
return "message";
}
}
檔:TestApplication/templates/message.html -
<!DOCTYPE HTML>
<html xmlns:th = "http://www.thymeleaf.org">
<head>
<title>Spring Boot CLI Example</title>
<meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8" />
</head>
<body>
<p th:text = "'Message: ' + ${message}" />
</body>
</html>
檔: TestApplication/static/index.html -
<!DOCTYPE HTML>
<html>
<head>
<title>Spring Boot CLI Example</title>
<meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8" />
</head>
<body>
<p>Go to <a href = "/msg">Message</a></p>
</body>
</html>
運行該應用程式
輸入以下命令 -
D:/worksp/springboot-cli/TestApplication/> spring run *.groovy
現在,Spring Boot CLI將開始運行,下載所需的依賴項,運行嵌入式tomcat,部署應用程式並啟動它。可以在控制臺上看到以下輸出 -
Resolving dependencies.............................
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _> | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.5.RELEASE)
...
2018-11-08 16:27:28.300 INFO 8360 --- [ runner-0] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-11-08 16:27:28.305 INFO 8360 --- [ runner-0] o.s.boot.SpringApplication
在流覽器中流覽應用程式
基於Spring應用現已準備就緒,打開網址為“http://localhost:8080/”
,將看到以下輸出 -
Go to Message
單擊消息鏈接,將看到以下輸出 -
Message: Welcome to xuhuhu.com!
理解關鍵執行過程
以下操作由Spring CLI執行 -
- 所有依賴項JAR僅在第一次使用時下載。
- Spring CLI根據代碼中使用的類和注釋自動檢測要下載的依賴項JAR。
- 最後,它編譯代碼,在嵌入式tomcat上部署
war
,在默認端口8080上啟動嵌入式tomcat伺服器。
上一篇:
Spring Boot CLI默認語句
下一篇:
Spring Boot CLI測試應用程式