Using @Grab Annotation in Spring Boot

The @Grab annotation comes from Groovy’s Grape facility. In a nutshell, Grape enables Groovy scripts to download dependency libraries at runtime without using a build tool like Maven or Gradle. In addition to providing the functionality behind the @Grab
annotation, Grape is also used by the Spring Boot CLI to fetch dependencies deduced from the code.

Using @Grab is as simple as expressing the dependency coordinates. For example, suppose you want to add the H2 database and thymeleaf support to your project:

class Grabs {}

Used this way, the group , module , and version attributes explicitly specify the dependency. Alternatively, you can express the same dependency using a colon-separated form similar to how dependencies can be expressed in a Gradle build


Where to place @Grab? It’s not strictly necessary to put the @Grab annotations in a separate class as we did. It would still work if we put it in the Controller or Repository class which uses that dependency. For organization’s sake, however, it’s useful to create an otherwise empty class definition that has all of the @Grab annotations. This makes it easy to view all
of the explicitly declared library dependencies in one place.

Here is for example a sample basic Groovy Web application which is structured using @Grab annotations

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


<!DOCTYPE HTML> <html xmlns:th=""> <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> 


        <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">
            Click to get <a href="/msg">Message</a> 

To run the example, run the following command from the root directory of the project using command prompt.

spring run *.groovy 

Now access the URL http://localhost:8080/