Setting Up Your First Spring Boot Project – A Step-by-Step Guide
Spring Boot is an open-source framework built on top of the Spring Framework, designed to simplify the development of Java-based enterprise applications. With Spring Boot, you can quickly create stand-alone, production-grade Spring applications with minimal configuration. If you’re new to Spring Boot, this step-by-step guide will walk you through setting up your first Spring Boot project from scratch.
In this guide, we will cover everything you need to get started, including project setup, essential dependencies, and a basic application structure. By the end of this guide, you should have a fully functional Spring Boot application ready for further development.
Introduction to Spring Boot
Spring Boot is a framework that takes the complexity out of Spring-based applications by auto-configuring them based on the dependencies and annotations used. It removes the need for boilerplate code and allows developers to focus on building the application rather than configuring it. Key features of Spring Boot include:
- Embedded server: Spring Boot provides an embedded server (such as Tomcat or Jetty) out of the box, eliminating the need for deployment to an external server.
- Auto-configuration: Spring Boot automatically configures Spring and third-party libraries based on the project’s dependencies.
- Production-ready: It includes features such as monitoring, metrics, and externalized configuration, making your application ready for production use.
Pre-requisites for Setting Up a Spring Boot Project
Before setting up your first Spring Boot project, ensure that the following tools and technologies are installed and configured on your development environment.
Software | Version/Requirement |
---|---|
Java Development Kit (JDK) | JDK 8 or higher |
Maven or Gradle | Apache Maven 3.6+ or Gradle 5.6+ |
IDE | IntelliJ IDEA, Eclipse, or Visual Studio Code |
Spring Boot CLI (optional) | For users who want to quickly bootstrap projects |
To check whether you have Java installed, you can use the following command:
java -version
Ensure that the JDK version is at least 8. If Maven is installed, verify it with:
mvn -v
If you do not have Java or Maven installed, you can download them from their official websites and follow the installation instructions provided.
Creating a Spring Boot Project Using Spring Initializr
The easiest way to create a Spring Boot project is through the Spring Initializr, a web-based tool that generates a Spring Boot project structure tailored to your specific needs.
Step 1: Accessing Spring Initializr
Navigate to the Spring Initializr website: https://start.spring.io/. Here, you will be presented with various configuration options for your project.
Step 2: Configuring Project Settings
The following fields need to be configured:
- Project Type: Select either Maven Project or Gradle Project depending on your build tool preference.
- Language: Choose Java as the primary language.
- Spring Boot Version: Choose the latest stable version of Spring Boot (e.g.,
3.0.0
). - Project Metadata: Provide the following details:
- Group: This is the root package name for your application (e.g.,
com.example
). - Artifact: This is the name of your project (e.g.,
springboot-demo
). - Name: This will be the display name of your project.
- Description: Provide a brief description of the project.
- Package Name: Typically generated based on the group and artifact (e.g.,
com.example.springbootdemo
). - Packaging: Choose Jar unless you have a specific need for a War file.
- Java Version: Select
17
if you are using the latest version of Java.
Step 3: Adding Dependencies
Click the “Add Dependencies” button to include the necessary dependencies for your project. For a basic Spring Boot project, include the following dependencies:
- Spring Web: Provides support for building web applications, including RESTful services.
- Spring Data JPA: Offers integration with Java Persistence API (JPA) for database access.
- H2 Database: An in-memory database for development and testing purposes.
Your project configuration should look something like this:
Project: Maven
Language: Java
Spring Boot: 3.0.0
Group: com.example
Artifact: springboot-demo
Dependencies: Spring Web, Spring Data JPA, H2 Database
Step 4: Generate and Download the Project
Once you’ve configured your project and added the necessary dependencies, click the Generate button to download the project. Extract the ZIP file, and open it in your preferred IDE.
Understanding the Project Structure
Once you open the project in your IDE, you’ll notice the following directory structure:
springboot-demo/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/example/springbootdemo/
│ │ │ └── SpringbootDemoApplication.java
│ │ └── resources/
│ │ ├── application.properties
│ │ └── static/
│ └── test/
│ └── java/
│ └── com/example/springbootdemo/
├── pom.xml
Here’s a breakdown of the key components:
- SpringbootDemoApplication.java: This is the main class annotated with
@SpringBootApplication
. This annotation serves multiple purposes, including enabling auto-configuration and component scanning. - application.properties: This file allows you to define properties such as database configurations and server ports.
- src/test/java: This folder is used for writing test cases for your application.
- pom.xml: This file contains the Maven configuration, including dependencies and build settings.
Configuring the Application Properties
Spring Boot provides a centralized way to configure the application through the application.properties
file, located in the src/main/resources
directory. This file can be used to configure server settings, database credentials, logging levels, and more.
For example, to change the default server port, you can add the following line to application.properties
:
server.port=8081
To configure the in-memory H2 database for your application, you can add the following properties:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
These properties enable the H2 console, which can be accessed at http://localhost:8080/h2-console
when running the application.
Running Your Spring Boot Application
Once you have completed the configuration, you can run your Spring Boot application. The simplest way to do this is through your IDE. If you’re using IntelliJ IDEA, right-click on the SpringbootDemoApplication.java
class and select Run. Alternatively, you can use the terminal:
./mvnw spring-boot:run
You should see the following output in the console:
Tomcat started on port(s): 8080 (http)
Started SpringbootDemoApplication in 3.456 seconds (JVM running for 4.0)
The application is now running on http://localhost:8080
. You can verify this by opening your browser and navigating to this URL.
Adding Basic REST Functionality
Now that the application is running, let’s add some basic functionality by creating a REST API endpoint.
Step 1: Create a Controller Class
Create a new Java class called HelloController
in the com.example.springbootdemo
package:
package com.example.springbootdemo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, Spring Boot!";
}
}
This HelloController
class defines a simple REST API endpoint /hello
that returns a message when accessed via HTTP GET.
Step 2: Test the REST API
Once the application is running, open your browser or use a tool like Postman to test the endpoint by visiting http://localhost:8080/hello
. You should see the following response:
Hello, Spring Boot!
Congratulations! You’ve successfully created and tested a RESTful API with Spring Boot.
Testing Your Application
Unit testing is an essential part of any software development process. Spring Boot makes it easy to write tests using the @SpringBootTest
annotation.
Step 1: Writing a Basic Test
Navigate to the src/test/java/com/example/springbootdemo
directory, and create a test class HelloControllerTest.java
:
package com.example.springbootdemo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
public class HelloControllerTest {
@Test
public void testHelloEndpoint() {
HelloController controller = new HelloController();
String response = controller.sayHello();
assertThat(response).isEqualTo("Hello, Spring Boot!");
}
}
This test ensures that the /hello
endpoint returns the expected response.
Step 2: Running the Test
To run the test, use the following Maven command in the terminal:
./mvnw test
If everything is configured correctly, the test will pass, and you will see output indicating that the test has successfully executed.
Conclusion
Setting up your first Spring Boot project is a straightforward process that can be completed quickly using the Spring Initializr and basic configuration. In this guide, we walked through setting up a Spring Boot project from scratch, configuring the application, and adding basic REST functionality. We also covered writing and running unit tests to ensure the reliability of your application.
As you move forward, you can explore additional features of Spring Boot, such as integrating with databases, securing your application with Spring Security, or deploying your project to cloud platforms like AWS or Google Cloud.
By following these steps, you now have the foundation needed to build powerful, production-ready applications using Spring Boot.
Disclaimer: The steps and configurations provided in this blog are accurate as of the time of writing. Spring Boot evolves rapidly, and some features may change. Report any inaccuracies so we can correct them promptly.