$ Spring Boot & Core Java — Revision Master
6–7 YOE Backend Engineer — Spring Core · Boot · MVC · Data JPA · Security · Microservices · Production Ops
// Read top-to-bottom once before every interview — annotations, flows, lifecycles, differences & real scenarios in one page
Spring Ecosystem Overview
Spring Core
IoC Container + DI — foundation of everything
Spring Boot
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 Package A 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.
@ConfigurationMarks the class as a source of Spring bean definitions.
@EnableAutoConfigurationEnables auto-config mechanism — auto-configures beans based on dependencies present on the classpath.
@ComponentScanScans the package for @Controller, @Service, @Repository, @Component and registers them as beans.
Spring IoC & Dependency Injection
IoC vs DI
IoCInversion of Control — the Spring Container manages object creation instead of the application code.
DIDependency 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.
SetterOptional 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
FeatureBeanFactoryApplicationContext
RoleBasic IoC containerExtends BeanFactory + advanced features
LoadingLazyEager (singleton beans)
ExtrasEvents, 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.
PrototypeNew bean every time it's requested.
RequestOne bean per HTTP request.
SessionOne bean per HTTP session.
ApplicationOne bean per ServletContext.
WebSocketOne bean per WebSocket session.
Stereotype Annotations
@ComponentGeneric bean — Spring creates & manages its lifecycle in the IoC container.
@ServiceMarks the business/service layer.
@RepositoryMarks the DAO layer + enables exception translation.
@ControllerHandles requests, returns a view (JSP/HTML).
@RestControllerHandles requests, returns JSON/XML data directly.
Spring Boot Auto-Configuration
Auto-Configuration Flow
@SpringBootApplication
@EnableAutoConfiguration
Reads spring.factories / AutoConfiguration.imports
Checks Classpath Deps
Finds @AutoConfiguration Classes
@Conditional Checks
Bean Creation
Stored in IoC Container
Application Ready
Conditional Annotations
@ConditionalOnClassCreates bean if a specific class is present on classpath.
@ConditionalOnMissingClassCreates bean if a specific class is NOT present.
@ConditionalOnBeanCreates bean only if another bean is present.
@ConditionalOnMissingBeanCreates bean only if not already present — used to let users override auto-config.
@ConditionalOnPropertyCreates bean based on a configuration property value.
Exclude Auto-Configuration
// application.properties spring.autoconfigure.exclude=DataSourceAutoConfiguration // or on main class @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
spring-boot-starter-parent
Parent POM — manages dependency versions, plugin configs & default build settings.
Configuration, Profiles & Embedded Server
Externalized Configuration
@ValueSingle property → @Value("${app.name}")
@ConfigurationPropertiesMultiple properties → @ConfigurationProperties(prefix="app")
EnvironmentDynamic access → environment.getProperty("app.name")
application.propertiesSimple key-value pairs.
application.ymlHierarchical structure — best for complex config.
Profiles & Embedded Server
Profiles — environment-specific config: dev, testing, prod. Activate with spring.profile.active=dev or class-level @Profile("dev").

Embedded server — default Tomcat; can override with Jetty/Undertow. To deploy on external server, package as WAR and remove embedded container.

