Skip to content

Spring Boot demo project with user management REST APIs, JPA/H2 integration, and Next.js frontend. Demonstrates Spring Boot fundamentals through practical implementation.

License

Notifications You must be signed in to change notification settings

adeeshperera/spring-boot-rest-api-starter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 

Repository files navigation

spring-boot-rest-api-starter

A modern full-stack web application built with Spring Boot 3.5.4 (backend) and Next.js 15 (frontend). This project is designed to help you understand the basics of Spring Boot by providing a practical example of how to structure, configure, and develop a RESTful backend using Spring Boot. You'll see how controllers, services, repositories, and entities work together, and how Spring Boot simplifies application setup, dependency management, and database integration. The frontend, built with Next.js and React, demonstrates how to connect to a Spring Boot API, making this project a hands-on introduction to building scalable, enterprise-ready applications with modern Java and JavaScript frameworks.

🏗️ Architecture Overview

This project follows a microservices-inspired architecture with clear separation between the frontend and backend layers:

┌─────────────────────────────────────────────────────────────┐
│                    Client Layer                             │
│  ┌─────────────────────────────────────────────────────┐    │
│  │           Next.js 15 Frontend                      │    │
│  │  • React 19 with TypeScript                        │    │
│  │  • Tailwind CSS v4                                 │    │
│  │  • Turbopack for development                       │    │
│  │  • ESLint for code quality                         │    │
│  └─────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────┘
                              │
                         HTTP/REST API
                              │
┌─────────────────────────────────────────────────────────────┐
│                   Server Layer                              │
│  ┌─────────────────────────────────────────────────────┐    │
│  │           Spring Boot 3.5.4 Backend               │    │
│  │                                                     │    │
│  │  ┌─────────────────┐  ┌─────────────────┐          │    │
│  │  │   Controllers   │  │   Services      │          │    │
│  │  │   (REST API)    │  │  (Business      │          │    │
│  │  │                 │  │   Logic)        │          │    │
│  │  └─────────────────┘  └─────────────────┘          │    │
│  │           │                    │                   │    │
│  │  ┌─────────────────┐  ┌─────────────────┐          │    │
│  │  │      DTOs       │  │   Entities      │          │    │
│  │  │   (Data         │  │  (JPA Models)   │          │    │
│  │  │  Transfer)      │  │                 │          │    │
│  │  └─────────────────┘  └─────────────────┘          │    │
│  │           │                    │                   │    │
│  │  ┌─────────────────┐  ┌─────────────────┐          │    │
│  │  │    Mappers      │  │  Repositories   │          │    │
│  │  │  (MapStruct)    │  │   (Spring       │          │    │
│  │  │                 │  │    Data JPA)    │          │    │
│  │  └─────────────────┘  └─────────────────┘          │    │
│  └─────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────┘
                              │
                        JPA/Hibernate
                              │
┌─────────────────────────────────────────────────────────────┐
│                   Data Layer                                │
│  ┌─────────────────────────────────────────────────────┐    │
│  │              H2 Database                            │    │
│  │  • In-memory database for development               │    │
│  │  • Automatic schema generation                      │    │
│  │  • H2 Console for database inspection               │    │
│  └─────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────┘

🚀 Tech Stack

Backend (Spring Boot 3.5.4)

  • Framework: Spring Boot 3.5.4 with Java 21
  • Web Layer: Spring Web MVC with RESTful APIs
  • Data Access: Spring Data JPA with Hibernate ORM
  • Database: H2 (in-memory for development)
  • Build Tool: Apache Maven 3.x
  • Code Generation: Lombok for boilerplate reduction
  • Cross-Origin: CORS configuration for frontend integration

Frontend (Next.js 15)

  • Framework: Next.js 15.4.4 with React 19
  • Language: TypeScript 5.x for type safety
  • Styling: Tailwind CSS v4 for utility-first styling
  • Development: Turbopack for faster builds
  • Code Quality: ESLint with Next.js configuration
  • Build Tool: Built-in Next.js bundler

📁 Project Structure

testpjt1/
├── client/testpjt-frontend/          # Next.js Frontend Application
│   ├── src/
│   │   └── app/                      # App Router (Next.js 13+)
│   │       ├── layout.tsx            # Root layout component
│   │       ├── page.tsx              # Home page component
│   │       └── globals.css           # Global styles
│   ├── public/                       # Static assets
│   ├── package.json                  # Frontend dependencies
│   ├── tsconfig.json                 # TypeScript configuration
│   ├── next.config.ts                # Next.js configuration
│   ├── tailwind.config.ts            # Tailwind CSS configuration
│   └── eslint.config.mjs             # ESLint configuration
│
└── server/testpjt/                   # Spring Boot Backend Application
    ├── src/main/java/com/testpjt/testpjt/
    │   ├── TestpjtApplication.java   # Spring Boot main class
    │   ├── config/
    │   │   ├── CorsConfig.java       # CORS configuration
    │   │   └── DataInitializer.java  # Initial data setup
    │   ├── controller/
    │   │   └── UserController.java   # REST API endpoints
    │   ├── dto/
    │   │   └── UserDto.java          # Data Transfer Objects
    │   ├── entity/
    │   │   └── User.java             # JPA entity models
    │   ├── mapper/
    │   │   └── UserMapper.java       # Entity-DTO mapping
    │   ├── repository/
    │   │   └── UserRepository.java   # Data access layer
    │   └── service/
    │       └── UserService.java      # Business logic layer
    ├── src/main/resources/
    │   └── application.properties    # Spring Boot configuration
    ├── src/test/                     # Unit and integration tests
    ├── pom.xml                       # Maven dependencies
    └── target/                       # Compiled classes and artifacts

