A comprehensive, production-ready Spring Boot 3.x REST API demonstrating modern Java development practices, security hardening, and performance optimizations for interview preparation.
- Spring Boot 3.5.4 with Java 17
- Spring Security 6.x with JWT authentication
- Spring Data JPA with Hibernate
- Redis for distributed caching
- PostgreSQL for production database
- MapStruct for efficient mapping
- OpenAPI 3.0 for documentation
- JWT-based authentication with role-based access control
- CSRF protection and CORS configuration
- Security headers (CSP, HSTS, X-Frame-Options)
- Input validation and sanitization
- OWASP dependency scanning
- Secure password encoding with BCrypt
- Redis distributed caching with TTL strategies
- HikariCP connection pooling
- Async operations with custom thread pools
- Database indexing and query optimization
- JVM tuning for containerized environments
- Comprehensive logging with MDC tracing
- Actuator endpoints for monitoring
- Prometheus metrics integration
- Global exception handling
- HATEOAS hypermedia support
- Docker containerization
- CI/CD pipeline with GitHub Actions
- Auto-configuration: How Spring Boot configures beans automatically
- Application startup: SpringApplication.run() lifecycle
- Bean lifecycle: Creation, initialization, and destruction
- Dependency injection: Constructor vs field injection
- Profiles: Environment-specific configurations
- IoC Container: BeanFactory vs ApplicationContext
- AOP: Aspect-oriented programming with proxies
- Transaction management: @Transactional propagation and isolation
- Event handling: ApplicationEvent and listeners
- Scopes: Singleton, prototype, request, session
- JPA/Hibernate: Entity lifecycle, lazy loading, caching
- Repository pattern: Spring Data JPA query methods
- Transaction boundaries: Service layer transactions
- Connection pooling: HikariCP configuration
- Database migrations: Flyway/Liquibase integration
- Authentication vs Authorization: Concepts and implementation
- JWT tokens: Structure, validation, and security
- Method-level security: @PreAuthorize/@PostAuthorize
- CORS: Cross-origin resource sharing
- CSRF: Cross-site request forgery protection
- Unit testing: Mockito vs @MockBean
- Integration testing: @SpringBootTest vs @WebMvcTest
- Testcontainers: Real database testing
- Test slices: Focused testing with specific contexts
βββ controller/ # REST endpoints with HATEOAS
βββ service/ # Business logic layer
βββ repository/ # Data access layer
βββ entity/ # JPA entities
βββ dto/ # Data transfer objects (Records)
βββ mapper/ # MapStruct mappers
βββ config/ # Configuration classes
βββ security/ # Security components
βββ exception/ # Custom exceptions and handlers
- Java 17+
- Maven 3.8+
- Docker & Docker Compose
- Redis (for caching)
- PostgreSQL (for production)
- Clone the repository
git clone <repository-url>
cd book-api- Start dependencies
docker-compose up -d redis postgres- Run the application
./mvnw spring-boot:run -Dspring-boot.run.profiles=dev- Access the API
- API: http://localhost:8080/api/v1/books
- Swagger UI: http://localhost:8080/swagger-ui.html
- H2 Console: http://localhost:8080/h2-console (dev profile)
- Actuator: http://localhost:8080/actuator
# Unit tests
./mvnw test
# Integration tests with Testcontainers
./mvnw verify
# Security scan
./mvnw org.owasp:dependency-check-maven:checkThe API uses JWT Bearer tokens for authentication. Include the token in the Authorization header:
curl -H "Authorization: Bearer <jwt-token>" \
http://localhost:8080/api/v1/books- USER: Read access to books
- LIBRARIAN: Create and update books
- ADMIN: Full access including delete operations
| Method | Endpoint | Description | Roles |
|---|---|---|---|
| GET | /api/v1/books |
Get all books (paginated) | USER+ |
| GET | /api/v1/books/{id} |
Get book by ID | USER+ |
| POST | /api/v1/books |
Create new book | LIBRARIAN+ |
| PUT | /api/v1/books/{id} |
Update book | LIBRARIAN+ |
| DELETE | /api/v1/books/{id} |
Delete book | ADMIN |
| GET | /api/v1/books/search?q={term} |
Search books | USER+ |
| GET | /api/v1/books/category/{category} |
Get books by category | USER+ |
| GET | /api/v1/books/low-stock?threshold={n} |
Get low stock books (async) | ADMIN |
# Build image
docker build -t book-api:latest .
# Run container
docker run -p 8080:8080 \
-e SPRING_PROFILES_ACTIVE=prod \
-e DB_HOST=postgres \
-e REDIS_HOST=redis \
book-api:latestdocker-compose up -d/actuator/health- Application health/actuator/metrics- Application metrics/actuator/prometheus- Prometheus metrics/actuator/info- Application information
- Structured logging with JSON format
- MDC for request tracing
- Log levels configurable per environment
- Log rotation and archival
| Variable | Description | Default |
|---|---|---|
SPRING_PROFILES_ACTIVE |
Active profile | dev |
DB_HOST |
Database host | localhost |
DB_PORT |
Database port | 5432 |
DB_NAME |
Database name | bookapi |
DB_USERNAME |
Database username | bookapi |
DB_PASSWORD |
Database password | password |
REDIS_HOST |
Redis host | localhost |
REDIS_PORT |
Redis port | 6379 |
JWT_SECRET |
JWT signing secret | (generated) |
- Service layer with Mockito
- Repository layer with @DataJpaTest
- Controller layer with @WebMvcTest
- Security configuration testing
- Full application context with @SpringBootTest
- Real databases with Testcontainers
- End-to-end API testing
- Security integration testing
- Load testing with JMeter
- Database performance profiling
- Cache hit ratio monitoring
- Memory usage analysis
The project includes a comprehensive GitHub Actions pipeline:
-
Test Stage
- Unit and integration tests
- Code coverage reporting
- OWASP dependency scanning
- SonarQube analysis
-
Build Stage
- Docker image building
- Multi-architecture support
- Vulnerability scanning with Trivy
- Image signing and attestation
-
Deploy Stage
- Kubernetes deployment
- Smoke testing
- Rollback capabilities
- Notification integration
Q: Explain how Spring Boot application starts up.
A: Spring Boot startup follows these steps:
SpringApplication.run()creates a SpringApplication instance- Determines application type (SERVLET, REACTIVE, NONE)
- Loads
ApplicationContextInitializersandApplicationListeners - Creates and configures
ApplicationContext - Runs auto-configuration classes based on classpath scanning
- Scans for components (
@Component,@Service,@Repository,@Controller) - Starts embedded server (Tomcat by default)
- Publishes
ApplicationReadyEvent
Q: Describe Spring Bean lifecycle.
A: Bean lifecycle phases:
- Instantiation: Constructor called
- Dependency Injection: Properties and dependencies set
- BeanNameAware:
setBeanName()called if implemented - ApplicationContextAware:
setApplicationContext()called if implemented - BeanPostProcessor:
postProcessBeforeInitialization()called - InitializingBean:
afterPropertiesSet()called if implemented - @PostConstruct: Custom init method called
- BeanPostProcessor:
postProcessAfterInitialization()called - Bean Ready: Bean is ready for use
- DisposableBean:
destroy()called during shutdown if implemented - @PreDestroy: Custom destroy method called
Q: How does @Transactional work?
A: @Transactional works through AOP proxies:
- Spring creates a proxy around the bean
- Proxy intercepts method calls
- Begins transaction before method execution
- Commits transaction on successful completion
- Rolls back on unchecked exceptions
- Supports propagation (REQUIRED, REQUIRES_NEW, etc.)
- Supports isolation levels (READ_COMMITTED, SERIALIZABLE, etc.)
Q: Explain the caching implementation.
A: Multi-level caching strategy:
- L1 Cache: Hibernate first-level cache (session-scoped)
- L2 Cache: Hibernate second-level cache (application-scoped)
- Application Cache: Spring Cache with Redis
- HTTP Cache: Browser/CDN caching with proper headers
- Cache-aside pattern: Application manages cache explicitly
- TTL strategies: Different expiration times based on data volatility
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Run the full test suite
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
- Spring Boot team for the excellent framework
- Spring Security team for comprehensive security features
- Testcontainers for integration testing capabilities
- OWASP for security best practices
- The open-source community for continuous improvements