Non-web app — Yes, disable via spring.main.web-application-type=none — used for batch jobs, scheduled tasks, CLI apps, Kafka consumers.
DevToolsAuto-restart on code change · LiveReload · dev-friendly settings.
ActuatorProduction-ready REST endpoints: /actuator/health, /metrics, /info, /beans. Custom endpoint via @Endpoint.
File UploadMultipartFile interface + @RequestParam.
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
@GetMappingRetrieve data.
@PostMappingCreate data.
@PutMappingUpdate entire resource.
@DeleteMappingDelete data.
@RequestMappingMaps a URL to a controller class/handler method — e.g. @RequestMapping("/reports")
Parameter-Binding Annotations
@PathVariableExtracts values from URL path — /users/102
@RequestParamExtracts query params — /users?id=102; used for filter/search/sort/paginate.
@RequestBodyConverts JSON request body → Java Object.
@ModelAttributeBinds 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 OKRequest processed successfully
201 CreatedResource created successfully
204 No ContentSuccessful, no response body
400 Bad RequestInvalid request from client
401 UnauthorizedAuthentication required/failed
403 ForbiddenAccess denied (authorization)
404 Not FoundResource not found
409 ConflictResource state conflict
500 Internal Server ErrorUnexpected 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
JPAHibernateSpring Data JPA
Specification (rules/interfaces)Implementation of JPAAbstraction over JPA/Hibernate
Repository Hierarchy
Repository
CrudRepository
PagingAndSortingRepository
JpaRepository
Common methods: save() findById() findAll() deleteById()
CrudRepository vs JpaRepository
CrudRepositoryJpaRepository
Basic CRUD ops onlyExtends CRUD + pagination + sorting + batch ops
JPQL vs SQL
JPQLSQL
Works on entities & fieldsWorks 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
@OneToOneOne entity ↔ exactly one entity. Ex: Employee ↔ AadhaarCard.
@OneToManyOne entity → many entities. Ex: Customer → Orders.
@ManyToOneMany entities → one entity. Ex: Orders → Customer.
@ManyToManyMany ↔ 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): PERSIST MERGE REMOVE ALL
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_NEWAlways create a new transaction (suspends outer one).
SUPPORTSJoin if exists, else run non-transactional.
MANDATORYTransaction must already exist, else throws.
NOT_SUPPORTEDSuspends existing transaction, runs without one.
NEVERFails if a transaction exists.
NESTEDTransaction inside another, using savepoints.
Isolation Levels — what data a transaction can see
READ_UNCOMMITTEDReads even uncommitted data (dirty read).
READ_COMMITTED ⭐Reads only committed data.
REPEATABLE_READSame row always returns same value within txn.
SERIALIZABLEOne 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
@EnableCachingEnables caching in the app.
@Cacheable ⭐Reads from cache; on miss, executes method & stores result.
@CachePutAlways executes method and updates the cache.
@CacheEvictRemoves specific / all cache entries.
@CachingCombines multiple cache ops on one method.
Cache Providers
Redis ⭐Distributed cache.
CaffeineLocal in-memory cache.
EhCacheLocal in-memory cache.
HazelcastDistributed 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.
Security Filter Chain Flow
Client Request
SecurityFilterChain
Auth Filter → AuthZ Filter → CSRF/CORS
Controller
Service
Repository
DB
Response
JWT — Stateless Authentication
Compact, URL-safe token: Header.Payload.Signature