🔧 Technical Implementation Details

Backend Architecture Patterns

1. Layered Architecture

The backend follows a clean layered architecture:

  • Controller Layer: RESTful endpoints (@RestController)
  • Service Layer: Business logic and transaction management (@Service)
  • Repository Layer: Data access abstraction (@Repository with Spring Data JPA)
  • Entity Layer: JPA domain models (@Entity)
  • DTO Layer: Data transfer objects for API communication

2. Dependency Injection

Uses Spring's IoC container with constructor injection via Lombok's @RequiredArgsConstructor.

3. Data Mapping

Implements the Mapper pattern to separate entity and DTO concerns.

4. Exception Handling

Centralized error handling with proper HTTP status codes in controllers.

Database Configuration

H2 In-Memory Database

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create-drop
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

Key Features:

  • Development-friendly: Automatic schema creation/drop on restart
  • Zero configuration: No external database setup required
  • Web console: Accessible at http://localhost:8080/h2-console
  • SQL logging: Enabled for debugging with spring.jpa.show-sql=true

REST API Design

User Management Endpoints

GET    /api/users           # Get all users
GET    /api/users/{id}      # Get user by ID
POST   /api/users           # Create new user
PUT    /api/users/{id}      # Update existing user
DELETE /api/users/{id}      # Delete user

HTTP Status Codes

  • 200 OK: Successful GET/PUT operations
  • 201 Created: Successful POST operations
  • 204 No Content: Successful DELETE operations
  • 400 Bad Request: Invalid request data
  • 404 Not Found: Resource not found

Cross-Origin Resource Sharing (CORS)

Configured to allow frontend-backend communication:

.allowedOrigins("http://localhost:3000", "http://127.0.0.1:3000")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)

Frontend Architecture

Next.js App Router

  • File-based routing: Automatic route generation from file structure
  • Server Components: React Server Components by default
  • Nested layouts: Hierarchical layout system
  • TypeScript integration: Full type safety across the application

Tailwind CSS v4

  • Utility-first: Atomic CSS classes for rapid development
  • Responsive design: Mobile-first responsive utilities
  • PostCSS integration: Advanced CSS processing

🛠️ Development Setup

Prerequisites

  • Java 21 or higher
  • Node.js 18 or higher
  • Maven 3.6 or higher

Backend Setup

  1. Navigate to backend directory:

    cd server/testpjt
  2. Install dependencies and run:

    ./mvnw spring-boot:run
  3. Access points:

    • API: http://localhost:8080/api
    • H2 Console: http://localhost:8080/h2-console

Frontend Setup

  1. Navigate to frontend directory:

    cd client/testpjt-frontend
  2. Install dependencies:

    npm install
  3. Start development server:

    npm run dev
  4. Access application:

    • Frontend: http://localhost:3000

📊 Database Schema

User Entity

CREATE TABLE users (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE,
    age INTEGER
);

Constraints:

  • Primary key: Auto-incrementing id
  • Unique constraint: email field
  • Not null: name and email fields

🧪 Testing

Backend Testing

cd server/testpjt
./mvnw test

Frontend Testing

cd client/testpjt-frontend
npm run lint

📦 Build & Deployment

Backend Build

cd server/testpjt
./mvnw clean package

Generates: target/testpjt-0.0.1-SNAPSHOT.jar

Frontend Build

cd client/testpjt-frontend
npm run build

Generates: .next/ directory with optimized production build

🔍 Key Spring Boot Concepts Demonstrated

  1. Auto-Configuration: Automatic configuration of components based on classpath
  2. Starter Dependencies: Pre-configured dependency bundles (spring-boot-starter-web, spring-boot-starter-data-jpa)
  3. Embedded Server: Built-in Tomcat server, no external deployment needed
  4. Spring Data JPA: Automatic repository implementation generation
  5. Configuration Properties: External configuration via application.properties
  6. Component Scanning: Automatic discovery and registration of Spring components
  7. Aspect-Oriented Programming: Cross-cutting concerns (CORS, transactions)

🚀 Production Considerations

Database Migration

  • Replace H2 with production database (PostgreSQL, MySQL)
  • Implement database migration scripts (Flyway/Liquibase)
  • Configure connection pooling

Security

  • Implement Spring Security for authentication/authorization
  • Add input validation and sanitization
  • Configure HTTPS and security headers

Monitoring

  • Add Spring Boot Actuator for health checks
  • Implement logging strategy (Logback configuration)
  • Add application metrics (Micrometer)

Performance

  • Enable caching (Spring Cache)
  • Implement pagination for large datasets
  • Add database indexing strategies

About

Spring Boot demo project with user management REST APIs, JPA/H2 integration, and Next.js frontend. Demonstrates Spring Boot fundamentals through practical implementation.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published