在 Spring Boot 中使用 @Grab 注解

x33g5p2x  于2022-09-30 转载在 Spring  
字(1.6k)|赞(0)|评价(0)|浏览(409)

@Grab 注解来自 Groovy 的 Grape 工具。简而言之,Grape 使 Groovy 脚本能够在运行时下载依赖库,而无需使用 Maven 或 Gradle 等构建工具。除了提供@Grab 背后的功能
注解时,Spring Boot CLI 也使用 Grape 来获取从代码推导出的依赖项。

使用 @Grab 就像表达依赖坐标一样简单。例如,假设您想将 H2 数据库和 thymeleaf 支持添加到您的项目中:

@Grab("h2")
@Grab("spring-boot-starter-thymeleaf")
class Grabs {}

使用这种方式, group 、 module 和 version 属性显式指定依赖关系。或者,您可以使用冒号分隔的形式表达相同的依赖关系,类似于在 Gradle 构建中表达依赖关系的方式
规格:

@Grab("com.h2database:h2:1.4.185")

在哪里放置@Grab?没有必要像我们所做的那样将 @Grab 注解放在单独的类中。如果我们将它放在使用该依赖项的 Controller 或 Repository 类中,它仍然可以工作。然而,为了组织起见,创建一个包含所有 @Grab 注解的空类定义很有用。这样可以轻松查看所有
在一个地方显式声明的库依赖项。

下面是一个示例基本 Groovy Web 应用程序,它使用 @Grab 注解构建
message.groovy

@Controller @Grab('spring-boot-starter-thymeleaf') class MessageController {     @RequestMapping("/msg") 	StringgetMsg(Modelmodel) {     	Stringmsg = "Hello World!";model.addAttribute("message",msg);         return "hello";     } }

模板/hello.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>

静态/index.html

<html>
     
    <head>
        <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
              
        <title>Spring Boot Example</title>
              
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         
    </head>
     
    <body>
             
        <p>
            Click to get <a href="/msg">Message</a> 
        </p>
         
    </body>
     
</html>

要运行该示例,请使用命令提示符从项目的根目录运行以下命令。

spring run *.groovy

现在访问 URL http://localhost:8080/

相关文章

微信公众号

最新文章

更多