Spring Boot makes building robust and production-ready applications seamless with its simplicity and powerful features. In this tutorial, we’ll walk you through the steps to create a simple banking application using Spring Boot. The application will have CRUD functionality, an in-memory H2 database, and a Swagger UI for API documentation.
Why Swagger UI Is Important
Swagger UI is an open-source tool that simplifies API documentation and testing. It allows developers and stakeholders to visualize and interact with the API’s endpoints without requiring any third-party tools like Postman. Integrating Swagger UI into your application saves time and improves collaboration by providing an intuitive interface to explore and test APIs.
Project Setup
Step 1: Generate the Spring Boot Project
- Visit Spring Initializr.
- Configure the project:
- Project: Maven
- Language: Java
- Spring Boot Version: 3.4.1
- Dependencies:
- Spring Web
- Spring Data JPA
- H2 Database
- Lombok
- Generate and download the project, then unzip it.
Step 2: Project Structure
The final structure of the project will look like this:
.
├── Dockerfile
├── pom.xml
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ └── bansikah
│ │ │ └── bankingapp
│ │ │ ├── BankingappApplication.java
│ │ │ ├── config
│ │ │ │ └── SwaggerConfig.java
│ │ │ ├── controller
│ │ │ │ └── AccountController.java
│ │ │ ├── model
│ │ │ │ └── Account.java
│ │ │ ├── repository
│ │ │ │ └── AccountRepository.java
│ │ │ └── service
│ │ │ └── AccountService.java
│ │ └── resources
│ │ ├── application.properties
│ │ ├── data.sql
│ │ ├── schema.sql
Enter fullscreen mode Exit fullscreen mode
In the spring initilizr It could be your name, or example or… not bansikah
Step 3: Add Dependencies to pom.xml
To ensure smooth dependency management, replace the dependencies section of your pom.xml with the following:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springdoc/springdoc-openapi-starter-webmvc-ui -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode
springdoc-openapi-starter-webmvc-ui
is the dependency responsible for the beautiful interface we are gonna have below, we used version 2.6.0
for this project you can try other versions above but am sure you will have same results.
Step 4: Configure the Application
application.properties
spring.application.name=bankingapp
# H2 Database Configuration
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.sql.init.platform=h2
# JPA Configuration
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=update
# Server Port
server.port=8082
# Swagger UI Base URL
springdoc.swagger-ui.path=/swagger-ui.html
Enter fullscreen mode Exit fullscreen mode
Step 5: Create the Components
Model: Account.java
package com.bansikah.bankingapp.model;
import jakarta.persistence.*;
@Entity
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private double balance;
// Getters and Setters
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 String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public double getBalance() { return balance; }
public void setBalance(double balance) { this.balance = balance; }
}
Enter fullscreen mode Exit fullscreen mode
You can use lombok, but i experience some issues so i had to removed it.
Repository: AccountRepository.java
package com.bansikah.bankingapp.repository;
import com.bansikah.bankingapp.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AccountRepository extends JpaRepository<Account, Long> {
}
Enter fullscreen mode Exit fullscreen mode
Service: AccountService.java
package com.bansikah.bankingapp.service;
import com.bansikah.bankingapp.model.Account;
import com.bansikah.bankingapp.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class AccountService {
@Autowired
private AccountRepository accountRepository;
public List<Account> getAllAccounts() {
return accountRepository.findAll();
}
public Optional<Account> getAccountById(Long id) {
return accountRepository.findById(id);
}
public Account saveAccount(Account account) {
return accountRepository.save(account);
}
public Account updateAccount(Long id, Account updatedAccount) {
return accountRepository.findById(id)
.map(account -> {
account.setName(updatedAccount.getName());
account.setEmail(updatedAccount.getEmail());
account.setBalance(updatedAccount.getBalance());
return accountRepository.save(account);
})
.orElse(null);
}
public void deleteAccount(Long id) {
accountRepository.deleteById(id);
}
}
Enter fullscreen mode Exit fullscreen mode
Controller: AccountController.java
package com.bansikah.bankingapp.controller;
import com.bansikah.bankingapp.model.Account;
import com.bansikah.bankingapp.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/accounts")
public class AccountController {
@Autowired
private AccountService accountService;
@GetMapping
public List<Account> getAllAccounts() {
return accountService.getAllAccounts();
}
@GetMapping("/{id}")
public ResponseEntity<Account> getAccountById(@PathVariable Long id) {
return accountService.getAccountById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
public Account createAccount(@RequestBody Account account) {
return accountService.saveAccount(account);
}
@PutMapping("/{id}")
public ResponseEntity<Account> updateAccount(@PathVariable Long id, @RequestBody Account account) {
Account updatedAccount = accountService.updateAccount(id, account);
if (updatedAccount == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(updatedAccount);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteAccount(@PathVariable Long id) {
accountService.deleteAccount(id);
return ResponseEntity.noContent().build();
}
}
Enter fullscreen mode Exit fullscreen mode
Step 6: Add Swagger Configuration
SwaggerConfig.java
package com.bansikah.bankingapp.config;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info().title("Bank Account API")
.version("1.0")
.description("API to test CRUD Bank Account | Tech with Bansikah"));
}
}
Enter fullscreen mode Exit fullscreen mode
We also have these two sql files to create the table and load data into it when the application is started.
schema.sql
CREATE TABLE IF NOT EXISTS ACCOUNT (
ID BIGINT AUTO_INCREMENT PRIMARY KEY,
NAME VARCHAR(255),
EMAIL VARCHAR(255),
BALANCE DOUBLE
);
Enter fullscreen mode Exit fullscreen mode
and data.sql file to load data into the table
data.sql
INSERT INTO ACCOUNT (NAME, EMAIL, BALANCE) VALUES ('John Doe', 'john@example.com', 1000.0);
INSERT INTO ACCOUNT (NAME, EMAIL, BALANCE) VALUES ('Jane Smith', 'jane@example.com', 2000.0);
Enter fullscreen mode Exit fullscreen mode
Run the application and access the swagger ui using http://localhost:8082/swagger-ui/index.html
You should see:
Now let’s test the Get account, and we have
You can test all the other API endpoint Updating data, Creating (post) and deleting.
Conclusion
Congratulations! You’ve successfully built a simple CRUD banking application using Spring Boot. With the help of Swagger UI, you can now explore and test the API endpoints directly through a web interface.
Code linkIf you have any challenges or questions, feel free to leave a comment below. Happy coding!
原文链接:Building a Simple CRUD Banking Application with Spring Boot and Swagger UI
暂无评论内容