Spring Boot CLI
Introduction
The Spring Boot Command Line Interface (CLI) is a powerful tool that simplifies Spring application development by allowing you to write, test, and run Spring Boot applications directly from the command line. It's designed to make development faster and more efficient, especially for prototyping and quick experimentation.
Think of Spring Boot CLI as a Swiss Army knife for Spring developers—it lets you run Spring Boot applications with minimal setup, write Groovy scripts instead of verbose Java code, and access various Spring Boot features without creating a complete project structure.
In this guide, you'll learn:
- How to install and set up Spring Boot CLI
- Writing and running applications using the CLI
- Advanced features and commands
- Real-world use cases for the CLI
Installation
Before you can use Spring Boot CLI, you need to install it. There are several ways to do this:
Using SDKMAN!
SDKMAN! provides a convenient way to install and manage multiple versions of Spring Boot CLI:
# Install SDKMAN! if you don't have it already
$ curl -s "https://get.sdkman.io" | bash
# Install Spring Boot CLI
$ sdk install springboot
# Verify installation
$ spring --version
Using Homebrew (macOS)
If you're using macOS and have Homebrew installed:
$ brew tap spring-io/tap
$ brew install spring-boot
Manual Installation
- Download the Spring Boot CLI distribution from the Spring official website
- Unzip the downloaded archive
- Add the
bin
directory to your PATH environment variable
# Example for Linux/Mac (add to .bashrc or .zshrc)
$ export PATH=/path/to/spring-boot-cli-x.x.x.RELEASE/bin:$PATH
After installation, verify that it's working:
$ spring --version
Spring CLI v3.2.0
Your First Spring Boot CLI Application
Let's create a simple web application using Spring Boot CLI. The power of the CLI lies in its ability to use Groovy scripts which are more concise than Java.
Create a file named hello.groovy
:
@RestController
class HelloController {
@RequestMapping("/")
String home() {
"Hello from Spring Boot CLI!"
}
}
Now, run this application using the CLI:
$ spring run hello.groovy
This will start a web server on port 8080. Visit http://localhost:8080
in your browser, and you'll see the message "Hello from Spring Boot CLI!"
What's happening behind the scenes? Spring Boot CLI:
- Recognizes that you're using Spring annotations
- Automatically adds required dependencies
- Compiles and runs the application
Notice how we didn't need to:
- Create a Maven or Gradle project
- Configure dependencies
- Write a main class
- Set up Spring Boot explicitly
Running Multiple Files
You can also run multiple Groovy files together. Let's create another file service.groovy
:
@Service
class GreetingService {
String getGreeting() {
return "Welcome to Spring Boot CLI tutorial!"
}
}
And modify hello.groovy
:
@RestController
class HelloController {
@Autowired
GreetingService greetingService
@RequestMapping("/")
String home() {
greetingService.greeting
}
}
Run both files together:
$ spring run hello.groovy service.groovy
Visit http://localhost:8080
again to see the updated message.
Common CLI Commands
Spring Boot CLI provides several commands to make development easier:
Running Applications
# Basic run
$ spring run app.groovy
# Run with specific profile
$ spring run app.groovy -- --spring.profiles.active=dev
# Run on a different port
$ spring run app.groovy -- --server.port=9000
# Debug mode
$ spring run --debug app.groovy
Testing Applications
You can also run tests using the CLI:
$ spring test test.groovy
Creating a Deployable JAR
Turn your Groovy scripts into a standalone JAR:
$ spring jar my-app.jar *.groovy
Initializing Projects
Creating a new project skeleton:
# Create a basic Maven project
$ spring init --build=maven my-project
# Create a Gradle project with Java 17
$ spring init --build=gradle --java-version=17 my-project
# Show available options
$ spring init --list
Dependency Management
Spring Boot CLI automatically adds dependencies based on the imports and annotations in your code. For example:
@RestController
@EnableScheduling
class ScheduledTasks {
@Scheduled(fixedRate = 5000)
@RequestMapping("/tasks")
String reportTasks() {
"Tasks are running: ${new Date()}"
}
}
When you run this script, Spring Boot CLI automatically adds:
- Spring Web for the
@RestController
- Spring Task for the
@EnableScheduling
and@Scheduled
Adding Custom Dependencies
You can explicitly add dependencies using the @Grab
annotation:
@Grab('org.springframework.boot:spring-boot-starter-data-jpa')
@Grab('com.h2database:h2')
@RestController
class JpaExample {
@Autowired
JdbcTemplate jdbcTemplate
@RequestMapping("/")
String home() {
jdbcTemplate.queryForObject('SELECT NOW()', String)
}
}
Real-World Examples
Building a REST API Prototype
Let's create a quick REST API for a book service:
@Grab('org.springframework.boot:spring-boot-starter-data-rest')
@RestController
class BookController {
// In-memory book repository
def books = [
[id: 1, title: "Spring in Action", author: "Craig Walls"],
[id: 2, title: "Cloud Native Java", author: "Josh Long"]
]
@GetMapping("/books")
def getAllBooks() {
books
}
@GetMapping("/books/{id}")
def getBook(@PathVariable int id) {
books.find { it.id == id }
}
@PostMapping("/books")
def addBook(@RequestBody Map book) {
book.id = books.size() + 1
books << book
book
}
}
Save this as books.groovy
and run it:
$ spring run books.groovy
You can now:
- GET all books:
curl http://localhost:8080/books
- GET a specific book:
curl http://localhost:8080/books/1
- POST a new book:
curl -X POST -H "Content-Type: application/json" -d '{"title":"Spring Boot CLI","author":"Spring Team"}' http://localhost:8080/books
Quick Database Application
Create a file database.groovy
for a quick database application:
@Grab('org.springframework.boot:spring-boot-starter-data-jpa')
@Grab('com.h2database:h2')
import javax.persistence.*
import org.springframework.data.jpa.repository.*
import org.springframework.data.repository.CrudRepository
@Entity
class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id
String name
String email
}
interface UserRepository extends CrudRepository<User, Long> {}
@RestController
class UserController {
@Autowired
UserRepository repository
@PostConstruct
void init() {
// Add some sample data
repository.save(new User(name: "John Doe", email: "[email protected]"))
repository.save(new User(name: "Jane Smith", email: "[email protected]"))
}
@GetMapping("/users")
Iterable<User> getAllUsers() {
repository.findAll()
}
@PostMapping("/users")
User addUser(@RequestBody User user) {
repository.save(user)
}
}
Run the application:
$ spring run database.groovy
The H2 in-memory database will be automatically configured, and JPA entities will be created.
Integration with Build Tools
While Spring Boot CLI is great for prototyping, you'll likely want to move to a full project structure when developing production applications. You can convert your CLI app to a Maven or Gradle project:
# Create a Maven project from your groovy files
$ spring init --build=maven --dependencies=web,data-jpa my-project
Then move your code from Groovy scripts to Java classes within the standard project structure.
Limitations of CLI
While Spring Boot CLI is powerful for quick development, it has some limitations:
- Not ideal for large applications with complex structures
- Less IDE support compared to standard Java projects
- May require conversion to standard project format for production deployment
- Limited debugging capabilities compared to full IDEs
Tips for Effective Use
- Use for prototyping: CLI is perfect for testing concepts quickly
- Create reusable scripts: Build a library of scripts for common tasks
- Test APIs: Quickly create mock APIs to test frontend applications
- Learning tool: Great way for beginners to learn Spring Boot without complex setup
- Development utilities: Create utility scripts that help with development workflows
Summary
Spring Boot CLI is a powerful tool for rapid Spring application development. It simplifies the development process by:
- Requiring minimal configuration
- Allowing concise Groovy scripts
- Providing automatic dependency resolution
- Offering convenient commands for common tasks
The CLI is particularly useful for:
- Prototyping and proof-of-concepts
- Learning Spring Boot
- Creating simple utility applications
- Testing ideas quickly
As your applications grow in complexity, you'll likely want to migrate to a standard project structure, but the CLI remains a valuable tool in any Spring developer's toolkit.
Additional Resources
Exercises
- Create a weather service that fetches data from a public API using
@Grab('org.springframework.boot:spring-boot-starter-webflux')
- Build a simple blog API with operations to create, read, update, and delete posts
- Create a scheduler application that prints messages at different intervals
- Develop a file uploader service that allows uploading and downloading files
- Try converting one of your CLI applications to a full Maven or Gradle project
Happy coding with Spring Boot CLI!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)