创建一个基于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测试应用程序