Opinionated fmwk — auto-config, starters, embedded server
Spring MVC
Web layer — DispatcherServlet, Controllers
Spring Data JPA
Repository abstraction over JPA/Hibernate
Spring Security
AuthN + AuthZ, JWT/OAuth2, filter chain
Spring Cloud
Microservices — Feign, Gateway, Config Server
Spring Boot =Opinionated framework built on top of Spring — auto-configuration + starter dependencies + embedded server + production-ready features (Actuator) → minimal config, less boilerplate.
Starter PackageA predefined dependency-package management bundle containing the required libraries on classpath for a specific functionality.
@Configuration + @Bean@Bean return type is a Spring bean; used inside a config class to create & register a bean in the container — can override auto-configured beans.
@SpringBootApplication = Bootstraps the App
@SpringBootApplication
= @Configuration + @EnableAutoConfiguration + @ComponentScan — single entry-point annotation on main class.
@Configuration
Marks the class as a source of Spring bean definitions.
@EnableAutoConfiguration
Enables auto-config mechanism — auto-configures beans based on dependencies present on the classpath.
@ComponentScan
Scans the package for @Controller, @Service, @Repository, @Component and registers them as beans.
Spring IoC & Dependency Injection
IoC vs DI
IoC
Inversion of Control — the Spring Container manages object creation instead of the application code.
DI
Dependency Injection — an IoC principle; dependencies are injected by the container rather than created by the class itself.
Injection Types
Constructor ⭐
Recommended — immutable, mandatory deps, easy to unit test.
Setter
Optional dependencies; mutable.
Field (Avoid)
Hard to test, hides dependencies, not immutable.
@Autowired vs @Resource vs @Qualifier
@Autowired
Resolves byType → @Qualifier → Name
@Resource
Resolves byName → fallback: Type
@Qualifier / @Primary / @Lazy
@QualifierResolves multiple-bean ambiguity by name
@PrimaryDefault bean when multiple candidates exist
@LazyBean created only when first needed, not at startup
BeanFactory vs ApplicationContext
Feature
BeanFactory
ApplicationContext
Role
Basic IoC container
Extends BeanFactory + advanced features
Loading
Lazy
Eager (singleton beans)
Extras
—
Events, i18n, AOP integration
Get Bean Info
applicationContext.getBeanDefinitionNames(), getBeanDefinitionCount(), or hit /actuator/beans
Application Startup Lifecycle & DI Lifecycle
Startup Lifecycle
main()
→
SpringApplication.run()
→
Create ApplicationContext / IoC Container
→
Load Configuration (app.properties/yaml)
Component Scanning
→
Create Beans
→
Dependency Injection
→
Auto-Configuration from Classpath
Bean Initialization
→
AppContext Initialization
→
Embedded Tomcat Starts
→
Application Ready
DI LifecycleComponent Scan → Bean Creation → Dependency Resolution → Dependency Injection → Bean Ready for Use.
Bean Lifecycle & Scopes
Bean Lifecycle — object created, managed & destroyed by the Container
Container Start
→
Component Scan
→
Bean Creation
→
DI (Dependency Resolution)
→
@PostConstruct (Init)
→
Bean Ready
Application Running
→
@PreDestroy
→
Bean Destroyed
Component Scan → Bean Creation → Dependency Resolution → Dependency Injection → Bean Ready for Use
Bean Scopes
Singleton (default)
One bean per container.
Prototype
New bean every time it's requested.
Request
One bean per HTTP request.
Session
One bean per HTTP session.
Application
One bean per ServletContext.
WebSocket
One bean per WebSocket session.
Stereotype Annotations
@Component
Generic bean — Spring creates & manages its lifecycle in the IoC container.
@Service
Marks the business/service layer.
@Repository
Marks the DAO layer + enables exception translation.
Creates bean if a specific class is present on classpath.
@ConditionalOnMissingClass
Creates bean if a specific class is NOT present.
@ConditionalOnBean
Creates bean only if another bean is present.
@ConditionalOnMissingBean
Creates bean only if not already present — used to let users override auto-config.
@ConditionalOnProperty
Creates bean based on a configuration property value.
Exclude Auto-Configuration
// application.properties
spring.autoconfigure.exclude=DataSourceAutoConfiguration
// or on main class@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
Content NegotiationSend JSON or XML — whichever format the client requests.
Spring MVC & REST API
RESTREpresentational State Transfer — a web service communication style between client & server using HTTP methods (GET, POST, PUT, PATCH, DELETE).
Request Flow
Client
→
DispatcherServlet (Front Controller)
→
Controller
→
Service
→
Repository
→
Database
Response: Java Object → JSON via Jackson (HttpMessageConverter) → returned to client
HTTP Method Mapping Annotations
@GetMapping
Retrieve data.
@PostMapping
Create data.
@PutMapping
Update entire resource.
@DeleteMapping
Delete data.
@RequestMapping
Maps a URL to a controller class/handler method — e.g. @RequestMapping("/reports")
Parameter-Binding Annotations
@PathVariable
Extracts values from URL path — /users/102
@RequestParam
Extracts query params — /users?id=102; used for filter/search/sort/paginate.
@RequestBody
Converts JSON request body → Java Object.
@ModelAttribute
Binds form data / query params → Object.
ResponseEntity & HTTP Status Codes
ResponseEntity<T> — represents the complete HTTP response including headers, status code, message, and response body.
200 OK
Request processed successfully
201 Created
Resource created successfully
204 No Content
Successful, no response body
400 Bad Request
Invalid request from client
401 Unauthorized
Authentication required/failed
403 Forbidden
Access denied (authorization)
404 Not Found
Resource not found
409 Conflict
Resource state conflict
500 Internal Server Error
Unexpected server-side error
JSON Conversion & Validation
Handled automatically by HttpMessageConverter; default library = Jackson.
@JsonProperty rename field · @JsonIgnore exclude field · @JsonInclude conditional include · @JsonFormat date/time format
Validation:@NotBlank, @NotNull, @Email on DTO fields + @Valid on controller param triggers validation. Customize: @NotBlank(message="name is required")
Global Exception Handling
Custom Exception extends RuntimeException
→
@ControllerAdvice handles globally
→
@ExceptionHandler catches specific exception
→
Custom Error Response status, msg, timestamp, data
Default (no custom handler) → BasicErrorController returns Spring Boot's standard error response
Spring Data JPA & Relationships
JPA vs Hibernate vs Spring Data JPA
JPA
Hibernate
Spring Data JPA
Specification (rules/interfaces)
Implementation of JPA
Abstraction over JPA/Hibernate
Repository Hierarchy
Repository
→
CrudRepository
→
PagingAndSortingRepository
→
JpaRepository
Common methods: save()findById()findAll()deleteById()
CrudRepository vs JpaRepository
CrudRepository
JpaRepository
Basic CRUD ops only
Extends CRUD + pagination + sorting + batch ops
JPQL vs SQL
JPQL
SQL
Works on entities & fields
Works on tables & columns
Derived query methods — Spring builds the query from method naming convention. @Query — write custom JPQL/native SQL when derived methods aren't enough.
JPA Relationships & Fetch Strategy
@OneToOne
One entity ↔ exactly one entity. Ex: Employee ↔ AadhaarCard.
@OneToMany
One entity → many entities. Ex: Customer → Orders.
@ManyToOne
Many entities → one entity. Ex: Orders → Customer.
@ManyToMany
Many ↔ many. Ex: Students ↔ Courses.
Lazy ⭐Load related data only when accessed.
EagerLoad related data immediately with parent entity.
Cascade Types (parent op → propagates to child): PERSISTMERGEREMOVEALL
N+1 Query Problem
1 Query (Parent)
+
N Queries (Child, one per row)
Fetching N Departments triggers 1 query for departments + N queries for each department's employees
Identify & Fix
Identify: enable Hibernate SQL logs → look for 1 parent query followed by many repeated child queries.
Fix:Join Fetch (fetch parent+child in single query) · @EntityGraph (control which relations load together) · DTO Projection (select only required fields, avoids entity graph loading entirely)
PaginationPageable interface retrieves data in chunks, returns Page<T>. Sorting:Sort.by("name") or combined with Pageable. Benefits: better performance, less memory, faster APIs.
Transactions, ACID & @Transactional
ACID Properties
Atomicity
All or nothing — transaction fully completes or fully rolls back.
Consistency
Moves DB from one valid state to another, respecting all rules/constraints.
Isolation
Concurrent transactions execute without interfering with each other.
Durability
Once committed, data is permanently saved even after a crash.
@Transactional Internal Working
Request
→
Proxy w/ @Transactional
→
Starts Transaction
→
Execute Business Method
→
Commit (success) / Rollback (failure)
Rollback not happening? Check exception type (must be unchecked), ensure exception isn't swallowed, verify proxy-based behavior (self-invocation bypasses proxy!), configure rollbackFor for checked exceptions.
Propagation — how a method behaves when called by another transactional method
REQUIRED ⭐
Join existing or create new.
REQUIRES_NEW
Always create a new transaction (suspends outer one).
SUPPORTS
Join if exists, else run non-transactional.
MANDATORY
Transaction must already exist, else throws.
NOT_SUPPORTED
Suspends existing transaction, runs without one.
NEVER
Fails if a transaction exists.
NESTED
Transaction inside another, using savepoints.
Isolation Levels — what data a transaction can see
READ_UNCOMMITTED
Reads even uncommitted data (dirty read).
READ_COMMITTED ⭐
Reads only committed data.
REPEATABLE_READ
Same row always returns same value within txn.
SERIALIZABLE
One transaction at a time — safest, slowest.
Optimistic vs Pessimistic Locking
Optimistic Locking
MechanismUses @Version field to detect conflicts during update
Ex: Candidate ProfileAdmin A & B both read v1 → A saves → v2 → B saves with v1 → Hibernate throws OptimisticLockException
Pessimistic Locking
MechanismLocks DB row until current transaction completes — prevents conflict before update
Ex: Bank WithdrawalUser A withdraws → row locked → User B must wait → A completes → B reads updated balance
Caching
Cache Annotations
@EnableCaching
Enables caching in the app.
@Cacheable ⭐
Reads from cache; on miss, executes method & stores result.
@CachePut
Always executes method and updates the cache.
@CacheEvict
Removes specific / all cache entries.
@Caching
Combines multiple cache ops on one method.
Cache Providers
Redis ⭐
Distributed cache.
Caffeine
Local in-memory cache.
EhCache
Local in-memory cache.
Hazelcast
Distributed in-memory data grid.
Flow: first request → fetch from DB → store in cache → subsequent requests served from cache until invalidated/updated.
Spring Security, JWT & OAuth2
AuthenticationWho are you? Verifies identity — session, JWT, OTP.
AuthorizationWhat can you access? Restricts resources/actions for an authenticated user.
Authorization framework — grants access to resources via Access Token, without sharing credentials. Eg: Login with Google
Authentication layer on top of OAuth2 — adds an ID Token to authenticate the user. Eg: Sign in with Google
CSRF (Cross-Site Request Forgery)
Malicious site performs unwanted actions using an authenticated session. Spring Security validates a unique CSRF token on every state-changing request (POST/PUT/PATCH/DELETE). Default: enabled for session auth; usually disabled for JWT (stateless).
RBACRole-Based Access Control — assign roles to users, authorize via hasRole() (API level) or @PreAuthorize() (method level).
BCryptPassword hashing algorithm — converts plain-text passwords into irreversible encrypted hashes before storing in DB.
Custom Auth ProviderNeeded when the default provider isn't sufficient (default only checks username & password).
Symmetric vs Asymmetric Encryption
Symmetric
Asymmetric
Same key encrypts & decrypts. AES, DES, 3DES
Different keys — encrypt with public key, decrypt with private key. RSA, ECC
Storing Sensitive Data (e.g. account info)
Receive Data
→
Encrypt (AES-256)
→
Store Encrypted
→
Decrypt Only When Required
Design Patterns in Spring
Singleton
One bean per application context (IoC container).
Factory
Spring uses BeanFactory / ApplicationContext to create & manage bean objects.
Dependency Injection
IoC principle — Spring creates & injects dependent objects instead of the class doing it.
@AsyncRuns a method asynchronously on a separate thread — long-running tasks (email, file processing, external API calls) don't block the caller. Enable with @EnableAsync. Flow: save user in DB → return response → send email in background. Use cases: email, notifications, report generation.
Testing
Testing Types & Annotations
Unit Test
Tests a single component in isolation. Tools: JUnit 5, Mockito.
Integration Test
Tests multiple components together.
@WebMvcTest
Tests Controller layer only.
@DataJpaTest ⭐
Tests JPA repository layer; loads JPA layer only; uses H2 in-memory DB; rolls back after each test.
@SpringBootTest
Loads full ApplicationContext (real beans) — integration testing.
MockMvc
Tests Controller / REST endpoints without starting the web server.
@Mock / @InjectMocks
Mockito annotations to mock dependencies and inject them into the class under test.
Mocking External APIs & Testcontainers
Unit testing external calls → Mockito. Mocking external API server behavior → WireMock.
Testcontainers — runs real MySQL / Redis / PostgreSQL / Kafka in Docker for production-like integration testing.
BenefitsProduction-like testing · no H2-vs-real-DB behavior differences.
Microservices Communication & Kafka
RestTemplate vs WebClient vs OpenFeign
RestTemplate
Old / legacy, synchronous, blocking.
WebClient
Reactive, non-blocking — used in new applications.
OpenFeign ⭐
Declarative client for service-to-service calls in microservices.
Kafka — Async Communication
Producer
→
Topic
→
Consumer @KafkaListener
Consumer Group → scalability. Offset → message position tracking.
Performance Tuning & Connection Pooling
REST API Performance Tuning Checklist
1
Indexing
2
Pagination
3
Caching
4
DTO Projection
5
Fetch Join / Entity Graph
6
Async Processing
7
Connection Pool Tuning
8
Query Optimization
Connection Pooling — HikariCP ⭐ (default)
Pre-created DB connections reused by the app instead of opening a new one per request — borrow from pool, use, return.
Use idempotency keys, DB unique constraints, validation checks; return the already-processed response for duplicates.
Implementing audit logging / soft delete
Audit: capture user, action, timestamp, IP via AOP/service logging/JPA auditing. Soft delete: use a deleted flag + @SQLDelete + @Where to hide deleted rows.
16. (blank in notes)
Listed as item 16 in the source notes with no question/answer written yet — a placeholder to fill in.
Production Issues Faced — STAR-style Answers
Admit cards not generated post-payment
Traced Payment → Seat Confirmation → Admit Card flow; found admit-card service failing due to missing config. Fix: corrected config + regenerated pending admit cards via batch job.
Success: show success, send email/SMS, proceed to next step. Failure: show failure, allow retry (new payment attempt). Missed callback: a scheduled reconciliation job runs every 30 min, checks all PENDING txns via the gateway's Transaction Status API and finalizes their status.
Zero-Downtime Deployment
Blue-Green
Two identical envs; deploy to inactive, switch traffic after validation.
Rolling
Replace instances one by one, rest stay available.
Canary
Route small % of traffic to new version first, ramp up if healthy.