1. What Is Spring Boot? Why Spring Boot?
Spring Boot is an opinionated framework, an extension built on top of the Spring Framework, used to build production-ready, stand-alone applications with minimal configuration.
Opinionated Framework → provides sensible defaults so developers focus on business logic instead of configuration.
Spring Boot = Spring Framework + Automation
Without Spring Boot
Create Project
↓
Add Dependencies
↓
Configure XML / Java Config
↓
Configure Tomcat, DispatcherServlet, Database, Logging
↓
More Boilerplate
With Spring Boot
Create Project
↓
Add Starter
↓
Run Application
↓
Ready
Spring vs Spring Boot
ConfigurationMore Configuration — XML / Java Config
ServerExternal Server Required
DependenciesManual Dependency Management
NatureFlexible, Foundation Layer
ConfigurationMinimal Configuration, Opinionated Defaults
ServerEmbedded Tomcat / Jetty / Undertow
DependenciesStarter Dependencies, Auto Configuration
NatureRapid Development, Production Ready
Features / Advantages Of Spring Boot
Profiles & External Config
Spring Ecosystem
Java
├── Spring Framework → Core (IoC, DI), MVC, AOP, JDBC, Security, Data
└── Spring Boot → Auto Configuration, Starter Dependencies, Embedded Server, Actuator, Production Ready, Microservices
2. @SpringBootApplication
Combines
@SpringBootConfiguration (specialization of @Configuration — marks main configuration class, contains @Bean definitions)
@EnableAutoConfiguration (creates beans automatically based on classpath)
@ComponentScan (scans package for Spring Beans)
@SpringBootApplication Flow
Application Starts
↓
Configuration Loaded
↓
Auto Configuration
↓
Component Scan → Beans Created
↓
Embedded Server Starts → Application Ready
Main Class Kept In Root Package so Component Scan covers all sub-packages by default.
3. Spring Boot Startup Flow, Runners & Startup Events
SpringApplication.run() — Internal Flow
main()
↓
SpringApplication.run() → Prepare Environment
↓
Create ApplicationContext → Apply Initializers
↓
Load application.properties → Load Active Profile
↓
Component Scan → Auto Configuration → Create Beans
↓
Dependency Injection → @PostConstruct → Context Refreshed
↓
CommandLineRunner → ApplicationRunner
↓
Embedded Server Starts → Application Ready
SpringApplication.run() responsibilities: Create SpringApplication, Start IoC Container, Create ApplicationContext, Perform Component Scan, Auto Configure Beans, Refresh Context, Execute Runners, Start Embedded Server.
Startup Events (Published In Order)
ApplicationStartingEvent → EnvironmentPreparedEvent → ContextInitializedEvent → ContextRefreshedEvent → ApplicationStartedEvent → ApplicationReadyEvent → (On Failure) ApplicationFailedEvent
CommandLineRunner vs ApplicationRunner
Methodrun(String... args)
ExecutedAfter ApplicationContext is loaded, before app is fully ready
UseSimple startup tasks — DB init, cache warmup, seed data
Methodrun(ApplicationArguments args)
BenefitNamed / option arguments, better CLI support
UseComplex CLI apps, parse startup options, batch applications
Multiple runners can co-exist; execution order controlled by @Order. Use ApplicationReadyEvent for post-startup tasks like starting a scheduler or warming external APIs. Keep runner logic lightweight and idempotent; fail fast on critical startup validation.
4. Auto Configuration & Internal Working
Auto Configuration Internal Flow
Application Starts → @EnableAutoConfiguration
↓
Read Classpath → Detect Dependencies
↓
Load Auto Configuration Classes (AutoConfiguration.imports)
↓
Check @Conditional Annotations
↓
Create Required Beans → Skip Existing Beans → Application Ready
Example: spring-boot-starter-web → auto-configures Tomcat, DispatcherServlet, Spring MVC, Jackson — no manual configuration required. spring-boot-starter-data-jpa → detects Hibernate on classpath → creates EntityManager, DataSource, TransactionManager automatically.
Conditional Annotations Used Internally
@ConditionalOnClass→Bean created if specified class exists in classpath
@ConditionalOnMissingBean→Bean created only if no existing bean of same type exists (default beans)
@ConditionalOnBean→Bean created only if another bean already exists
@ConditionalOnProperty→Bean created based on a matching property value
@ConditionalOnMissingClass→Bean created if specified class is absent
@Conditional→Base annotation used to build custom conditions
Why Auto Configuration?
✓Reduce Boilerplate
✓Faster Development
✓Sensible Defaults
✓Easy Customization
✓Production Ready
5. Starter Dependencies, Spring Initializr & Embedded Server
Common Starters
spring-boot-starter-web→REST APIs, Embedded Tomcat, DispatcherServlet, Spring MVC, Jackson
spring-boot-starter-data-jpa→Hibernate, Spring Data JPA, Transactions
spring-boot-starter-security→Spring Security — Authentication & Authorization
spring-boot-starter-validation→Jakarta Validation — @NotNull, @Valid
spring-boot-starter-test→JUnit, Mockito, Spring Test
spring-boot-starter-actuator→Production Monitoring
Starter Dependency = predefined dependency bundle containing required libraries for a specific feature. Without a starter you'd need many individual dependencies; with a starter, one dependency includes everything needed.
Spring Initializr
Project generator used to create Spring Boot projects. Provides: Java Version, Spring Boot Version, Maven/Gradle, Packaging, Dependencies, Project Structure.
Embedded Server
Server packaged inside the application itself. Default: Tomcat. Also supports: Jetty, Undertow.
Benefits: No External Installation, Easy Deployment, Single Executable JAR, Same Environment Everywhere, Cloud Friendly.
JAR vs WAR
ContainsApplication + Embedded Server + Dependencies
Runjava -jar app.jar
Preferred ForMicroservices, Docker, Kubernetes, AWS, Azure, Standalone Apps
ContainsApplication Only
RequiresExternal Server — Tomcat, JBoss, WebLogic
Preferred ForLegacy Enterprise, Shared Application Server, Organizational Standards
6. IoC & Dependency Injection
IoC (Inversion Of Control)
Traditional: Service service = new Service();
Spring: Spring creates the object, Spring manages the object, Spring injects the object.
DI Internal Flow
Component Scan
↓
Bean Created → Stored In IoC Container
↓
Dependency Resolved → Injected
↓
Bean Ready For Use
Injection Types
Constructor Injection ⭐
Recommended / Best Practice
ImmutableMandatory DependencyEasy Testing
Setter Injection
Optional Dependency
Object May Be Partially Initialized
Field Injection
Simple, uses Reflection
Hard To TestAvoid In Production
@Autowired vs @Resource vs @Qualifier vs @Primary
| Annotation | Resolution | Purpose |
| @Autowired | By Type → @Qualifier → Name | Automatic bean injection |
| @Resource | By Name → Fallback: By Type | Injects by name first |
| @Qualifier | — | Resolve multiple-bean ambiguity |
| @Primary | — | Default bean when multiple beans exist |
Autowiring Resolution Order & Circular Dependency
@Autowired → By Type
↓ Multiple Beans?
@Qualifier
↓ Still Multiple?
@Primary
↓ Still Ambiguous?
NoUniqueBeanDefinitionException
7. Spring Bean, Bean Lifecycle & Scopes
Bean Lifecycle
Container Start → Bean Instantiation
↓
Dependency Injection
↓
@PostConstruct → Bean Ready
↓
Application Running
↓
@PreDestroy → Bean Destroyed
Bean Scopes
Singleton → One Bean (Default)
Prototype → New Bean Every Request
Request → One Per HTTP Request
Session → One Per User Session
Application → One Per ServletContext
8. Stereotype Annotations & @Bean vs @Component vs @Configuration
Component Hierarchy
@Component
├── @Service — Business Logic
├── @Repository — Database Layer + Exception Translation
└── @Controller — MVC, Returns View (JSP/HTML)
└── @RestController = @Controller + @ResponseBody → Returns JSON/XML
@Configuration vs @Component vs @Bean
BehaviorBean automatically discovered via Component Scan
BehaviorCreates a Configuration class; contains @Bean methods
BehaviorBean created manually inside a @Configuration class
Real usage: @Bean → AWS S3 Client, Mail Sender, ObjectMapper, RestTemplate, WebClient.
9. Configuration, Profiles & External Config
Configuration Sources (Read In Order)
application.properties → application.yml → Environment Variables → Command Line Arguments → System Properties → External Configuration Files
Property Resolution Priority (Highest → Lowest)
Command Line Args
→
Java System Properties
→
Environment Variables
→
External application.properties
→
Internal application.properties
→
Default Values
application.properties vs application.yml
Formatserver.port=8081
Best ForSimple, small configuration
FormatHierarchical (server → port → 8080)
Best ForCleaner, large / nested configuration
Example properties: server.port=8081, spring.datasource.url=..., spring.jpa.hibernate.ddl-auto=update, logging.level.root=INFO
Profiles
application.properties (Common) → application-dev.properties → application-test.properties → application-stqa.properties → application-prod.properties
Activate: spring.profiles.active=dev
@Profile("dev") → loads a bean only for a specific environment (e.g. MockEmailService in dev, AwsSesEmailService in production).
@Value vs @ConfigurationProperties
ReadsSingle property — e.g. @Value("${app.name}")
ReadsGroup of related properties into a Java object — Type Safe, Cleaner, Recommended
@ConfigurationPropertiesScan → automatically scans and registers @ConfigurationProperties classes as beans (no need for @Component on the config class). Environment interface → reads properties, active profile and feature flags programmatically.
10. Conditional Beans — Feature Toggles
Application Starts → Read Configuration
↓
Evaluate Condition
↓ True
Create Bean
↓ False
Skip Bean
Real examples: payment.gateway=stripe → creates StripeService (else PayPalService); notification.email.enabled=true → creates EmailService; Redis / Kafka / SMTP beans created only when enabled.
11. Spring MVC & REST
Request Flow
Browser / Postman
↓
DispatcherServlet (Front Controller) → HandlerMapping
↓
Controller → Service → Repository → Database
↓
Entity → DTO → Jackson
↓
JSON Response
DispatcherServlet responsibilities: Receive Request → Find Controller → Execute Controller → Return Response.
REST — Representational State Transfer
HTTP Methods & CRUD
| Method | CRUD | Meaning |
| GET | Read | Retrieve |
| POST | Create | Create a resource |
| PUT | Update | Complete update of a resource |
| PATCH | Update | Partial update of a resource |
| DELETE | Delete | Delete a resource |
Core REST Annotations
@RequestMapping("/reports")→Map an HTTP request URL to a controller class
@GetMapping / @PostMapping / @PutMapping / @DeleteMapping / @PatchMapping→HTTP-method-specific mappings
@PathVariable→Extracts values from the URL path — /users/101
@RequestParam→Extracts query parameter values — /users?id=101
@RequestBody→JSON → Java Object (via Jackson)
@ModelAttribute→Form data / query parameters → Object
ResponseEntity & JSON Conversion
ResponseEntity<T>
Contains: Body + Headers + Status Code.
JSON Conversion
Java Object → HttpMessageConverter → Jackson → JSON (and reverse, automatically).
HTTP Status Codes
| Code | Meaning |
| 200 OK / 201 Created / 204 No Content | 2xx — Success |
| 400 Bad Request / 401 Unauthorized / 403 Forbidden / 404 Not Found / 409 Conflict | 4xx — Client Error |
| 500 Internal Server Error / 503 Service Unavailable | 5xx — Server Error |
REST API Best Practices
✓Use Nouns (/api/users, not /getUsers)
✓Use Proper HTTP Methods
✓Return DTO, Never Entity
✓Meaningful HTTP Status Codes
✓Global Exception Handling
✓Validate Input
✓Pagination, Sorting, Filtering
✓Version APIs (/api/v1/users)
✓Secure APIs — JWT, OAuth2, HTTPS
12. Validation
Common Validation Annotations
@NotNull, @NotBlank, @NotEmpty, @Size, @Email, @Pattern, @Min, @Max, @Positive
Controller: @Valid RequestDTO
Custom message: @NotBlank(message="Name is required")
Bean Validation, Nested Validation, Mostly Used On DTOs
Supports Validation Groups, Method Validation, Service Layer
13. Exception Handling
Exception Flow
Request → Controller → Service → Repository
↓
Exception
↓
@ControllerAdvice → @ExceptionHandler
↓
Custom Error Response → Client
Goal: Provide Consistent Error Response, Avoid Stacktrace To Client, Centralize Error Handling. @ControllerAdvice = Global Exception Handler (Centralized, Reusable, Cleaner Controllers). @ExceptionHandler handles a specific exception and returns a custom response (e.g. UserNotFoundException → 404 NOT FOUND).
Common Exceptions & Custom Error Response
| Exception | Meaning |
| MethodArgumentNotValidException | Validation Failed |
| EntityNotFoundException | Resource Missing |
| DataIntegrityViolationException | Constraint Violation |
| ConstraintViolationException | Bean Validation |
| SQLException | Database Error |
| AccessDeniedException | 403 |
| AuthenticationException | 401 |
Typical custom error response fields: timestamp, status, error, message, path.
14. Spring Data JPA — Basics, Entity & Repository
JPA → Java Persistence API, Specification (not implementation)
Hibernate → Implementation of JPA
Spring Data JPA → Abstraction that makes Hibernate/JPA easier
Spring Data JPA Architecture
Controller → Service
↓
Repository (JpaRepository)
↓
Hibernate → JDBC
↓
Database
Entity Annotations & Primary Key Generation
Common Entity Annotations
@Entity (marks entity), @Table (table name), @Id (primary key), @GeneratedValue (auto ID), @Column, @Version (optimistic lock), @Transient (ignore field), @Lob, @CreationTimestamp, @UpdateTimestamp
Primary Key Generation
IDENTITY → DB Auto Increment
AUTO → Spring decides
SEQUENCE → Uses DB Sequence
UUID → Globally Unique — best for Cloud, Microservices, Distributed Systems
CrudRepository vs JpaRepository & Derived Queries
CRUD + Pagination + Sorting + Flush + Batch Operations
Common methods: save(), findById(), findAll(), delete(), deleteById(), count(), existsById(), flush(), saveAll(). Derived query methods (no SQL required): findByEmail(), findByStatus(), findByNameContaining(), findBySalaryGreaterThan(), findByStatusAndRole(). @Query used when a derived method isn't enough — supports JPQL or Native SQL.
JPQL vs SQL
Works on Entities & Fields — SELECT e FROM Employee e
Works on Tables & Columns — SELECT * FROM employee
15. JPA Relationships, Cascade, N+1 & Performance
JPA Relationships
@OneToOne — Employee ↔ Aadhaar
@OneToMany — Customer ↔ Orders
@ManyToOne — Orders ↔ Customer
@ManyToMany — Student ↔ Course
Cascade Types
A parent operation is automatically applied to the child entity.
Types: ALL, PERSIST, MERGE, REMOVE, REFRESH, DETACH
Load When Needed, Less Memory, Better Performance, may cause LazyInitializationException
Load Immediately, More Queries/Memory, can cause N+1
Rule: default to LAZY, load only required data.
N+1 Query Problem & How To Solve
1 Query For Parent (e.g. 100 Employees)
↓
100 More Queries For Each Child
↓
101 Queries Total → Slow APIs, High DB Load
✓Fetch Join — Single query loads Employee + Department + Address
✓@EntityGraph — specify which associations to load, without changing fetch type
✓DTO Projection — return only required fields, not the entity
✓Batch Fetching
✓Avoid Unnecessary EAGER
Pagination, Sorting & Indexing
Pagination & Sorting
Avoid SELECT * loading millions of rows — use Pageable → Page<Employee> (page, size). Sort.by("salary") ASC/DESC. Pagination + Sorting can be combined.
Benefits: Less Memory, Fast API, Scalable.
Indexing
Create index on: Primary Keys, Foreign Keys, Search Columns, Frequently Filtered/Joined Columns.
Benefits: Fast Queries, Less Full Table Scan.
Database Performance Checklist
✓Proper Indexes
✓Pagination
✓DTO Projection
✓Fetch Join / EntityGraph
✓Batch Processing
✓Connection Pool Tuning
✓Query Optimization
✓Cache Frequently Used Data
✓Avoid SELECT *
16. Hibernate & Persistence Context
Hibernate — ORM Framework
Converts Java Object → SQL → Database. Developer writes Java; Hibernate writes SQL.
Flow: Entity → Persistence Context → Hibernate → SQL → Database.
Persistence Context / First Level Cache
First Level Cache is Session Level, Enabled By Default. Maintains managed entities — same entity loaded once during the transaction, avoiding repeated DB calls.
17. Transactions, Propagation, Isolation & Locking
@Transactional — Why?
Begin Transaction → Execute SQL
↓ Success
Commit
↓ Exception
Rollback
Without a transaction: Insert Success, Update Failed, Delete Skipped → Data Inconsistent. With a transaction: everything Commits or everything Rolls back.
A = Atomicity, C = Consistency, I = Isolation, D = Durability (ACID).
Propagation Types
REQUIRED ⭐ (Default)→Join existing transaction, else create new
REQUIRES_NEW→Always start a new transaction
SUPPORTS→Join if exists, else run non-transactional
MANDATORY→Must have an existing transaction
NOT_SUPPORTED→Suspend existing transaction
NEVER→No transaction allowed
Isolation Levels
READ_UNCOMMITTED→Dirty Reads Possible
READ_COMMITTED ⭐→Only Committed Data
REPEATABLE_READ→Same Row, Same Value
SERIALIZABLE→Highest Isolation, Slowest
Optimistic vs Pessimistic Locking
Uses @Version, no lock during read, version checked during update — detects conflicts. If version changed → OptimisticLockException. Best for rare conflicts.
Locks the record immediately using a DB lock, other users wait — prevents conflicts before update. Best for Banking, Inventory, Seat Booking.
18. Connection Pooling — HikariCP
HikariCP — Default Connection Pool
Fast, Lightweight, Reusable Connections — avoids creating a new connection for every request.
Important properties: maximumPoolSize, minimumIdle, connectionTimeout, idleTimeout, maxLifetime.
Connection Pool Flow
API Request → Borrow Connection
↓
Execute SQL
↓
Return Connection To Pool
19. Spring Security, JWT & OAuth2
Authentication vs Authorization
Authentication → WHO ARE YOU? Login → Verify Identity
Authorization → WHAT CAN YOU ACCESS? Role Check → Permission Check
Remember: Authentication always happens before Authorization.
Security Request Flow
Request → SecurityFilterChain
↓
Authentication → Authorization
↓
Controller → Response
Spring Security Components: SecurityFilterChain, UserDetailsService, AuthenticationManager, PasswordEncoder, AuthenticationProvider, JWT Filter.
JWT Flow & Structure
POST /login → AuthenticationManager → UserDetailsService
↓
Generate JWT → Return Token → Client Stores Token
↓
Authorization: Bearer <token> → JWT Filter → Validate Token
↓
SecurityContext → Controller
JWT Structure = Header.Payload.Signature — Header (Algorithm, Token Type), Payload (Username, Roles, Claims, Expiry), Signature (Verification, Tamper Protection). JWT = Stateless Authentication.
JWT vs Session & OAuth2 vs OIDC
Stateless, Scalable, Stored Client Side, Preferred For REST
Stateful, Stored Server Side, Traditional MVC
Authorization Framework — can use JWT internally
OAuth2 + Authentication — provides Identity, User Information, ID Token
BCrypt, RBAC & CSRF
BCrypt Password Encoder
Plain Password → BCrypt → Hash → Database. Never store plain passwords.
Role Based Access & CSRF
Roles: ADMIN, USER, TRAINER, CANDIDATE — hasRole("ADMIN"), @PreAuthorize, hasAuthority().
CSRF (Cross Site Request Forgery): enabled by default for session-based apps, usually disabled for stateless JWT APIs.
20. Caching
Cache Flow
Client → Cache
↓ Found
Return
↓ Not Found
Database → Store In Cache → Return
Cache Annotations & Providers
@EnableCaching enables caching.
@Cacheable → Read & Store
@CachePut → Update Cache
@CacheEvict → Remove Cache
Providers: Redis ⭐, Caffeine, EhCache, Hazelcast.
When to cache: Master Data — Country, State, Role, Configuration, Lookup Tables, frequently read / rarely updated. When NOT to cache: Payments, Transactions, frequently updated or sensitive data.
21. Async Processing
@Async
Runs a method in a separate thread. Use cases: Send Email, Generate Report, Notification, File Upload.
Async Flow
Save User → Return Response
↓
Background Thread → Send Email
22. Testing
Unit Test
One class, mocked dependencies — JUnit + Mockito
Integration Test
Loads Spring Context, tests multiple components
@SpringBootTest
Loads the entire application context
@DataJpaTest
Loads only JPA components — repository testing
@WebMvcTest
Controller layer only
MockMvc
Tests controllers without starting a real server
Testcontainers: starts real PostgreSQL / Redis / Kafka / RabbitMQ inside Docker — production-like testing, no H2 differences. Mockito: mocks dependencies to focus on business logic without a database (@Mock, @InjectMocks).
23. Spring Boot Actuator
Provides production-ready monitoring, management and health information for the application.
Without Actuator: no visibility into application status. With Actuator: Health, Metrics, Environment, Beans, Logs, Thread Dump, Heap Dump, Monitoring.
Common Actuator Endpoints
/actuator/health→Application health
/actuator/info→Application information
/actuator/metrics→Performance metrics
/actuator/env→Environment properties
/actuator/beans→Spring beans
/actuator/mappings→All REST endpoints
/actuator/loggers→Logging configuration
/actuator/threaddump→Running threads
/actuator/heapdump→Heap memory dump
Health Status values: UP (working), DOWN (critical failure), OUT_OF_SERVICE (temporarily unavailable), UNKNOWN (cannot determine). Default health checks: Database, Disk Space, Ping, Redis, RabbitMQ, MongoDB, Elasticsearch — plus Custom Health Indicators (e.g. Payment Gateway, External API, Kafka, SMTP availability).
24. DevTools, Packaging & Production Configuration
DevTools
Automatic Restart, Live Reload, Disable Template Cache — Development Only.
Production Configuration Flow
HTTPS → Database Pool → Logging
↓
Security → Monitoring → External Configuration
↓
Graceful Shutdown → Caching
Logging: DEBUG for Development (detailed logs); INFO/WARN/ERROR only for Production. Graceful Shutdown allows running requests to complete before the app stops — no data loss, safer deployment. Externalized Secrets (passwords, API keys, JWT secrets, DB credentials) must never live in source code — use Environment Variables, Secret Manager, Vault, or Kubernetes Secrets.
Zero Downtime Deployment & Docker
Zero Downtime Deployment
Rolling Deployment, Blue-Green, Canary Release, Load Balancer, Health Checks.
Docker Deployment Flow
Build JAR → Docker Image
↓
Docker Hub → Docker Compose
↓
EC2 → Container Running
Enterprise Production Best Practices
✓Use Executable JAR For Microservices
✓Keep Secrets Outside Source Code
✓Enable & Secure Only Required Actuator Endpoints
✓Use HTTPS In Production
✓Configure HikariCP Properly
✓Use INFO Logging In Production
✓Enable Graceful Shutdown
✓Monitor JVM, Database & HTTP Metrics
✓Disable DevTools In Production
✓Use Readiness & Liveness Probes In Kubernetes
25. Microservices Communication
Modern, Non-Blocking, Reactive
Declarative HTTP Client, Less Boilerplate, preferred for microservices
Kafka → Async Communication: Producer → Topic → Consumer. @KafkaListener. Consumer Group → Scalability. Offset → Message Position.
26. Common Design Patterns In Spring
Proxy
@Transactional, @Cacheable, @Async
Template
JdbcTemplate, KafkaTemplate
MVC
Controller-Service-Repository
27. Production Issue Troubleshooting
General Troubleshooting Flow
API Slow → Check SQL → Indexes → N+1
↓
External APIs → Thread Dump → GC
↓
Connection Pool
1. API Slow
Slow SQL, N+1, No Index, External Service, Large JSON, Small Connection Pool
2. Application Slow
CPU, Memory, GC, Thread Pool, Deadlock, Blocking Calls
3. Connection Pool Exhausted
Connection Leak, Long Running Query, Database Down, Pool Too Small, Deadlock
4. Memory Increasing
Memory Leak, Large Cache, Static Collection, Huge Objects
5. 401 / 403 Errors
JWT Expired, Wrong Role, Invalid Token, Security Config
6. Works Locally, Fails In Production
Wrong Profile, Missing ENV, Firewall, Port, Database URL, Secrets
7. Deployment Successful, Old Behavior Persists
Old JAR, Browser Cache, Load Balancer, Rolling Deployment, Config Not Updated
8. @Transactional Not Working
Method Private, Self Invocation, Checked Exception, Wrong Proxy
9. LazyInitializationException
Session Closed, Access Lazy Entity Outside Transaction — Fix: DTO, Fetch Join, EntityGraph
10. Duplicate Records
Retry, Double Click, Race Condition — Fix: Unique Constraint, Idempotency, Transaction
28. Top Interview Differences
Spring vs Spring Boot
@Controller vs @RestController
@Component vs @Bean
@Configuration vs @Component
@Autowired vs @Resource
Constructor vs Field Injection
@PathVariable vs @RequestParam
PUT vs PATCH
JPA vs Hibernate vs Spring Data JPA
JPQL vs SQL
CrudRepository vs JpaRepository
LAZY vs EAGER
Authentication vs Authorization
JWT vs Session
OAuth2 vs JWT vs OpenID Connect
@Valid vs @Validated
JAR vs WAR
BeanFactory vs ApplicationContext
RestTemplate vs WebClient vs Feign
Optimistic vs Pessimistic Locking
Cache vs Session
Monolith vs Microservices
Synchronous vs Asynchronous
Blocking vs Non-Blocking
DTO vs Entity vs VO
SOAP vs REST
HTTP vs HTTPS
UUID vs Sequence
save() vs saveAndFlush()
@RequestBody vs @ModelAttribute
CommandLineRunner vs ApplicationRunner
Cacheable vs CacheEvict
Singleton vs Prototype
29. Real Project Scenarios
Banking API→spring-boot-starter-web → REST APIs
CertifyHub→spring-boot-starter-data-jpa → Hibernate configured automatically; UserController → UserService → UserRepository
Authentication Service→spring-boot-starter-security → security beans created
Microservice Deployment→Executable JAR → Docker → java -jar app.jar
CertifyHub Startup→Load Default Roles → Create Admin User → Load Permission Cache → Verify DB Connection
Payment Service→payment.gateway=stripe → Create Stripe Bean (@ConditionalOnProperty)
Notification Service→notification.email.enabled=true → Create Email Sender
CertifyHub Health→Health Endpoint monitored by Kubernetes
Banking Application→Custom Health Check → Payment Gateway → Database → Redis
AWS Deployment→CloudWatch → Actuator Metrics → Auto Scaling
@PostConstruct→Load Country Cache
@PreDestroy→Close Kafka Producer
@Qualifier→Choose StripePaymentService over PaypalPaymentService
Development / Testing / Production→Local PostgreSQL + Debug → Test DB + Mocks → AWS RDS + INFO Logging + Redis
30. Top Interview One-Liner Revision
›Spring Boot → Opinionated Spring Framework
›IoC → Spring Creates Objects
›DI → Spring Injects Objects
›Bean → Object Managed By Spring
›ApplicationContext → Spring Container
›BeanFactory → Basic Container
›@SpringBootApplication → Main Boot Annotation
›Auto Configuration → Configure Beans Automatically
›Starter → Dependency Bundle
›Embedded Server → Built-in Server
›Spring Initializr → Project Generator
›DispatcherServlet → Front Controller
›@RestController → REST API
›ResponseEntity → Full HTTP Response
›DTO → Transfer Object
›Entity → Database Table
›Repository → Database Layer
›JPA → Specification
›Hibernate → JPA Implementation
›JPQL → Entity Query
›LAZY → Load On Demand
›EAGER → Load Immediately
›Fetch Join → Solve N+1
›EntityGraph → Optimized Fetch
›@Transactional → Commit / Rollback
›Propagation → Transaction Behavior
›Isolation → Data Visibility
›Optimistic Lock → @Version
›Pessimistic Lock → DB Lock
›Persistence Context → First Level Cache
›HikariCP → Connection Pool
›Validation → Prevent Bad Data
›@ControllerAdvice → Global Exception
›Spring Security → Authentication + Authorization
›JWT → Stateless Authentication
›BCrypt → Password Hashing
›OAuth2 → Authorization Framework
›OIDC → Authentication Layer
›Redis → Distributed Cache
›@Cacheable → Read Cache
›@Async → Background Thread
›MockMvc → Controller Testing
›Mockito → Mock Dependencies
›Testcontainers → Real Integration Tests
›Actuator → Monitoring
›DevTools → Development Productivity
›Executable JAR → Standalone Deployment
›WAR → External Server Deployment
›Graceful Shutdown → Safe Application Stop
›WebClient → Non-Blocking Client
›Feign → Declarative HTTP Client
›UUID → Distributed Unique ID
›Soft Delete → Logical Delete
›Audit Logging → Track Changes
›Idempotency → Same Request = Same Result
›Pagination → Large Data Handling
›Docker → Package Application
›Microservice → Independently Deployable Service
31. 15-Minute Final Revision Flow
Spring Boot → @SpringBootApplication → Auto Configuration
↓
Starter Dependencies → Embedded Server → SpringApplication.run()
↓
IoC → DI → Beans → Configuration → Profiles
↓
REST → DispatcherServlet → Jackson → DTO → Validation → Global Exception
↓
JPA → Hibernate → Repository → Transactions → Pagination → Sorting
↓
LAZY → N+1 → Fetch Join → Security → JWT → RBAC → BCrypt
↓
Cache → Redis → Async → JUnit → Mockito
↓
Actuator → HikariCP → DevTools → JAR vs WAR → Docker → Production
5–7 Years Interview Mantra — Interviewers Expect You To Explain
✓ Why, not just What ✓ Internal working of Spring Boot (Auto Configuration, Startup Flow)
✓ Real production issues you've faced & how you fixed them ✓ Performance optimization (N+1, Indexing, Caching)
✓ Transaction management (Propagation, Isolation, Locking) ✓ Security concepts (JWT, OAuth2, RBAC) with real examples
✓ JPA optimization & REST best practices ✓ Monitoring & deployment (Actuator, Docker, Zero Downtime)
✓ Trade-offs between approaches, with real project examples