Spring Boot
Spring Boot
Creating a Spring Boot Project
Making HTTP GET Requests with Query Parameters in Spring Boot
Making HTTP POST Requests in Spring Boot
Calling a REST API in Spring Boot
Validating Request Input in Spring Boot
Uploading Files in Spring Boot
Downloading Files in Spring Boot
Upload Image File as Base64 String in Spring Boot
How to Zip Multiple Files for Download in Spring Boot/Java
Spring Boot with MySQL
Spring Boot with MongoDB
Spring Data JPA Query Methods
Pagination and Sorting in Spring Boot
Enable Global CORS in Spring Boot
How to Write Unit Tests in Spring Boot - Best Practices and Examples
Convert XML to JSON in Spring Boot
Convert JSON to XML in Spring Boot
Change Logback Log Level Programmatically at Runtime via a REST API in Spring Boot
Exporting Data from MySQL Database to Excel in Spring Boot via REST API using Apache POI Library
Importing Excel Data into MySQL Database in Spring Boot via REST API using Apache POI Library
JWT Authentication using Spring Security OAuth2 in Spring Boot Example
Spring JPA Query to Check if the Current Date is Between a Range of Two Dates
Spring JPA Query to Find the Offered Price on the Current Date by Searching Between a Range of Two Dates
MongoDB Query to Find Ranking of Records in Spring Boot Java
Using Multiple Databases with Spring Data JPA in Spring Boot
Convert HTML to PDF for download in Spring Boot
Building Microservices using Spring Boot in 2024
Calling a Rest API using WebClient in Spring Boot
Creating a Spring Boot Project
- Last updated Apr 25, 2024
In this tutorial, you will learn how to create a Spring Boot project. Spring Boot is a framework that simplifies Java application development by providing pre-configured components and reducing the amount of boilerplate code required.
To create a Spring Boot project, follow these steps:
- Go to the Spring Initializr website at https://start.spring.io.
- Set up the project configuration:
- Choose the project type (Maven or Gradle).
- Set the language to Java.
- Specify the Spring Boot version.
- Enter a Group and Artifact name for your project. The group name is the id of the project. Artifact is the name of your project.
- Add any necessary project metadata (description, package name, etc.).
- Choose between packaging as a JAR (Java Archive) or a WAR (Web Application Archive) depends on how you plan to deploy your Spring Boot application. Choose JAR packaging if you want a standalone executable JAR file and WAR packaging if you intend to deploy your application to a Java EE application server or servlet container. When you package your Spring Boot application as a JAR using JAR packaging, it includes an embedded web server, such as Tomcat, by default. This means that you don't need to separately deploy your application to an external Tomcat server. Instead, you can run the JAR file directly, and the embedded Tomcat server will start and serve your application.
- Select the Java version based on the compatibility requirements of your project. Consider the specific needs of your project, any compatibility requirements, and the Java version supported by your target deployment environment when making these choices.
- Add project dependencies:
- Click on the "Add Dependencies" button.
- Select the dependencies that your project requires (example: Spring Web which is needed for building a Spring web application, and Spring Boot DevTools which is needed for quick restart of the application while it is running, etc.).
- Generate the project:
- Click on the "Generate" button.
- Spring Initializr will generate a zip file containing your Spring Boot project.
- Download and extract the generated project:
- Download the zip file generated by Spring Initializr.
- Extract the contents of the zip file to a directory on your local machine.
- Import the project into your IDE:
- Open your preferred IDE (IntelliJ IDEA, Eclipse, or Spring Tool Suite).
- Import the extracted project as a Maven or Gradle project, depending on the build system you chose in Spring Initializr.
- Add configurations:
- Implement your business logic by creating controllers, services, repositories, and other necessary components:
- Create a User class that represents the user entity. This class can have properties such as id, firstName, lastName, email, etc., along with their getters and setters methods:
- Create a service interface that defines the contract for the UserService. Create a new interface called UserService:
- Create an implementation class that implements the UserService interface and handles the business logic. Let's create a class called UserServiceImpl:
- Create a controller class that will handle HTTP requests and interact with the UserService. Create a new class called UserController:
- Build and run your Spring Boot application:
- Use your IDE's build tools (Maven or Gradle) to build your project and resolve dependencies.
- Once the build is successful, run the main class of your application.
- The Spring Boot application will start and deploy an embedded web server (e.g., Tomcat) automatically.
- You should see logs indicating that the application has started.
- Test your Spring Boot application:
- Open a web browser or use API testing tools (example: Postman) to test your application's endpoints if you have created a web application.
- Verify that your application is functioning as expected based on the implemented logic.
Refer to this image for example:
Open the src/main/resources/application.properties file in your Eclipse editor and specify the server port as 8080 by adding the following configuration line to the file:
server.port = 8080
public class User { private Long id; private String firstName; private String lastName; private String email; private boolean deleted; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean isDeleted() { return deleted; } public void setDeleted(boolean deleted) { this.deleted = deleted; } }
import java.util.List; public interface UserService { void addUser(User user); void updateUser(User user); void deleteUser(Long userId); User getUserById(Long userId); ListgetAllUsers(); }
import java.util.List; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { //Inject any required dependencies or repositories @Override public void addUser(User user) { // Implement the logic to save a user to the database or other source } @Override public void updateUser(User user) { // Implement the logic to update a user data in database or other source } @Override public void deleteUser(Long userId) { // Implement the logic to soft delete a user from the database or source } @Override public User getUserById(Long userId) { // Implement the logic to retrieve a user by ID from the database or other // source // Return the user object return null; } @Override public ListgetAllUsers() { // Implement the logic to retrieve all users from the database or other // source // Return the list of users return null; } }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @PostMapping(path = "/add") public void addUser(@RequestBody User userDto) { userService.addUser(userDto); } @PutMapping(path = "/update") public void updateUser(@RequestBody User userDto) { userService.updateUser(userDto); } @DeleteMapping(path = "/{userId}/delete") public void deleteUser(@PathVariable(name = "userId") Long userId) { userService.deleteUser(userId); } @GetMapping(path = "/{userId}") public ResponseEntitygetUserById(@PathVariable(name = "userId") Long userId) { return ResponseEntity.ok(userService.getUserById(userId)); } @GetMapping(path = "/all") public ResponseEntity
> getAllUsers() { return ResponseEntity.ok(userService.getAllUsers()); } }
Congratulations! You have successfully created and run a Spring Boot project using Spring Initializr. You can continue developing your application by adding more features, configuring additional dependencies, and deploying it to various environments as needed.