Introduction to Spring Boot CLI

1. Introduction

Spring Boot CLI is a command-line abstraction that allows us to easily run Spring micro-services expressed as Groovy scripts. It also provides simplified and enhanced dependency management for those services.

This short article takes a quick look at how to configure Spring Boot CLI and execute simple terminal commands to run pre-configured micro-services.

We’ll use Spring Boot CLI 2.0.0.RELEASE for this article. The newest version of Spring Boot CLI can be found over at Maven Central.

2. Setting Up Spring Boot CLI

One of the easiest ways to set up Spring Boot CLI is to use SDKMAN. Setup and installation instructions for SDKMAN can be found here.

After installing SDKMAN, run the following command to automatically install and configure Spring Boot CLI:

$ sdk install springboot

To verify the install, run the command:

$ spring --version

We can also install Spring Boot CLI by compiling from source, and Mac users can use pre-built packages from Homebrew or MacPorts. See the official docs for all installation options.

3. Common Terminal Commands

Spring Boot CLI provides several useful commands and features out-of-the-box. One of the most helpful features is Spring Shell, which wraps commands with the necessary spring prefix.

To start the embedded shell, we run:

spring shell

From here, we can directly enter desired commands without pre-pending the spring keyword (since we’re now in spring shell).

For example, we can display the current version of the running CLI by typing:

version

One of the most important commands is telling Spring Boot CLI to run a Groovy script:

run [SCRIPT_NAME].groovy

Spring Boot CLI will either automatically infer the dependencies or will do so given the correctly supplied annotations. After this, it will launch an embedded web container and app.

Let’s take a closer look at how to use Groovy script with Spring Boot CLI!

4. Essential Groovy Scripts

Groovy and Spring come together with Spring Boot CLI to allow powerful, performant micro-services to be quickly scripted in single-file Groovy deployments.

Support for multiply-scripted applications usually requires additional build tools like Maven or Gradle.

Below we’ll cover some of the most common use-cases for Spring Boot CLI, reserving more complex setups for other articles.

For a list of all Spring-supported Groovy annotations, please check out the official docs.

4.1. @Grab

The @Grab annotation and Groovy’s Java-esque import clauses allow for easy dependency management and injection.

In fact, most annotations abstract, simplify, and automatically include the necessary import statements. This allows us to spend more time thinking about architecture and the underlying logic of the services we want to deploy.

Let’s take a look at how to use the @Grab annotation:

package org.test

@Grab("spring-boot-starter-actuator")

@RestController
class ExampleRestController{
  //...
}

As we can see, spring-boot-starter-actuator comes pre-configured allowing for succinct script deployment without requiring a customized application or environmental properties, XML, or other programmatic configuration, though each of those things can be specified when necessary.

The full list of @Grab arguments — each specifying a library to download and import — is available here.

4.2. @Controller, @RestController, and @EnableWebMvc

To further expedite deployment, we can alternatively utilize Spring Boot CLI’s provided “grab hints” to automatically infer correct dependencies to import.

We’ll go over some of the most common use cases below.

For example, we can use the familiar @Controller and @Service annotations to quickly scaffold a standard MVC controller and service:

@RestController
class Example {
 
    @Autowired
    private MyService myService;

    @GetMapping("/")
    public String helloWorld() {
        return myService.sayWorld();
    }
}

@Service
class MyService {
    public String sayWorld() {
        return "World!";
    }
}

Spring Boot CLI supports all default configuration for Spring Boot. So, we can our Groovy apps will automatically access static resources from their usual default locations.

4.3. @EnableWebSecurity

To add Spring Boot Security options to our app, we can use the @EnableWebSecurity annotation, which will then be automatically downloaded by Spring Boot CLI.

Below, we’ll abstract part of this process using the spring-boot-starter-security dependency, which leverages the @EnableWebSecurity annotation under the hood:

package vietmx.security

@Grab("spring-boot-starter-security")

@RestController
class SampleController {

    @RequestMapping("/")
    public def example() {
        [message: "Hello World!"]
    }
}

For more details on how to protect resources and handle security, please check out the official documentation.

4.4. @Test

To set up a simple JUnit test, we can add the @Grab(‘junit’) or @Test annotations:

package vietmx.test

@Grab('junit')
class Test {
    //...
}

This will allow us to execute JUnit tests easily.

4.5. DataSource and JdbcTemplate

Persistent data options can be specified including DataSource or JdbcTemplate without explicitly using the @Grab annotation:

package vietmx.data

@Grab('h2')
@Configuration
@EnableWebMvc
@ComponentScan('vietmx.data')
class DataConfig {

    @Bean
    DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
          .setType(EmbeddedDatabaseType.H2).build();
    }

}

By simply using familiar Spring bean configuration conventions, we’ve grabbed the H2 embedded database and set it as the DataSource.

5. Custom Configuration

There are two primary ways to configure a Spring Boot micro-service using Spring Boot CLI:

  1. we can add argument parameters to our terminal commands
  2. we can use a customized YAML file to provide an application configuration

Spring Boot will automatically search the /config directory for application.yml or application.properties

├── app
    ├── app.groovy
    ├── config
        ├── application.yml
    ...

We can also set up:

├── app
    ├── example.groovy
    ├── example.yml
    ...

A full list of application properties can be found here at Spring.

6. Conclusion

This concludes our quick walk-through of Spring Boot CLI! For more details, check out the official docs.

And as usual, the source code for this article can be found over on GitHub.

Related posts:

Java Program to implement Dynamic Array
Java Program to Find Nearest Neighbor for Static Data Set
Java Program to Perform Inorder Non-Recursive Traversal of a Given Binary Tree
Spring Boot - Enabling HTTPS
Java Program to Implement ConcurrentHashMap API
Spring Cloud AWS – S3
Java Program to Generate Random Numbers Using Multiply with Carry Method
Lập trình đa luồng trong Java (Java Multi-threading)
Spring Security 5 for Reactive Applications
Guide to WeakHashMap in Java
How to Read a Large File Efficiently with Java
Java Program to Generate a Sequence of N Characters for a Given Specific Case
Java Program to Give an Implementation of the Traditional Chinese Postman Problem
Java Program to Generate All Possible Combinations of a Given List of Numbers
Spring Cloud – Adding Angular
Anonymous Classes in Java
Request Method Not Supported (405) in Spring
Logging in Spring Boot
Lập trình mạng với java
Spring Boot - Actuator
Java Program to Perform String Matching Using String Library
Serverless Functions with Spring Cloud Function
Java Program to Represent Graph Using Adjacency Matrix
Java Program to Implement Euclid GCD Algorithm
Java Program to Check whether Graph is a Bipartite using DFS
Upload and Display Excel Files with Spring MVC
Performance Difference Between save() and saveAll() in Spring Data
Guide to Character Encoding
Lớp Properties trong java
Java Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach
Phương thức forEach() trong java 8
Hướng dẫn Java Design Pattern – Proxy