Header: token type + signing algorithm (HS256/RS256)
Payload: claims — userId, username, roles, iat, exp, sub
Signature: crypto signature of header+payload using secret/private key
Login
Validate Creds
Generate JWT
Return Token
Subsequent requests: Authorization: Bearer <token>
OAuth2 vs OpenID Connect vs CSRF
OAuth2OpenID Connect
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
SymmetricAsymmetric
Same key encrypts & decrypts. AES, DES, 3DESDifferent 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
SingletonOne bean per application context (IoC container).
FactorySpring uses BeanFactory / ApplicationContext to create & manage bean objects.
Dependency InjectionIoC principle — Spring creates & injects dependent objects instead of the class doing it.
ProxyUsed behind @Transactional, @Cacheable, @Async.
TemplateJdbcTemplate, KafkaTemplate — boilerplate abstraction.
ObserverSpring Application Events.
MVCController → Service → Repository separation.
Async Processing
@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 TestTests a single component in isolation. Tools: JUnit 5, Mockito.
Integration TestTests multiple components together.
@WebMvcTestTests Controller layer only.
@DataJpaTest ⭐Tests JPA repository layer; loads JPA layer only; uses H2 in-memory DB; rolls back after each test.
@SpringBootTestLoads full ApplicationContext (real beans) — integration testing.
MockMvcTests Controller / REST endpoints without starting the web server.
@Mock / @InjectMocksMockito 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
RestTemplateOld / legacy, synchronous, blocking.
WebClientReactive, 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
1Indexing
2Pagination
3Caching
4DTO Projection
5Fetch Join / Entity Graph
6Async Processing
7Connection Pool Tuning
8Query 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.
spring.datasource.hikari.maximum-pool-size=20 spring.datasource.hikari.minimum-idle spring.datasource.hikari.connection-timeout spring.datasource.hikari.idle-timeout spring.datasource.hikari.max-lifetime
Production Monitoring
Application
API response time, throughput (TPS/RPS), error rate (4xx/5xx), latency.
JVM
Heap / non-heap memory, GC, thread count, CPU.
Database
Slow queries, pool usage, active connections, deadlocks.
Infrastructure
CPU, memory, disk, network, container/VM health.
Business
Successful/failed payments, bookings, certificate generation.
ToolsActuator · Prometheus · Grafana · ELK stack.
Most Asked Differences (Master Table)
Topic ATopic BKey Difference
CrudRepositoryJpaRepositoryBasic CRUD only vs CRUD + pagination & sorting
JPQLSQLEntities/fields vs tables/columns
AuthenticationAuthorizationVerify identity vs permitted actions/resources
@Resource@AutowiredInjects by Name→Type vs Type→Qualifier→Name
Starter DependenciesManual Dependency MgmtPredefined bundled deps (e.g. spring-boot-starter-web) vs developer adds/maintains each lib (e.g. jjwt-api)
@Configuration@ComponentDefines/manages beans via @Bean vs creates a Spring-managed bean itself
BeanFactoryApplicationContextBasic IoC container vs extends it + advanced features
JPAHibernate / Spring Data JPASpecification vs Implementation vs Abstraction layer
Optimistic LockingPessimistic LockingDetect conflict via @Version vs prevent conflict via DB lock
@Valid@ValidatedBasic bean validation vs adds validation groups + method-level validation
@RequestBody@ModelAttributeJSON → Object (Jackson) vs Form/query params → Object
@Controller@RestControllerReturns a view vs returns JSON/XML directly
CommandLineRunnerApplicationRunnerRaw String[] args vs typed ApplicationArguments API
MVCREST APIReturns views (JSP/HTML) via @Controller vs returns data (JSON/XML) via @RestController
GETPOSTRetrieve (idempotent, no body needed) vs create resource (has body)
PUTPATCHReplace entire resource vs partial update
JWTOAuth2Token format/mechanism for stateless auth vs a full authorization framework/protocol
OAuth2OpenID ConnectAuthorization only (access token) vs adds authentication (ID token) on top
Eager LoadingLazy LoadingLoads related data immediately vs only when accessed
@Cacheable@CacheEvictReads/populates cache vs removes cache entries
Singleton ScopePrototype ScopeOne bean per container vs new bean on every request
MonolithMicroservicesSingle deployable unit vs independently deployable services
save()saveAndFlush()— listed in notes as a topic to revise, no detail written yet —
Fetch JoinEntity GraphJPQL-level join to fetch parent+child in one query vs declarative annotation controlling which associations load eagerly per query
Real-World Troubleshooting Scenarios
Multiple beans of same type — app fails to start
Spring throws NoUniqueBeanDefinitionException. Fix with @Qualifier, mark one @Primary, or inject by bean name.
API randomly returns 401/403
Determine 401 (Authentication) vs 403 (Authorization). Verify JWT token, roles/permissions, Security config, token expiry, headers, logs.
DB connection pool suddenly exhausted
Check logs + pool metrics. Root causes: connection leaks, slow queries, long transactions, traffic spike. Fix: optimize queries, release connections, tune HikariCP, scale.
Memory usage keeps increasing
Determine leak vs normal growth. Monitor JVM heap, GC logs, heap dump. Fix: leaks, unclosed resources, large caches, excessive object creation.
Users still see old behavior after deployment
Verify new version deployed, app restarted, caches refreshed, correct profile active, load balancer routing to updated instances.
Logs missing in production
Check logging config, log level, file path, permissions, active profile, log rotation, forwarding to centralized logging.
Inconsistent REST API response time
Investigate slow DB queries, external calls, thread/connection contention, GC pauses, network latency. Use APM tools, SQL plans, JVM metrics.
Works locally, fails in production
Check logs, environment config, DB connectivity, dependencies, external services, server resources.
Changed application.properties — no effect in prod
Check app restarted, correct file used, env vars overriding properties, correct profile active, latest build actually deployed.
High traffic crash despite low CPU
Likely connection/thread pool exhaustion, memory issues, blocked threads, slow external APIs. Analyze thread dumps, heap, pools, dependencies.
Handling duplicate API requests / idempotency
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.
Admin reports loading very slowly
Analyzed SQL — found missing indexes & unnecessary joins. Fix: added indexes, optimized queries, added pagination. Result: 30s → 2s.
Candidate approval screens slow (N+1)
Enabled Hibernate SQL logs, found N+1 while loading candidate documents. Fix: Join Fetch / Entity Graph.
Payment deducted but seat not booked
Seat booking service timed out after payment succeeded. Fix: retry mechanism + reconciliation job + compensation handling.
Seats shown available though all booked
Concurrent bookings updated seat counts incorrectly. Fix: transaction management + optimistic locking.
System Design — Payment Gateway Integration
User Clicks "Proceed"
Create Order + Payment Record (PENDING)
Redirect to Gateway (SBI ePay / ICICI Eazypay / Razorpay / Stripe / PayU)
User Makes Payment
Gateway Sends Callback/Webhook
Verify Signature & Validate Response
Update Payment Status & Complete Order
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.
K8s Rolling Update
Pods replaced gradually, desired healthy-pod count maintained.
Open Q"Application behaves differently in Docker than locally. Why?" — listed in notes as a question to prepare, no answer written yet.
30-Second Spring Boot Summary
Spring Boot = IoC + DI + Auto-Configuration + Starter Dependencies
Flow: Client → Controller → Service → Repository → Database
Security: Authentication + Authorization + JWT
Performance: Pagination + Caching + Indexing + HikariCP
JPA: Hibernate + JpaRepository + Transactions
Testing: JUnit + Mockito + Testcontainers
Microservices: OpenFeign + Kafka + API Gateway
@ConfigurationPropertiesScan — scans & registers @ConfigurationProperties beans
SLF4J — logging facade used across the app
Content Negotiation — serve JSON or XML based on client Accept header