Hello! In this blog post, we will develop our first web application using Spring Boot 3. Spring Boot is a framework that helps in easily creating web applications based on Java. It is designed to enhance efficiency and productivity, and is widely used by many developers. Through this process, we will build a simple RESTful API.
1. What is Spring Boot?
Spring Boot is a library built on top of the Spring Framework, providing an environment to create Spring applications quickly and easily. Spring Boot has the following advantages:
- Auto-configuration: Spring Boot automatically handles the configuration of the application, reducing the complex setup process for developers.
- Dependency Management: You can easily add and manage the necessary libraries through Maven or Gradle.
- Standalone: Spring Boot applications are built as executable JAR files and do not require a separate web server.
- Embedded Server Support: It supports embedded servers like Tomcat, Jetty, and Undertow for quick testing and deployment.
2. Preparing the Development Environment
The following environment is required to develop a Spring Boot application:
- Java JDK 17 or higher: Spring Boot 3.x runs on Java 17 or higher. You need to install the JDK and set the environment variables.
- IDE: Integrated Development Environments (IDE) such as IntelliJ IDEA or Eclipse are recommended. In this example, we will use IntelliJ IDEA.
- Build Tool: You need to choose either Maven or Gradle to manage dependencies. We will use Maven in this example.
3. Creating the Project
There are several ways to create a Spring Boot project, but to save time, we’ll use Spring Initializr. Please follow the steps below:
- Open Spring Initializr in your web browser.
- Enter the following settings:
- Project: Maven Project
- Language: Java
- Spring Boot: 3.x.x (latest version)
- Project Metadata:
- Group: com.example
- Artifact: demo
- Name: demo
- Description: Demo project for Spring Boot
- Package name: com.example.demo
- Packaging: Jar
- Java: 17
- Add the following dependencies:
- Spring Web
- Spring Data JPA
- H2 Database
- Click the Generate button to download the ZIP file, then extract it.
4. Opening the Project in the IDE
After launching IntelliJ IDEA, open the project as follows:
- Click on the File menu and select “Open”.
- Select the extracted project folder and click the Open button.
- Select Gradle or Maven to download the necessary libraries.
5. Writing the Basic Application Code
After the basic structure of the project is created, the entry point of the application, DemoApplication.java
, will be generated. The file looks like this:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Now, let’s add a controller class to create a REST API. Create a file named HelloController.java
at the path src/main/java/com/example/demo
.
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot 3!";
}
}
The code above is a simple controller that returns the string “Hello, Spring Boot 3!” when a GET request is sent to the “/hello” URL.
6. Running the Application
Now, let’s run the application. Click the run button in the top menu of IntelliJ IDEA, as shown below:
- Run → Run ‘DemoApplication’
If the application starts successfully, “Started DemoApplication in …” message will be displayed in the console. Now open your web browser and access the URL http://localhost:8080/hello
.
If it works correctly, you will see the message “Hello, Spring Boot 3!”.
7. Implementing Simple CRUD using H2 Database
Now, we will implement simple CRUD (Create, Read, Update, Delete) operations using H2 data. First, add the following content to the src/main/resources/application.properties
file to set up the H2 database:
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
spring.jpa.hibernate.ddl-auto=create
Next, let’s create a model class. Create a file named Product.java
at the path src/main/java/com/example/demo
.
package com.example.demo;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
Now, we will create a service and controller to perform CRUD operations for the Product model. Create a file named ProductController.java
at the path src/main/java/com/example/demo
.
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/products")
public class ProductController {
@Autowired
private ProductRepository productRepository;
@GetMapping
public List getAllProducts() {
return productRepository.findAll();
}
@PostMapping
public Product createProduct(@RequestBody Product product) {
return productRepository.save(product);
}
@GetMapping("/{id}")
public ResponseEntity getProductById(@PathVariable Long id) {
return productRepository.findById(id)
.map(product -> ResponseEntity.ok().body(product))
.orElse(ResponseEntity.notFound().build());
}
@PutMapping("/{id}")
public ResponseEntity updateProduct(@PathVariable Long id, @RequestBody Product productDetails) {
return productRepository.findById(id)
.map(product -> {
product.setName(productDetails.getName());
product.setPrice(productDetails.getPrice());
Product updatedProduct = productRepository.save(product);
return ResponseEntity.ok().body(updatedProduct);
}).orElse(ResponseEntity.notFound().build());
}
@DeleteMapping("/{id}")
public ResponseEntity deleteProduct(@PathVariable Long id) {
return productRepository.findById(id)
.map(product -> {
productRepository.delete(product);
return ResponseEntity.noContent().build();
}).orElse(ResponseEntity.notFound().build());
}
}
Finally, create a ProductRepository interface to define methods to interact with the database. Create a file named ProductRepository.java
at the path src/main/java/com/example/demo
.
package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository {
}
8. Running and Testing the Application
Restart the application and use an API testing tool like Postman to test the CRUD API. Here are examples for each request:
- Create Product:
POST /products { "name": "Sample Product", "price": 19.99 }
GET /products
GET /products/{id}
PUT /products/{id} { "name": "Updated Product", "price": 29.99 }
DELETE /products/{id}
9. Checking the H2 Console
You can also manage data through the H2 database. Open your web browser and go to http://localhost:8080/h2-console
. Enter jdbc:h2:mem:testdb
in the JDBC URL, use sa
for the username, and click the Connect button.
Now you can perform various tasks such as querying or deleting data from the H2 database.
10. Conclusion and Next Steps
In this post, we implemented simple CRUD functionality using Spring Boot 3 and H2 database to create a RESTful API. I hope this example helped you understand the basic concepts and workings of Spring Boot. In the future, you can enhance the application by adding more complex databases and business logic.
In the next blog post, we will cover Spring Security for authentication and authorization. Thank you!