Spring Boot CLI (Command Line Interface)
The Spring Boot CLI tool is used to quickly develop the Spring Applications from the command line. It allows us to run the Groovy Scripts, which is useful for writing the Java-like syntax without so much boilerplate code. Using Spring Boot CLI (Command Line Interface), we can easily bootstrap a new Spring project. Even we can write our command for it.
The Spring Boot CLI tool is not a necessary tool to create a Spring Boot Application. It is surely the quickest way to bootstrap a Spring Boot Application and get it on the ground.
There are several ways to Bootstrap a Spring Boot Project, such as Using STS (Spring Tool Suite) IDE, Eclipse IDE, Spring Initializr, etc. But the command-line interface is slightly fast and useful for the people who love to work on the command line.
In this section of learning Spring Boot series, we will discuss the following topics about Spring Boot CLI:
- What is Spring Boot CLI
- How to install Spring Boot CLI
- Installation Instructions & Requirements for Spring Boot CLI
- Spring Boot CLI for Linux
- Spring Boot CLI for Windows
- Spring Boot CLI for OSX(Homebrew)
- MacPorts Installation
- Windows Scoop Installation
- Spring Boot CLI Commands
- Essential Groovy Scripts
- Conclusion
What is Spring Boot CLI (Command Line Interface)
Spring Boot CLI is a tool to develop, run, and test the Spring Boot applications from the command prompt (Terminal). When we create a new Spring Boot application from the terminal, it internally uses the Spring Boot Starter and AutoConfiguration components to export all the dependencies and execute the application.
It internally holds the Groovy and Grape (JAR Dependency Management) to add the Spring Boot default configurations and import all the dependencies automatically.
How to Install Spring Boot CLI
Spring Boot CLI can be installed easily using the different installation packages. Here, we will discuss the guide for installing the Spring Boot CLI for all the major operating systems such as Windows, Linux, and macOS.
Before understanding the installation steps, let’s discuss a few criteria for installing it:
Every package contains an Install.txt file that holds the installation instruction and requirements:
The following are some installation instructions and requirements to install the Spring Boot CLI:
Installation Instructions and Requirements for Spring Boot
Prerequisites:
- Java JDK v1.8 or above
- Groovy v${groovy.version} ( it is packaged as part of this distribution, and therefore does not need to be installed)
The CLI will use whatever JDK it finds on your path. To check the JDK, you should run the below command:
java -version
Alternatively, we can set the JAVA_HOME
environment variable to point to a suitable JDK.
Environment Variables:
No specific environment variables are required to run the CLI; however, you may want to
set SPRING_HOME
to point to a specific installation. You should also add SPRING_HOME/bin
to your PATH environment variable.
Shell Completion:
Shell auto-completion scripts are provided for BASH and ZSH. Add symlinks to the appropriate
location for your environment. For example, something like:
ln -s ./shell-completion/bash/spring /etc/bash_completion.d/spring
ln -s ./shell-completion/zsh/_spring /usr/local/share/zsh/site-functions/_spring
Checking Your Installation
To verify the CLI installation, you can run the following command:
spring --version
Now, understand how to install it on different operating systems:
Spring Boot CLI for Linux
Follow the below steps to develop a Spring Boot application using CLI on a Linux system:
Step1:
To install the Spring Boot CLI on Linux, follow this link and navigate to manual installation.
Select any of the above-given links. It will download a compressed file.
Step2:
Now, extract this file to a specific directory:
Step3:
Navigate to the extracted directory and search for the spring-2.4.1 folder. Under this folder, you will find a bin folder.
Step4:
open the terminal inside the bin folder (by right-clicking or using the cd command).
Step5:
Create a Groovy script; Spring Boot uses a Groovy script, so for manual bootstrapping, we have to create it. To create a groovy script, create any file with a .groovy extension. For example, we are creating SbCliDemo.groovy file by executing the below command:
nano SbCliDemo.groovy
Enter the below code in the Groovy file:
SbCliDemo.groovy:
@RestController
class SbCliDemo{
@RequestMapping("/cli-demo")
String index()
{
"Spring Boot Example Using Spring Boot CLI"
}
}
The above code is written to create a controller class in the Spring Boot project. Save this file.
Step6:
Now, we can bootstrap our first project using the CLI:
To execute this project, run the below command:
./spring run SbCliDemo.groovy
Before executing the project, make sure Java is properly installed on your machine and the environment variable for Java (JAVA_HOME) is properly set. To verify the Java Version and environment variable, execute the below commands:
java -version
echo $JAVA_HOME
It will display the output as follows:
If it is not set properly, see how to install Java and set its environment variable on Linux.
Step7:
After executing the spring run
command, it will start downloading the dependencies and run our first spring application using the CLI.
It will produce the output as follows:
Resolving dependencies..............................................
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.1)
2021-01-08 19:25:27.680 INFO 14258 --- [ runner-0] o.s.boot.SpringApplication : Starting application using Java 1.8.0_275 on alien-Inspiron-3542 with PID 14258 (started by alien in /home/alien/Documents/spring-2.4.1/bin)
2021-01-08 19:25:27.688 INFO 14258 --- [ runner-0] o.s.boot.SpringApplication : No active profile set, falling back to default profiles: default
2021-01-08 19:25:30.236 INFO 14258 --- [ runner-0] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-01-08 19:25:30.277 INFO 14258 --- [ runner-0] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-01-08 19:25:30.278 INFO 14258 --- [ runner-0] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.41]
2021-01-08 19:25:30.324 INFO 14258 --- [ runner-0] org.apache.catalina.loader.WebappLoader : Unknown class loader [org.springframework.boot.cli.compiler.ExtendedGroovyClassLoader$DefaultScopeParentClassLoader@63296e09] of class [class org.springframework.boot.cli.compiler.ExtendedGroovyClassLoader$DefaultScopeParentClassLoader]
2021-01-08 19:25:30.371 INFO 14258 --- [ runner-0] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-01-08 19:25:30.371 INFO 14258 --- [ runner-0] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1998 ms
2021-01-08 19:25:30.826 INFO 14258 --- [ runner-0] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-01-08 19:25:31.788 INFO 14258 --- [ runner-0] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-01-08 19:25:31.811 INFO 14258 --- [ runner-0] o.s.boot.SpringApplication : Started application in 5.435 seconds (JVM running for 73.559)
From the above output, we can see our application is started in 5.435 seconds.
Now, we can invoke this project on any web browser using the port number and mapping URL.
Step8:
To invoke the project on the web browser, type the below address on any of the browser’s address bar:
http://localhost:8080/cli-demo
It will display our message:
Spring Boot CLI for Windows
The steps for using the CLI in windows are the same as in Linux:
Follow the below steps to use the CLI on Windows:
Download the CLI setup from this link.
- Extract the downloaded compressed file to a specific directory.
- Navigate to bin folder under spring-2.4.1 folder.
- Now, open the terminal here or change the directory to this folder in your terminal.
- Create below Groovy script (above step 5)
SbCliDemo.groovy:
@RestController
class SbCliDemo{
@RequestMapping("/cli-demo")
String index()
{
"Spring Boot Example Using Spring Boot CLI"
}
}
5. run the project using the below command:
./spring run SbCliDemo.groovy
Spring Boot CLI for OSX (Homebrew)
To install the Spring Boot CLI on macOS with Homebrew, execute the following commands:
$ brew tap pivotal/tap
$ brew install springboot
It will install the Spring Boot CLI to /usr/local/bin directory.
Note: If the formula is not available, your installation of brew might be out-of-date. In that case, you need to update the brew by executing the below command:
$ brew update
,and try again.
It will install the Spring Boot CLI to /usr/local/bin directory.
Note: If the formula is not available, your installation of brew might be out-of-date. In that case, you need to update the brew by executing the below command:
$ brew update
and try again.
MacPorts Installation
To install the Spring Boot CLI on Mac using MacPorts, execute the below command:
$ sudo port install spring-boot-cli
Windows Scoop Installation
To install Spring Boot CLI on Windows using the Scoop, execute the following commands:
> scoop bucket add extras
> scoop install springboot
It will install spring to ~/scoop/apps/springboot/current/bin directory.
Note: If the app manifest is not visible, your installation of scoop might be out-of-date. In that case, update scoop by executing the below command:
scoop update
, and try again.
Spring Boot CLI Commands
The Spring Boot CLI is a command-line tool that provides a command-line interface for developing and testing the Spring Boot applications. It allows us to run Groovy Scripts that means we will have the Java-like interface without writing the boilerplate code. We can bootstrap a new project and write our command for it. Let’s discuss some useful commands for Spring Boot CLI:
The run Command
The run command is used to run the Java or Groovy Scripts of Spring Boot applications.
The syntax for the run command is as follows:
spring run [options] <files> [--] [args]
Options:
–autoconfigure [Boolean]: It is used to add the auto-configuration compiler transformation.
–classpath, -cp: It is used to adds the classpath entries, and it’s useful in case we have third-party libraries.
— no-guess-dependencies: It is used if we do not want to guess the dependencies. It is useful when you already use the @Grab annotation in your application.
–no-guess-imports: It is used if we do not want to guess the imports.
-q, –quiet: It is used to quiet logging. In a nutshell, it won’t print anything to the console.
-v, –verbose: It is used to display the output verbosely means it will log everything. It is useful for debugging.
–watch: It is used to set a watch to the file(s) for changes. It is useful when you don’t want to stop and run the app again.
To run a Groovy application, execute the command as follows:
$ spring run SbCliDemo.groovy
By executing the above command will run a script (web application) named SbCliDemo.groovy ( you may use your script). It will listen to port 8080 by default, but we can override the port number by executing the below command:
$ spring run app.groovy -- --server.port=8888
Now, it will listen to port 8888.
To run a Java application, execute the command as follows:
$ spring run SbCliDemo.java
The test Command
The test command is used to run a Spring Groovy script and Java tests. The syntax for the test command is as follows:
spring test [options] files [--] [args]
Options:
–autoconfigure [Boolean]: It is used to add the auto-configuration compiler transformation (default is true).
–classpath, -cp: It is used toadd the classpath entries, which is useful when you have third-party libraries.
–no-guess-dependencies: It is used if we do not want to guess the dependencies.
–no-guess-imports: It is used if we do not want to guess the imports.
The grab Command
The grab command is used to download all the Spring Groovy scripts and Java dependencies to the ./repository directory. The syntax for the grab command is as follows:
spring grab [options] files [--] [args]
Options:
–autoconfigure [Boolean]: It is used to add the auto-configuration compiler transformation (default is true).
–classpath, -cp: It is used to add the classpath entries, which is useful when you have third-party libraries.
–no-guess-dependencies: It is used if we do not want to guess the dependencies.
–no-guess-imports: It is used if we do not want to guess the imports.
The jar Command
It is used to create a self-contained executable JAR file from a Groovy script or Java. The syntax for the jar command is as follows:
spring jar [options] <jar-name> <files>
Options:
–autoconfigure [Boolean]: It is used to add the auto-configuration compiler transformation (default is true).
–classpath, -cp: It is used to add the classpath entries, which is useful when you have third-party libraries.
–exclude: It is used to specify a pattern to find the files and exclude them from the final JAR file.
–include: It is used to specify a pattern to find the files and include them in the final JAR file.
–no-guess-dependencies: It is used if we do not want to guess the dependencies.
–no-guess-imports: It is used if we do not want to guess the imports.
The war Command
The war command is much similar to the previous command. It is used to create a self-contained executable WAR file from a Groovy or Java. The syntax for war command is as follows:
spring war [options] <war-name> <files>
The install Command
It is much similar to the grab command; the only difference is that we have to specify the library that we want to install (in a coordinate format groupId:artifactId:version ; the same as the @Grab annotation). It will download it and add the dependencies in a lib directory. The syntax for the install command is as follows:
spring install [options] <coordinates>
For example:
spring install org.spockframework:spock-core:1.0-groovy-2.4
It will download the Spock library and its dependencies in the lib directory.
The uninstall command
The uninstall command is used to uninstall the dependencies from the lib directory. The syntax for uninstalling command is as follows:
spring uninstall [options] <coordinates>
We can test this command by executing the following command:
spring uninstall org.spockframework:spock-core:1.0-groovy-2.4
The above command will remove all the Spock dependencies from the lib directory
The init command
It will help you initialize a new project by using the Spring Initializr. There is no need for an IDE, it will help you get everything ready to start developing Spring Boot applications. The syntax for the init command is as follows:
spring init [options] [location]
To create a default project, execute the below command:
$ spring init
The above command will generate a demo.zip file. We can unzip it (a Maven project structure) and import it into our IDE.
The shell Command
It is one of the helpful commands of the Spring Shell; it wraps commands with the necessary spring prefix.
To start the embedded shell, we will execute the below command:
spring shell
From this point, we can directly type our desired commands without typing the spring keyword (since we’re now in the spring shell). For example, to execute the run command, we can directly type the below command:
run SbCliDemo.groovy
The help Command
The help command is used to display the help options. We can execute it as follows:
spring help
Essential Groovy Scripts
The Spring Boot CLI packages the Groovy and Spring to quickly script powerful, performant micro-services in single-file Groovy deployments.
It supports for multiply-scripted applications usually requires additional build tools like Maven or Gradle.
Let’s discuss some essential Groovy scripts:
@Grab
The @Grab
annotation and Groovy’s Java-esque import clauses are used to easy dependency management and injection.
Most annotations such as abstract, simplify, and automatically include the necessary import statements. Thus we will get more time to implement the logic of the services.
The @Grab annotation is used as follows:
package org.demo
@Grab("spring-boot-starter-actuator")
@RestController
class RestControllerDemo{
//...
}
The Spring Boot started actuator comes pre-configured for allowing the succinct script deployment. There is no need for customized applications, environmental properties, XML, or other project configuration. Though, we can specify these components if necessary.
@Controller, @RestController, and @EnableWebMvc
To accelerate the deployment of the Spring Boot applications, we can alternatively utilize the CLI’s grab hints. They will automatically deduce the dependencies to be imported.
For example, the @Controller and @Service annotations are used to quickly scaffold a standard MVC controller and service. Consider the below code:
@RestController
class Demo {
@Autowired
private MyService myService;
@GetMapping("/")
public String helloWorld() {
return myService.sayWorld();
}
}
@Service
class MyService {
public String sayWorld() {
return "World!";
}
}
SB CLI facilitates with all default configuration for Spring Boot. So, our Groovy apps will automatically access static resources respective default locations.
@EnableWebSecurity
The @EnableWebSecurity annotation is used to add Security options to our Spring Boot project, which later will be automatically downloaded by Spring Boot CLI.
@Test
The @Grab(‘junit’) or @Test annotations are used to set up a simple JUnit test:
package JS.test
@Grab('junit')
class Test {
//...
}
The above code will allow us to execute JUnit tests easily.
DataSource and JdbcTemplate
We can specify persistent data options including DataSource or JdbcTemplate without explicitly using the @Grab annotation. Consider the below code:
package JS.data
@Grab('h2')
@Configuration
@EnableWebMvc
@ComponentScan('JS.data')
class DataConfig {
@Bean
DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2).build();
}
}
From the above code, we have grabbed the H2 embedded database and set it as the DataSource using Spring bean configuration conventions.
Conclusion
I hope this tutorial helps you to install and use the Spring Boot CLI for your required operating system. For more detail, refer to the Spring’s getting started guide.