Spring Interview Playbook

 

1️⃣ Core Spring


What is Spring Framework?

Answer:

  • Lightweight, open-source Java framework for enterprise applications

  • Based on IoC (Inversion of Control) and DI (Dependency Injection)

  • Promotes loose coupling and testability

  • Modular architecture (Core, AOP, JDBC, ORM, MVC, Security)

  • Eliminates heavy XML configuration (supports annotations & Java config)

Real-time example:

  • In a banking app → Service layer depends on Repository

  • Spring injects repository into service automatically


What is Inversion of Control (IoC)?

Answer:

  • Control of object creation is given to Spring container

  • Developer no longer uses new keyword for dependencies

  • Container manages:

    • Bean creation

    • Dependency wiring

    • Lifecycle

    • Configuration

Without IoC:

UserService service = new UserService();

With IoC:

@Autowired
UserService service;

Real-time example:

  • Large e-commerce app → 200+ services

  • IoC avoids manual object creation chaos


What is Dependency Injection (DI)?

Answer:

  • Technique to inject required dependencies into a class

  • Achieves loose coupling

  • Makes unit testing easier

Types of DI

  • Constructor Injection (Recommended)

  • Setter Injection

  • Field Injection (Avoid in production)

Why Constructor Injection?

  • Makes dependencies mandatory

  • Supports immutability

  • Easy for unit testing (Mockito)

Example:

@Service
class OrderService {
private final PaymentService paymentService;

public OrderService(PaymentService paymentService) {
this.paymentService = paymentService;
}
}

Real-time example:

  • OrderService depends on PaymentService

  • Spring injects automatically


What is a Spring Bean?

Answer:

  • Any object managed by Spring IoC container

  • Created, configured, and destroyed by container

Ways to define beans

  • @Component

  • @Service

  • @Repository

  • @Controller

  • @Bean (Java config)

  • XML configuration (legacy)

Real-time example:

  • UserService

  • EmailService

  • ProductRepository


What is Spring Bean Scopes?

Spring defines lifecycle and visibility of beans.


1. Singleton (Default)

  • One instance per Spring container

  • Shared across entire application

  • Thread-safe design required

Used in:

  • Service layer

  • DAO layer

  • Utility classes

Example:

@Scope("singleton")
@Service
class UserService {}

Real-time:

  • PaymentService shared by all users


2. Prototype

  • New object every time requested

  • Spring manages creation only (not destruction)

  • Suitable for stateful objects

Used in:

  • Report generator

  • Temporary calculation objects

@Scope("prototype")
@Component
class ReportBuilder {}

3. Request Scope (Web Apps)

  • One bean per HTTP request

  • Destroyed after request completes

Used in:

  • Request-specific form data

  • API request context


4. Session Scope

  • One bean per HTTP session

  • Lives until session expires

Used in:

  • Shopping cart

  • Logged-in user details


5. Application Scope

  • One per ServletContext

  • Shared across entire web application

Used in:

  • Application cache

  • Global settings


6. WebSocket Scope

  • One bean per WebSocket session

  • Used in chat applications


Scope Interview Follow-up Points

  • Singleton is NOT same as GoF Singleton

  • Singleton beans must be stateless

  • Prototype injected into Singleton → creates problem (use ObjectFactory)


What is @Component, @Service, @Repository, @Controller?

Answer:

All are stereotype annotations.

  • @Component → Generic bean

  • @Service → Business logic

  • @Repository → DAO (adds exception translation)

  • @Controller → MVC controller

Real-time:

  • Layered architecture separation


What is @Autowired?

Answer:

  • Automatically injects dependency

  • Works on constructor, setter, field

  • By default injects by type

  • Use @Qualifier if multiple beans

Example:

@Autowired
@Qualifier("stripePayment")
PaymentService paymentService;

What is Spring AOP?

Answer:

Aspect-Oriented Programming separates cross-cutting concerns.

Cross-cutting concerns:

  • Logging

  • Security

  • Transaction management

  • Monitoring

Key Terms:

  • Aspect → LoggingAspect

  • Advice → Before, After, Around

  • JoinPoint → Method execution

  • Pointcut → Expression

Example:

@Aspect
@Component
class LoggingAspect {
@Before("execution(* com.app.service.*.*(..))")
public void log() {
System.out.println("Method called");
}
}

Real-time:

  • Logging every service method without modifying code


What is Bean Lifecycle?

Phases:

  1. Bean instantiation

  2. Dependency injection

  3. @PostConstruct

  4. Ready for use

  5. @PreDestroy

  6. Destroy

Customization:

  • InitializingBean

  • DisposableBean

Real-time:

  • Opening DB connection on init

  • Closing resources on destroy


What is BeanFactory vs ApplicationContext?

Both are Spring IoC containers, but ApplicationContext is a more advanced version of BeanFactory.


BeanFactory

  • Basic IoC container

  • Responsible for:

    • Bean creation

    • Dependency injection

  • Beans loaded lazily (created only when requested)

  • Does NOT support:

    • Automatic AOP integration

    • Event publishing

    • Internationalization (i18n)

  • Lightweight and minimal

Example

BeanFactory factory =
new XmlBeanFactory(new ClassPathResource("beans.xml"));

MyService service = factory.getBean(MyService.class);

Used rarely in modern applications.


ApplicationContext

  • Advanced container (extends BeanFactory)

  • Provides all BeanFactory features +

    • AOP support

    • Event handling

    • Internationalization (MessageSource)

    • Environment & profiles

    • Annotation-based configuration

  • Beans loaded eagerly by default (singleton beans at startup)

  • Fully integrated with Spring Boot

Example

ApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);

MyService service = context.getBean(MyService.class);

Comparison Table

BeanFactoryApplicationContext
Basic IoC containerAdvanced container
Lazy loadingEager loading (default)
No built-in AOPSupports AOP
No event systemSupports events
Minimal featuresEnterprise-ready features

Real-Time Usage

  • ApplicationContext is used in almost all real-world applications.

  • Spring Boot automatically creates an ApplicationContext.

  • BeanFactory is mostly for:

    • Memory-constrained environments

    • Understanding core IoC concepts


Summary

BeanFactory is the basic container with lazy loading.
ApplicationContext extends BeanFactory and adds enterprise features like AOP, events, profiles, and is used in almost all real applications.


What is @Configuration and @Bean?

Answer:

  • @Configuration → Marks config class

  • @Bean → Defines custom bean

Example:

@Configuration
class AppConfig {

@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
}

Real-time:

  • Third-party libraries as beans


What is Circular Dependency?

Answer:

A circular dependency occurs when:

  • Bean A depends on Bean B

  • Bean B depends on Bean A

This creates a dependency cycle.


Example (Constructor Injection – Fails)

@Service
class A {
private final B b;

public A(B b) {
this.b = b;
}
}

@Service
class B {
private final A a;

public B(A a) {
this.a = a;
}
}

Result:

  • Spring tries to create A → needs B

  • To create B → needs A

  • Fails with BeanCurrentlyInCreationException


Setter Injection – Works (Not Recommended)

@Service
class A {
private B b;

@Autowired
public void setB(B b) {
this.b = b;
}
}

@Service
class B {
private A a;

@Autowired
public void setA(A a) {
this.a = a;
}
}

Why it works:

  • Spring first creates beans without dependencies

  • Injects dependencies afterward

  • Breaks creation cycle

Why not recommended:

  • Hides poor design

  • Allows partially initialized beans

  • Encourages tight coupling

  • Makes dependencies optional (not enforced)


Proper Solution (Refactor Design)

Instead of A and B depending on each other, extract common logic into a third service.

Refactored Design

@Service
class CommonService {
}

@Service
class A {
private final CommonService commonService;

public A(CommonService commonService) {
this.commonService = commonService;
}
}

@Service
class B {
private final CommonService commonService;

public B(CommonService commonService) {
this.commonService = commonService;
}
}

Now:

  • A → CommonService

  • B → CommonService

  • No circular dependency


Interview Summary

  • Circular dependency = two beans depend on each other

  • Constructor injection fails

  • Setter injection works but is bad design

  • Best solution → redesign architecture and remove tight coupling


What is Profiles in Spring?

Answer:

  • Used for environment-specific configuration

  • Allows different beans and properties to be loaded based on the active environment

  • Helps separate configuration without changing code

  • Common real-time environment names:

    • local

    • dev

    • qa

    • uat

    • staging

    • prod

Example Using @Profile

@Profile("dev")
@Component
class DevDataSource {
}

@Profile("prod")
@Component
class ProdDataSource {
}

Only the bean matching the active profile will be loaded.

How to Activate Profile

In application.properties

spring.profiles.active=dev

Or via command line

--spring.profiles.active=prod

Profile-Specific Property Files

  • application-local.properties

  • application-dev.properties

  • application-qa.properties

  • application-uat.properties

  • application-staging.properties

  • application-prod.properties

Spring automatically loads the correct file based on the active profile.

Real-Time Example

  • local → Developer machine DB

  • dev → Shared development database

  • qa → QA testing database

  • uat → User acceptance testing environment

  • staging → Pre-production environment

  • prod → Production database

Interview Summary

Profiles allow loading environment-specific beans and configurations such as database URLs, logging levels, API keys, and feature flags without modifying application code.


What is @Value and @PropertySource?

Answer:

  • Used to inject values from properties files

  • @Value → Injects a specific property value

  • @PropertySource → Loads external/custom property files into Spring context

Example using @Value

@Value("${server.port}")
private int port;

Injecting custom property:

@Value("${app.name}")
private String appName;

Example using @PropertySource

@Configuration
@PropertySource("classpath:custom.properties")
class AppConfig {
}

This loads custom.properties so values can be injected using @Value.


Used In

  • Database configuration

  • API keys

  • External service URLs

  • Feature flags

Interview Summary

@Value is used to inject individual property values, while @PropertySource is used to load additional properties files into the Spring application context.


What is Environment Abstraction?

Answer:

  • Provides access to application properties

  • Gives access to active profiles

  • Allows reading system environment variables

  • Supports checking default profiles

  • Helps implement environment-based logic

Spring provides the Environment interface for this.


Example using Environment

@Autowired
private Environment env;

Read property

String dbUrl = env.getProperty("spring.datasource.url");

Get active profiles

String[] profiles = env.getActiveProfiles();

Get default profiles

String[] defaultProfiles = env.getDefaultProfiles();

Read system environment variable

String javaHome = env.getProperty("JAVA_HOME");

Check if profile is active

if (env.acceptsProfiles("prod")) {
System.out.println("Production environment");
}

Used In

  • Dynamic configuration access

  • Profile-based conditional logic

  • Reading OS environment variables

  • Feature toggles based on environment


Interview Summary

Environment abstraction allows accessing properties, profiles, and system variables programmatically using the Environment interface, enabling environment-aware application behavior.


What is Lazy Initialization?

Answer:

  • @Lazy → Bean is created only when it is first requested

  • Default singleton beans are created eagerly at startup

  • Helps reduce application startup time

  • Useful for heavy or rarely used beans

Example using @Lazy

@Lazy
@Service
class HeavyService {
}

Bean will be created only when it is first injected or accessed.

Using @Lazy on Injection

@Service
class OrderService {

private final HeavyService heavyService;

public OrderService(@Lazy HeavyService heavyService) {
this.heavyService = heavyService;
}
}

Here, HeavyService is initialized only when actually used.

Used In

  • Expensive initialization logic

  • Large configuration objects

  • Rarely used services

  • Improving startup performance

Interview Summary

Lazy initialization delays bean creation until it is needed, helping optimize startup time and resource usage.


What is difference between @Primary and @Qualifier?

Answer:

  • @Primary → Marks a bean as the default choice when multiple beans of the same type exist

  • @Qualifier → Explicitly specifies which bean to inject

Used when multiple implementations of the same interface are present.

Example Scenario

public interface PaymentService {
void pay();
}

Two Implementations

@Service
@Primary
class StripePaymentService implements PaymentService {
public void pay() {}
}

@Service
class PaypalPaymentService implements PaymentService {
public void pay() {}
}

Injection Without Qualifier

@Autowired
private PaymentService paymentService;

Here, StripePaymentService will be injected because it is marked with @Primary.

Using @Qualifier

@Autowired
@Qualifier("paypalPaymentService")
private PaymentService paymentService;

Here, PaypalPaymentService will be injected explicitly.


When to Use

  • @Primary → When one implementation should act as default

  • @Qualifier → When you need specific implementation


Interview Summary

@Primary defines the default bean among multiple candidates, while @Qualifier allows explicit selection of a specific bean during injection.


What is @Conditional annotation?

Answer:

  • Creates a bean only if a specific condition is satisfied

  • Used heavily in Spring Boot auto-configuration

  • Enables conditional bean registration

  • Helps build flexible and modular configuration

Common Conditional Annotations

  • @ConditionalOnProperty → Loads bean if property exists or has specific value

  • @ConditionalOnClass → Loads bean if a class is present in classpath

  • @ConditionalOnMissingBean → Loads bean only if no other bean of same type exists

  • @ConditionalOnBean → Loads bean only if another bean exists

Example using @ConditionalOnProperty

@Configuration
class FeatureConfig {

@Bean
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
public FeatureService featureService() {
return new FeatureService();
}
}

application.properties:

feature.enabled=true

Bean loads only if property is true.

Example using @ConditionalOnClass

@Configuration
@ConditionalOnClass(name = "com.mysql.cj.jdbc.Driver")
class MySqlConfig {
}

Loads only if MySQL driver is available.


Used For

  • Feature toggling

  • Optional modules

  • Auto-configuration logic

  • Environment-based bean loading

Interview Summary

@Conditional annotations allow beans to be created only when certain conditions are met, widely used in Spring Boot’s auto-configuration and feature toggling.


Common Core Spring Interview Scenarios

What are the thread-safety concerns with Singleton beans and how to keep them stateless?

  • Singleton beans are shared across multiple threads and are not thread-safe by default.

  • Problem occurs when mutable instance variables are used.
    Bad example:

@Service
class CounterService {
private int count = 0;
public void increment() { count++; }
}

This causes race conditions.
Correct (stateless) example:

@Service
class CounterService {
public int increment(int count) { return count + 1; }
}

Here no shared mutable state exists, making it thread-safe.

What happens when a Prototype bean is injected into a Singleton bean?

  • Prototype bean is created only once during injection.

  • Same instance reused inside singleton.

Solution 1: Using ObjectProvider
@Service
class A {
@Autowired
private ObjectProvider<B> provider;
public void useB() {
B b = provider.getObject();
}
}

Solution 2: Using Provider (JSR-330)

@Service
class A {
@Autowired
private javax.inject.Provider<B> provider;
public void useB() {
B b = provider.get();
}
}

Solution 3: Using @Lookup method injection

@Service
abstract class A {
public void useB() {
B b = getB();
}
@Lookup
protected abstract B getB();
}

Each call returns a new prototype instance.

Why is constructor injection preferred?

  • Makes dependencies mandatory.

  • Supports immutability.

  • Easier for unit testing.

  • Detects circular dependency early.


What is the difference between @Component and @Bean?

@Component

  • Auto-detected through component scanning (@ComponentScan)

  • Used for application-level classes like @Service, @Repository, @Controller

  • Spring automatically instantiates and manages the bean

  • Best for classes you own and can annotate

@Bean

  • Declared inside a @Configuration class

  • Used for third-party classes or when you cannot modify the source code

  • Provides fine-grained control — you explicitly define how the object is created, configured, initialized, and customized before registering it as a Spring bean

Example

@Configuration
class AppConfig {

@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.findAndRegisterModules();
return mapper;
}
}

Interview Summary

Use @Component for your own classes.
Use @Bean when you need manual control or for external libraries.


What are proxies and how does Spring create proxies for AOP?

Answer:

  • A proxy is a wrapper object created by Spring around your actual bean.

  • It intercepts method calls and adds extra behavior like:

    • Transactions

    • Logging

    • Security

    • Caching

The original object is called the target, and Spring returns the proxy instead of the real object.

How Spring Creates Proxies

Spring uses two mechanisms:

  • JDK Dynamic Proxy → Used when the class implements an interface

  • CGLIB (Code Generation Library) → Used when no interface is present (creates subclass at runtime)

You can force CGLIB:

spring.aop.proxy-target-class=true

Proxy Flow

Client → Proxy → (Advice Applied) → Target Method

Example with @Transactional:

@Transactional
public void transfer() {
// business logic
}

Flow:

  1. Client calls transfer()

  2. Proxy starts transaction

  3. Target method executes

  4. Proxy commits or rolls back

Simple Interview Definition

Spring creates proxy objects around beans to intercept method calls and apply cross-cutting concerns like transactions and logging using JDK dynamic proxies or CGLIB.


How does @Transactional work internally?

  • Spring creates a proxy around the bean.

  • When method is called, proxy:

    • Starts transaction.

    • Executes method.

    • Commits if successful.

    • Rolls back if RuntimeException occurs.
      Simple flow:
      Call method → Proxy starts transaction → Business logic runs → Commit/Rollback.


What happens if @Transactional is missing?

  • No transaction boundary.

  • Partial updates possible.

  • Risk of inconsistent database state.


Interview Summary

These topics test understanding of Spring internals like proxy mechanism, transaction flow, dependency injection behavior, thread safety, and real-world production design practices.


Core Spring Summary

Core Spring focuses on:

  • IoC container

  • Dependency Injection

  • Bean lifecycle

  • AOP

  • Scopes

  • Configuration management

  • Environment abstraction





2️⃣ Spring MVC 


What is Spring MVC?

Answer:

  • A web framework based on Model-View-Controller pattern

  • Built on top of Spring Core

  • Used to build web applications and REST APIs

  • Handles HTTP requests and responses

MVC Components:

  • Model → Data (DTO, Entity)

  • View → UI (JSP, Thymeleaf) or JSON

  • Controller → Handles requests

Real-time example:

  • E-commerce site

    • Controller → Handles /products

    • Service → Fetches products

    • View → Displays products page or JSON


What is DispatcherServlet?

Answer:

  • Front Controller in Spring MVC

  • Handles all incoming HTTP requests

  • Delegates to appropriate controller

Flow:

  1. Client sends request

  2. DispatcherServlet receives

  3. Finds handler using HandlerMapping

  4. Calls controller

  5. Returns response

Real-time example:

  • All API calls like /login, /users, /orders go through DispatcherServlet


What is @Controller?

Answer:

  • Marks a class as MVC Controller

  • Returns View name by default

  • Used in traditional MVC apps

@Controller
public class HomeController {

@GetMapping("/home")
public String home() {
return "home"; // home.jsp
}
}

What is @RestController?

Answer:

  • Combination of:

    • @Controller

    • @ResponseBody

  • Returns JSON/XML instead of View

@RestController
public class UserController {

@GetMapping("/users")
public List<User> getUsers() {
return userService.getAll();
}
}

Real-time example:

  • Microservices returning JSON responses


Difference between @Controller and @RestController?

@Controller@RestController
Returns View name (JSP/Thymeleaf)Returns JSON or XML directly
Used in traditional MVC appsUsed in REST APIs / Microservices
Needs @ResponseBody for JSON@ResponseBody applied automatically
Mostly used in monolithic web appsCommon in distributed systems / SOA / Microservices

Example using @Controller

@Controller
public class HomeController {

@GetMapping("/home")
public String home() {
return "home"; // resolves to home.jsp or home.html
}
}

Returns a view name, not JSON.

Example using @RestController

@RestController
public class UserController {

@GetMapping("/users")
public List<String> getUsers() {
return List.of("A", "B");
}
}

Returns JSON response directly.

Key Point

@RestController = @Controller + @ResponseBody

Interview Summary

Use @Controller for server-side rendered web applications.
Use @RestController for REST APIs, distributed environments, SOA, and microservices where JSON/XML responses are required.


What is @RequestMapping?

  • Used to map HTTP requests to controller methods

  • Can be applied at class level and method level

  • Defines URL path and HTTP method

Common variants:

  • @GetMapping

  • @PostMapping

  • @PutMapping

  • @DeleteMapping

  • @PatchMapping

Example – Class Level Mapping

@RestController
@RequestMapping("/api")
class UserController {
}

Base URL becomes: /api

Example – Method Level Mapping

@RestController
class UserController {

@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return new User(id, "John");
}
}

URL becomes: /users/{id}

Example – Class + Method Level Combined

@RestController
@RequestMapping("/api")
class UserController {

@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return new User(id, "John");
}
}

Final URL: /api/users/{id}

Interview Summary: @RequestMapping maps a URL and HTTP method to a specific controller method in Spring MVC or REST APIs.


What is @PathVariable?

  • Extracts value from the URL path

  • Binds URI template variable to method parameter

  • Used to identify specific resource

Example request:
GET /users/10

Example code:

@GetMapping("/users/{id}")
public User get(@PathVariable Long id) {
return new User(id, "John");
}

Used for:

  • Resource identification

  • RESTful APIs

  • Accessing specific entity by ID

Interview Summary: @PathVariable is used to capture dynamic values from the URL path and bind them to method parameters.


What is @RequestParam?

  • Extracts query parameter from URL

  • Binds request parameter to method argument

  • Used for optional or additional data

Example request:
GET /users?id=10

Example code:

@GetMapping("/users")
public User get(@RequestParam Long id) {
return new User(id, "John");
}

Used for:

  • Filtering

  • Pagination

  • Sorting

  • Optional parameters

Interview Summary: @RequestParam is used to capture query parameters from the URL and bind them to controller method parameters.


What is @RequestBody?

  • Maps HTTP request body to a Java object

  • Converts JSON/XML into Java object using HttpMessageConverter (Jackson by default)

  • Commonly used in POST and PUT APIs

Example:

@PostMapping("/users")
public User create(@RequestBody User user) {
return user;
}

Example JSON request body:

{
"id": 1,
"name": "John"
}

Real-time usage:

  • Creating a new user via JSON payload

  • Updating existing records

  • Sending complex request data from frontend

Interview Summary: @RequestBody binds incoming JSON/XML request data to a Java object in REST APIs.


What is @ResponseBody?

  • Converts the return value of a method into JSON or XML

  • Uses HttpMessageConverters (Jackson by default for JSON)

  • Writes response directly to HTTP response body instead of returning a view

  • Automatically included when using @RestController

Example:

@Controller
public class UserController {

@GetMapping("/users")
@ResponseBody
public User getUser() {
return new User(1L, "John");
}
}

Interview Summary: @ResponseBody tells Spring to serialize the returned object into JSON/XML and send it directly in the HTTP response.


What is HttpMessageConverter?

  • Converts Java object → JSON/XML

  • Converts JSON/XML → Java object

  • Works between HTTP request/response and controller methods

  • Uses Jackson library by default for JSON

Example:

@GetMapping("/users")
public User getUser() {
return new User(1L, "John");
}

Spring automatically converts the User object into JSON in the HTTP response.

For request body:

@PostMapping("/users")
public User create(@RequestBody User user) {
return user;
}

Spring converts incoming JSON into a User object.

Real-time usage:

  • Automatically serializes objects to JSON in REST APIs

  • Converts frontend JSON payload into Java objects

Interview Summary: HttpMessageConverter interface handles automatic conversion between Java objects and HTTP request/response formats like JSON or XML.

What is ResponseEntity?

  • A Spring class used to represent the entire HTTP response

  • Allows control over:

    • HTTP status code

    • Response headers

    • Response body

  • Mainly used in REST APIs

  • It is a class in Spring (org.springframework.http.ResponseEntity)


Example – Return with Status 200

@GetMapping("/users/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
User user = new User(id, "John");
return ResponseEntity.ok(user);
}

Example – Return Custom Status

@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user) {
return ResponseEntity
.status(HttpStatus.CREATED)
.body(user);
}

Returns → HTTP 201 Created


Example – Return Custom Header

@GetMapping("/users")
public ResponseEntity<User> getUser() {
User user = new User(1L, "John");
return ResponseEntity
.ok()
.header("X-App-Version", "1.0")
.body(user);
}

Response includes custom header:
X-App-Version: 1.0


Example – Return Only Status

@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
return ResponseEntity.noContent().build();
}

Returns → HTTP 204 No Content


Interview Summary

ResponseEntity gives full control over HTTP response including body, headers, and status code, making it ideal for building proper REST APIs.

What is Model, ModelMap, and ModelAndView?

  • Used in traditional Spring MVC (server-side rendering)

  • Used to pass data from controller to view (JSP/Thymeleaf)

Model

  • Stores data for the view

  • Simple interface

model.addAttribute("name", "Siraj");

ModelMap

  • Similar to Model

  • Backed by a Map structure

  • Allows key-value storage

modelMap.addAttribute("name", "Siraj");

ModelAndView

  • Combines model data + view name

  • Returns both in single object

return new ModelAndView("home", "name", "Siraj");

Used in:

  • Traditional MVC applications (JSP, Thymeleaf)

Interview Summary: Model and ModelMap store data for the view, while ModelAndView holds both the model data and view name together.


What is ViewResolver?

  • Resolves logical view name to actual view file

  • Used in traditional Spring MVC (not REST)

  • Maps returned String from controller to physical view

Example:
Controller returns:

return "home";

Resolved to:
/WEB-INF/views/home.jsp

Common ViewResolvers

  • InternalResourceViewResolver → For JSP

  • ThymeleafViewResolver → For Thymeleaf templates

Interview Summary

ViewResolver converts the logical view name returned by a controller into the actual view file path in traditional Spring MVC applications.


What is Exception Handling in Spring MVC?

Spring provides two main ways to handle exceptions: @ExceptionHandler and @ControllerAdvice.


What is @ExceptionHandler?

  • Used inside a controller

  • Handles specific exceptions for that controller only

  • Suitable for controller-specific logic

Example:

@RestController
class UserController {

@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
throw new UserNotFoundException();
}

@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handle(UserNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("User not found");
}
}

Scope → Only applies to UserController.


What is @ControllerAdvice?

  • Global exception handler

  • Applies to all controllers

  • Used for centralized error handling

  • Keeps controllers clean

Example:

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handle(UserNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("User not found");
}
}

Scope → Applies to all controllers in the application.

Key Differences

@ExceptionHandler@ControllerAdvice
Local to one controllerGlobal across application
Defined inside controllerDefined in separate class
Used for specific casesUsed for centralized error handling
Harder to manage if many controllersClean and scalable approach

Real-Time Example

  • Return 404 when user not found

  • Return 400 for validation errors

  • Return 500 for unexpected server errors


Interview Summary

@ExceptionHandler handles exceptions at controller level, while @ControllerAdvice provides centralized global exception handling for the entire application.

Difference between @RestControllerAdvice and @ControllerAdvice?

  • Both are used for global exception handling

  • Both apply across multiple controllers

@ControllerAdvice

  • Used in traditional Spring MVC applications

  • Typically returns view names (JSP, Thymeleaf)

  • Requires @ResponseBody if returning JSON

Example:

@ControllerAdvice
public class GlobalHandler {

@ExceptionHandler(Exception.class)
public String handle() {
return "error"; // returns error.jsp
}
}


@RestControllerAdvice

  • Used in REST APIs

  • Returns JSON/XML by default

  • Combines @ControllerAdvice + @ResponseBody

Example:

@RestControllerAdvice
public class GlobalHandler {

@ExceptionHandler(Exception.class)
public String handle() {
return "Something went wrong";
}
}

Returns JSON response automatically.


Interview Summary

@ControllerAdvice is used for global exception handling in MVC apps (view-based), while @RestControllerAdvice is used in REST APIs and automatically returns JSON responses.


What is Validation in Spring MVC?

  • Used to validate incoming request data

  • Ensures data integrity before processing

  • Works with Bean Validation (Jakarta Validation / Hibernate Validator)

Common annotations:

  • @Valid → Triggers validation

  • @NotNull → Field must not be null

  • @Size → Restricts length

  • @Email → Valid email format


Example – Entity Validation

public class User {

@NotNull
@Size(min = 3, max = 20)
private String name;

@Email
private String email;
}

Example – Controller Validation

@PostMapping("/users")
public User create(@Valid @RequestBody User user) {
return user;
}

If validation fails → Spring returns HTTP 400 (Bad Request).

Real-Time Usage

  • Validate registration form

  • Validate login request

  • Validate API payload before saving to DB


Interview Summary

Validation in Spring MVC ensures incoming request data meets defined constraints using annotations like @NotNull, @Size, and @Email, triggered by @Valid.


What is CORS in Spring MVC?

  • CORS stands for Cross-Origin Resource Sharing

  • Allows frontend applications hosted on different domain/port to access backend APIs

  • Required when frontend and backend run on different origins

Example:

@CrossOrigin(origins = "http://localhost:3000")
@GetMapping("/users")
public List<User> getUsers() {
return List.of(new User(1L, "John"));
}

Allows requests from http://localhost:3000.


Global CORS Configuration

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}

Real-Time Usage

  • React app calling Spring Boot backend

  • Angular frontend hosted on different server

  • Microservices communicating across domains


Interview Summary

CORS allows cross-origin requests between frontend and backend applications, typically enabled using @CrossOrigin or global configuration in Spring MVC.


What is Interceptor?

  • Intercepts HTTP request before and after controller execution

  • Spring-specific mechanism

  • Works after DispatcherServlet

  • Similar to Servlet Filter but more controller-focused

Used for:

  • Logging

  • Authentication checks

  • Authorization

  • Performance timing

  • Pre/Post request processing

Example – Creating Interceptor

public class LoggingInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) {
System.out.println("Request received: " + request.getRequestURI());
return true; // continue request
}
}

Registering Interceptor

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoggingInterceptor());
}
}

Real-Time Usage

  • Log all API requests

  • Check authentication token

  • Measure request processing time

Interview Summary

An Interceptor in Spring MVC intercepts requests before and after controller execution, commonly used for logging, authentication, and performance monitoring.


What is Filter vs Interceptor?

FilterInterceptor
Part of Servlet API (javax.servlet)Spring-specific (HandlerInterceptor)
Executes before DispatcherServletExecutes after DispatcherServlet but before controller
Configured at servlet container levelConfigured in Spring context
Works for all requests (static + dynamic)Works only for controller requests
Used for CORS, encoding, compressionUsed for authentication, logging, timing

Example – Filter

@Component
public class LoggingFilter implements Filter {

@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) {
System.out.println("Filter executed");
chain.doFilter(request, response);
}
}

Example – Interceptor

public class LoggingInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) {
System.out.println("Interceptor executed");
return true;
}
}

Interview Summary

Filter is a Servlet-level component that runs before Spring’s DispatcherServlet, while Interceptor is Spring-specific and runs after DispatcherServlet but before the controller, mainly used for authentication and logging.


What is REST API Best Practice?

  • Use proper HTTP methods

    • GET → Read

    • POST → Create

    • PUT → Update

    • DELETE → Delete

  • Use plural nouns for resources

    • /users instead of /user

    • /orders instead of /getOrders

  • Use correct HTTP status codes

    • 200 → OK

    • 201 → Created

    • 400 → Bad Request

    • 404 → Not Found

    • 500 → Server Error

  • Keep APIs stateless

    • Do not store client session on server

    • Each request must contain required authentication info

  • Implement versioning

    • /api/v1/users

    • Prevents breaking changes

  • Use meaningful URLs

    • /users/10/orders

    • Avoid verbs in URL

  • Validate input properly

  • Secure APIs using HTTPS


Interview Summary

REST API best practices include using correct HTTP methods and status codes, plural resource naming, stateless design, proper versioning, and secure, clean URL structure.


What is Content Negotiation?

  • Mechanism to decide the response format (JSON, XML, etc.)

  • Allows client to specify preferred response type

  • Commonly used in REST APIs

Based on:

  • Accept header (most common)

  • URL extension (e.g., .json, .xml)

  • Request parameter (optional configuration)

Example – Using Accept Header

Request:

GET /users
Accept: application/json

Response:

{
"id": 1,
"name": "John"
}

Request:

GET /users
Accept: application/xml

Response:

<User>
<id>1</id>
<name>John</name>
</User>

Same API → Different response formats based on client request.


Example in Spring

@GetMapping(value = "/users", produces = "application/json")
public List<User> getUsers() {
return List.of(new User(1L, "John"));
}

Spring automatically selects the correct format using HttpMessageConverter.


Real-Time Usage

  • Same API supports JSON and XML clients

  • Public APIs serving multiple client types

  • Integration with legacy systems requiring XML


Interview Summary

Content negotiation allows the server to return data in different formats (JSON or XML) based on client request, usually determined by the Accept header.


How to handle large file upload in spring?

  • Use MultipartFile to receive uploaded files

  • Configure maximum file size in application properties

  • Prefer streaming instead of loading entire file into memory

  • Validate file type and size before processing


Configure Max File Size

spring.servlet.multipart.max-file-size=50MB
spring.servlet.multipart.max-request-size=50MB

Example – Using MultipartFile

@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
System.out.println("File name: " + file.getOriginalFilename());
return "File uploaded";
}

Streaming Large Files (Better for Big Files)

@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
try (InputStream inputStream = file.getInputStream()) {
// process stream line by line
}
return "File processed";
}

Avoid:

file.getBytes(); // Loads entire file into memory

Real-Time Usage

  • Bulk CSV upload

  • Excel import

  • Data migration files

  • Media uploads


Interview Summary

Large file uploads in Spring are handled using MultipartFile, proper size configuration, and streaming to avoid memory issues.


How to implement API versioning?

API versioning allows you to support multiple versions of an API without breaking existing clients.

Common Options

  • URL versioning → /api/v1/users

  • Header-based versioning

  • Media-type (Accept header) versioning

1. URL Versioning (Most Common & Simple)

@RestController
@RequestMapping("/api/v1/users")
class UserControllerV1 {
}

Next version:

@RestController
@RequestMapping("/api/v2/users")
class UserControllerV2 {
}

Simple, clear, and easy to maintain.


2. Header-Based Versioning

Client sends custom header:

X-API-VERSION: 1

Controller:

@GetMapping(value = "/users", headers = "X-API-VERSION=1")
public String getUsersV1() {
return "Version 1";
}

3. Media-Type Versioning

Client sends:

Accept: application/vnd.company.v1+json

Controller:

@GetMapping(value = "/users", produces = "application/vnd.company.v1+json")
public String getUsersV1() {
return "Version 1";
}

Best Practice

  • URL versioning is the simplest and most readable

  • Easy for clients and documentation

  • Widely used in real-world REST APIs


Interview Summary

API versioning can be implemented using URL, headers, or media type. URL versioning (/api/v1/...) is the most common and easiest approach in real projects.


Why DTO vs Entity separation?

  • Avoid exposing internal DB model in APIs

  • Prevent lazy loading issues

  • Hide sensitive fields (e.g., password)

  • Decouple API layer from persistence layer

  • Improve security and flexibility

Example (Good Practice):

public class UserDTO {
private Long id;
private String name;
}

Interview Summary: Use DTOs to control what data is exposed and keep your API independent from the database structure.


Common Spring MVC Interview Scenarios

  • Difference between Filter & Interceptor

  • How JSON conversion works internally

  • How DispatcherServlet works

  • How to handle global exceptions

  • How validation errors are handled

  • How CORS works

  • How Spring handles file upload








3️⃣ Spring Boot 


What is Spring Boot?

Answer:

  • An opinionated framework built on top of Spring

  • Simplifies Spring application development

  • Eliminates heavy XML configuration

  • Provides production-ready features

Key Features:

  • Auto-configuration

  • Embedded servers (Tomcat, Jetty, Undertow)

  • Starter dependencies

  • Actuator monitoring

  • Minimal setup

Real-time example:

  • Build REST API in minutes without manually configuring DispatcherServlet


Why Spring Boot Over Traditional Spring?

Answer:

  • No manual configuration

  • No web.xml

  • Embedded server

  • Less boilerplate

  • Faster development

Traditional Spring:

  • Configure XML

  • Setup server manually

Spring Boot:

  • Just @SpringBootApplication

  • Run main method


What is @SpringBootApplication?

Answer:
  • Main annotation used to bootstrap a Spring Boot application

  • Combination of:

    • @Configuration → Marks class as configuration class

    • @EnableAutoConfiguration → Enables auto-configuration

    • @ComponentScan → Scans components in current package and sub-packages


Example

@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

What Happens Internally?

  • Starts embedded server (Tomcat by default)

  • Creates ApplicationContext

  • Scans components

  • Applies auto-configuration

  • Registers all beans


Real-Time Usage

  • Entry point of Spring Boot application

  • Starts the entire application context

  • Used in microservices and standalone apps


Interview Summary

@SpringBootApplication is a convenience annotation that combines configuration, component scanning, and auto-configuration to start a Spring Boot application.


What is Auto-Configuration?

Answer:

  • Automatically configures beans based on:

    • Classpath dependencies

    • Existing beans

    • Properties

Uses:

  • @ConditionalOnClass

  • @ConditionalOnMissingBean

  • @ConditionalOnProperty

Example:

  • Add spring-boot-starter-data-jpa

  • Boot auto-configures:

    • EntityManager

    • DataSource

    • TransactionManager


How Does Auto-Configuration Work Internally?

Answer:

  • Uses spring.factories / AutoConfiguration imports

  • Loads configuration classes conditionally

  • Creates beans only if conditions match

Interview follow-up:

  • It does NOT override user-defined beans


What are Starter Dependencies?

Answer:

Predefined dependency bundles.

Examples:

  • spring-boot-starter-web

  • spring-boot-starter-data-jpa

  • spring-boot-starter-security

  • spring-boot-starter-test

  • spring-boot-starter-actuator

Benefits:

  • No dependency conflict

  • Less version management


What is Embedded Server?

Answer:

Spring Boot packages:

  • Embedded Tomcat (default)

  • Jetty

  • Undertow

No external server required.

<packaging>jar</packaging>

Run:

java -jar app.jar

Real-time:

  • Microservices deployed independently


What is application.properties vs application.yml?

application.properties

server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/test

application.yml

server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/test

YAML advantages:

  • Hierarchical structure

  • Cleaner configuration


What is Spring Boot Profiles?

Answer:

  • Environment-specific configuration

  • Dev, Test, Prod

application-dev.properties
application-prod.properties

Activate:

spring.profiles.active=dev

Real-time:

  • Dev DB vs Production DB


What is Spring Boot Actuator?

Answer:

Provides production-ready monitoring endpoints.

Common endpoints:

  • /actuator/health

  • /actuator/metrics

  • /actuator/info

  • /actuator/env

  • /actuator/beans

Real-time:

  • Kubernetes health checks

  • Monitoring via Prometheus


What is @ConfigurationProperties?

Answer:

  • Maps properties to Java class

@ConfigurationProperties(prefix = "app")
@Component
class AppConfig {
private String name;
}

Used in:

  • Centralized configuration management


What is CommandLineRunner?

Answer:

  • Executes code after application startup

@Component
class InitRunner implements CommandLineRunner {
public void run(String... args) {
System.out.println("App Started");
}
}

Real-time:

  • Seed database on startup


What is DevTools?

Answer:

  • Automatic restart

  • Live reload

  • Developer productivity improvement

Dependency:

spring-boot-devtools

What is Spring Boot Logging?

Answer:

  • Uses Logback by default

  • Supports:

    • INFO

    • DEBUG

    • ERROR

    • WARN

Configure:

logging.level.com.app=DEBUG

What is Spring Boot Packaging?

JAR (Recommended)

  • Embedded server

  • Microservices

WAR

  • Deploy on external server


What is Externalized Configuration?

Spring Boot supports configuration from:

  • application.properties

  • YAML files

  • Environment variables

  • Command-line arguments

  • Cloud config servers

Priority order applies.


What is Banner in Spring Boot?

  • ASCII banner at startup

  • Customize using banner.txt


What is Lazy Initialization in Spring Boot?

Enable:

spring.main.lazy-initialization=true
  • Improves startup time

  • Beans created only when needed


What is Spring Boot CLI?

  • Command-line tool

  • Run Groovy-based Spring apps quickly

Used rarely in production.


What is Spring Boot Test?

Annotations:

  • @SpringBootTest

  • @WebMvcTest

  • @DataJpaTest

  • @MockBean

Real-time:

  • Integration testing

  • Slice testing


What is Custom Starter in Spring Boot?

  • A reusable dependency that provides auto-configuration

  • Used to standardize common setup across projects

  • Contains:

    • Auto-config class

    • Properties class

    • Conditional beans

Example

Auto-Configuration

@Configuration
@ConditionalOnClass(MyService.class)
public class MyStarterAutoConfig {

@Bean
@ConditionalOnMissingBean
public MyService myService() {
return new MyService();
}
}

Properties

@ConfigurationProperties(prefix = "my.starter")
public class MyStarterProperties {
private String message;
}

Usage

my.starter.message=Hello

Used in:

  • Company-wide logging

  • Common security module


What is Graceful Shutdown?

  • Finishes ongoing requests

  • Stops accepting new requests

  • Closes connections safely

  • Prevents partial transactions

Enable:

server.shutdown=graceful

Used in:

  • Kubernetes deployments

  • Production releases


What is HikariCP?

  • Default connection pool in Spring Boot

  • High-performance and lightweight

  • Auto-configured with JDBC

Config example:

spring.datasource.hikari.maximum-pool-size=20

How Connection Pooling Works?

  • Maintains reusable DB connections

  • Request → borrow connection

  • After use → return to pool

  • Avoids costly open/close operations

Benefits:

  • Faster response time

  • Better scalability

  • Prevents DB overload


Common Spring Boot Interview Scenarios

  • Difference between @Configuration and @SpringBootApplication

  • How auto-configuration works internally

  • How to disable auto-configuration

  • How to change embedded server

  • How properties precedence works

  • How Actuator secures endpoints

  • How Boot handles exception globally


Spring Boot Summary

Spring Boot focuses on:

  • Auto-configuration

  • Embedded servers

  • Production-ready features

  • Monitoring

  • Externalized configuration

  • Simplified dependency management






4️⃣ Spring Data JPA 


What is Spring Data JPA?

Answer:

  • Abstraction over JPA (Java Persistence API)

  • Reduces boilerplate DAO code

  • Built on top of ORM frameworks like Hibernate

Key Features:

  • Automatic CRUD methods

  • Query method generation

  • Pagination & sorting

  • Custom JPQL/Native queries

  • Auditing support

Real-time example:

  • Instead of writing 100+ lines DAO code, just extend JpaRepository


What is ORM (Object Relational Mapping)?

Answer:

  • Maps Java objects to database tables

  • Eliminates manual JDBC coding

  • Handles SQL generation automatically

Popular ORM:

  • Hibernate (most common)

  • EclipseLink

Example:

@Entity
class User {
@Id
@GeneratedValue
private Long id;
private String name;
}

Maps to:

USER table
id | name

Real-time:

  • Convert DB rows into Java objects automatically


What is Hibernate?

Answer:

  • Most popular JPA implementation

  • Converts HQL/JPQL to SQL

  • Manages caching, lazy loading, dirty checking

Key Responsibilities:

  • SQL generation

  • Connection handling

  • Transaction synchronization

  • Object state management


What is JPA?

Answer:

  • Specification (not implementation)

  • Defines APIs for ORM

  • Hibernate implements JPA

Think:

  • JPA → Rules

  • Hibernate → Implementation


What is Entity Lifecycle in JPA?

Entity states:

  1. Transient → Not managed

  2. Persistent → Managed by EntityManager

  3. Detached → Previously managed

  4. Removed → Marked for deletion

Real-time:

  • Fetch entity → modify → auto update via dirty checking


What is JpaRepository?

Answer:

Extends:

  • CrudRepository

  • PagingAndSortingRepository

Provides:

  • save()

  • findById()

  • delete()

  • findAll()

  • Pagination

public interface UserRepo extends JpaRepository<User, Long> {}

What is the Difference Between save() and saveAndFlush()?

  • save() → Delays DB synchronization

  • saveAndFlush() → Immediately writes to DB

  • Flush → Synchronizes persistence context with DB

Used when:

  • Need immediate DB consistency


What is Dirty Checking?

Answer:

  • Hibernate tracks entity changes automatically

  • No need to call update()

User user = repo.findById(1L).get();
user.setName("New Name");
  • Automatically updated at transaction commit


What is FetchType.LAZY vs FetchType.EAGER?

LAZY (Default for @OneToMany)

  • Loads data only when accessed

  • Improves performance

EAGER

  • Loads immediately with parent

@OneToMany(fetch = FetchType.LAZY)

Real-time:

  • Load Order without loading all OrderItems initially


What is N+1 Problem?

Answer:

Occurs when:

  • One query loads parent

  • N queries load child data

Example:

  • 1 query for Orders

  • 100 queries for OrderItems

Problem:

  • Performance degradation

Solution:

  • Use JOIN FETCH

  • Use EntityGraph

  • Use batch fetching

@Query("SELECT o FROM Order o JOIN FETCH o.items")

What is @Transactional?

Answer:

  • Manages database transactions declaratively

  • Applied at method or class level

@Transactional
public void processOrder() {}

Default Behavior:

  • Rollback on RuntimeException

  • Commit on success


What are Transaction Propagation Types?

  • REQUIRED (Default)

  • REQUIRES_NEW

  • SUPPORTS

  • MANDATORY

  • NEVER

  • NOT_SUPPORTED

Real-time:

  • PaymentService → REQUIRES_NEW

  • Audit logging → Separate transaction


What are Isolation Levels?

  • READ_UNCOMMITTED

  • READ_COMMITTED

  • REPEATABLE_READ

  • SERIALIZABLE

Issues:

  • Dirty Read

  • Non-repeatable Read

  • Phantom Read

Real-time:

  • Banking system → Use REPEATABLE_READ or SERIALIZABLE


What is First-Level Cache?

  • Default cache

  • Session-level (EntityManager)

  • Automatically enabled


What is Second-Level Cache?

  • Shared across sessions

  • Requires configuration

  • Improves performance

Tools:

  • EhCache

  • Hazelcast


What is JPQL?

  • Java Persistence Query Language

  • Works on Entity names (not table names)

@Query("SELECT u FROM User u WHERE u.name = :name")

What is Native Query?

  • Direct SQL query

@Query(value = "SELECT * FROM users", nativeQuery = true)

Used when:

  • Complex SQL

  • DB-specific features


What is Pagination and Sorting?

Page<User> users = repo.findAll(PageRequest.of(0, 10));

Used in:

  • Large datasets

  • REST APIs


What is Auditing in JPA?

Tracks:

  • CreatedDate

  • ModifiedDate

  • CreatedBy

@CreatedDate
private LocalDateTime createdAt;

What is Cascade Type?

Defines how operations propagate:

  • PERSIST

  • MERGE

  • REMOVE

  • ALL

  • DETACH

  • REFRESH

@OneToMany(cascade = CascadeType.ALL)

What is Orphan Removal?

  • Deletes child when removed from parent collection

@OneToMany(orphanRemoval = true)

What is Optimistic vs Pessimistic Locking?

Optimistic

  • Uses @Version

  • Prevents lost updates

Pessimistic

  • Locks DB row

  • Prevents concurrent modification

Used in:

  • Banking, inventory systems


What is DTO Projection?

Instead of loading full entity:

@Query("SELECT new com.app.UserDTO(u.id, u.name) FROM User u")

Improves:

  • Performance

  • Security


What is LazyInitializationException?

Occurs when:

  • Access lazy field outside transaction

Solution:

  • Use JOIN FETCH

  • Use DTO

  • Use OpenSessionInView (not recommended)


How to implement Soft Delete?

  • Add deleted flag column.

  • Override delete logic.

  • Use Hibernate @Where(clause="deleted=false").

Used when:

  • Data should not be permanently removed.


What are memory leak scenarios?

  • Large caching without eviction.

  • Static collections.

  • Unclosed resources.

  • Too many open sessions.

Prevention:

  • Monitor heap.

  • Proper resource management.


Common Spring Data JPA Interview Scenarios

  • Explain N+1 problem

  • Difference between EntityManager and Repository

  • How transactions work internally (Proxy-based)

  • How dirty checking works

  • Why LAZY is preferred

  • How to optimize performance

  • When to use native query

  • How cascading works

  • What happens if @Transactional missing


Spring Data JPA Summary

Covers:

  • ORM concepts

  • Hibernate internals

  • Entity lifecycle

  • Fetch strategies

  • Transaction management

  • Isolation & propagation

  • Caching

  • Locking

  • Performance optimization








5️⃣ Spring Cloud 

Spring Cloud helps build microservices architecture using Spring Boot.

It provides solutions for:

  • Service discovery

  • API gateway

  • Distributed configuration

  • Fault tolerance

  • Load balancing

  • Distributed tracing

  • Circuit breakers


What is Spring Cloud?

Answer:

  • Collection of tools for building distributed systems

  • Built on top of Spring Boot

  • Solves common microservices problems

Real-time example:

  • E-commerce system:

    • User Service

    • Order Service

    • Payment Service

    • Inventory Service
      Spring Cloud connects and manages them.


What is Microservices Architecture?

Answer:

  • Application split into small independent services

  • Each service:

    • Has its own database

    • Deployable independently

    • Communicates via REST or messaging

Benefits:

  • Scalability

  • Fault isolation

  • Independent deployment


Service Discovery


What is Service Discovery?

Answer:

  • Mechanism to dynamically register and discover services

  • Avoids hardcoding service URLs


What is Eureka?

Answer:

  • Service registry server

  • Services register themselves

  • Other services discover them

Components:

  • Eureka Server

  • Eureka Client

@EnableEurekaServer

Client config:

eureka.client.service-url.defaultZone=http://localhost:8761/eureka

Real-time:

  • Order Service calls Payment Service without knowing IP


What is Load Balancing?

Answer:

  • Distributes traffic across multiple service instances

Spring Cloud uses:

  • Spring Cloud LoadBalancer (replaced Ribbon)

Real-time:

  • 3 instances of Payment Service

  • Requests distributed automatically


API Gateway


What is API Gateway?

Answer:

  • Single entry point for all client requests

  • Routes requests to internal services

Spring Cloud Gateway features:

  • Routing

  • Filtering

  • Authentication

  • Rate limiting

  • Logging

spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://USER-SERVICE
predicates:
- Path=/users/**

Real-time:

  • Frontend calls only Gateway

  • Gateway routes internally


Why Use API Gateway?

  • Hides internal service structure

  • Centralized security

  • Centralized logging

  • Reduces client complexity


Distributed Configuration


What is Spring Cloud Config?

Answer:

  • Centralized configuration management

  • Stores config in Git repository

  • Services fetch config at startup

Real-time:

  • Change DB URL without redeploying services


Fault Tolerance


What is Resilience4j?

Answer:

  • Fault tolerance library

  • Replaced Hystrix

  • Provides:

Features:

  • Circuit Breaker

  • Retry

  • Rate Limiter

  • Bulkhead

  • TimeLimiter


What is Circuit Breaker?

Answer:

  • Stops calling failing service

  • Prevents cascading failures

States:

  • CLOSED

  • OPEN

  • HALF_OPEN

Real-time:

  • Payment Service down

  • Order Service stops calling it temporarily


What is Retry?

  • Retries failed request automatically

  • Used for temporary failures


What is Bulkhead?

  • Limits concurrent calls

  • Prevents resource exhaustion


What is Rate Limiting?

  • Limits number of requests

  • Protects service from overload


Distributed Tracing


What is Distributed Tracing?

Answer:

  • Tracks request across multiple services

  • Helps debugging

Tools:

  • Spring Cloud Sleuth

  • Zipkin

Real-time:

  • Track request from Gateway → Order → Payment → Inventory


Messaging in Spring Cloud


What is Spring Cloud Stream?

  • Event-driven microservices

  • Works with:

    • Kafka

    • RabbitMQ

Used for:

  • Asynchronous communication

Real-time:

  • Order created → Event sent → Inventory updated


Security in Spring Cloud

  • API Gateway handles authentication

  • OAuth2 integration

  • JWT validation at gateway level

  • Centralized auth server


Common Spring Cloud Interview Scenarios

  • How Eureka works internally

  • How services communicate without hardcoding URLs

  • What happens if Eureka goes down

  • How circuit breaker prevents cascading failure

  • Difference between Retry and Circuit Breaker

  • Why API Gateway is important

  • How centralized config works

  • How to secure microservices


Common Architecture Pattern

Typical Microservices Setup:

Client

API Gateway

Eureka (Service Discovery)

Microservices (User, Order, Payment)

Database


Spring Cloud Summary

Spring Cloud solves:

  • Service discovery

  • API routing

  • Load balancing

  • Fault tolerance

  • Centralized configuration

  • Distributed tracing

  • Event-driven communication

What is Blue-Green Deployment?

  • Two identical environments.

  • Switch traffic after validation.

  • Zero downtime release.


What is Rate Limiting?

  • Limits number of API calls.

  • Protects against abuse.

  • Implement via:

    • API Gateway

    • Resilience4j


What is Idempotency in microservices?

  • Same request → Same result.

  • Prevent duplicate processing.

Implementation:

  • Unique request ID.

  • Store processed request IDs.

Used in:

  • Payment APIs.


What is Observability?

  • Logging

  • Metrics

  • Tracing

  • Health monitoring

Tools:

  • Actuator

  • Prometheus

  • Grafana







6️⃣ Spring Security 

Spring Security is used to secure Spring applications (monolith + microservices).

It handles:

  • Authentication

  • Authorization

  • Session management

  • OAuth2

  • JWT

  • CORS

  • CSRF

  • Method-level security


What is Spring Security?

Answer:

  • Powerful authentication and authorization framework

  • Integrates with Spring Boot easily

  • Secures REST APIs and web applications

Real-time example:

  • Banking app → Only authenticated users can view account

  • Admin APIs accessible only to ADMIN role


Authentication & Authorization


What is Authentication?

Answer:

  • Verifying identity of a user

  • "Who are you?"

Methods:

  • Username & password

  • JWT token

  • OAuth2 login

  • LDAP

  • SSO


What is Authorization?

Answer:

  • Checking permissions after authentication

  • "What can you access?"

Example:

  • USER → View profile

  • ADMIN → Delete users


What is RBAC (Role-Based Access Control)?

Answer:

  • Access based on roles

  • Roles mapped to authorities

Example:

  • ROLE_USER

  • ROLE_ADMIN

@PreAuthorize("hasRole('ADMIN')")

Real-time:

  • Only admin can approve loans


Spring Security Architecture


What is Security Filter Chain?

Answer:

  • Series of filters applied before request reaches controller

  • Works inside Servlet filter layer

Common filters:

  • UsernamePasswordAuthenticationFilter

  • BasicAuthenticationFilter

  • CsrfFilter


What is AuthenticationManager?

  • Responsible for authentication process

  • Validates credentials


What is UserDetailsService?

  • Loads user-specific data from DB

  • Returns UserDetails object

@Service
class CustomUserService implements UserDetailsService {
public UserDetails loadUserByUsername(String username) {}
}

JWT (Stateless Security)


What is JWT?

  • JSON Web Token

  • Used for stateless authentication

  • Stored in Authorization header

Structure:

Header.Payload.Signature

How JWT Flow Works?

  1. User logs in

  2. Server validates credentials

  3. Server generates JWT

  4. Client sends JWT in every request

  5. Server validates token

Header example:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Real-time:

  • Microservices authentication


Advantages of JWT

  • Stateless

  • Scalable

  • No session storage

  • Suitable for distributed systems


OAuth2 and Authorization Server


What is OAuth2?

  • Authorization framework

  • Delegated access

  • Used for social login (Google, GitHub)

Flow:

  • Client

  • Authorization Server

  • Resource Server


What is Authorization Server?

  • Issues access tokens

  • Validates users

  • Example: Keycloak


What is Resource Server?

  • API server

  • Validates token before serving data


What is Keycloak?

Answer:

  • Open-source Identity and Access Management tool

  • Provides:

    • SSO

    • OAuth2

    • OpenID Connect

    • Role management

Real-time:

  • Central auth for multiple microservices


CSRF & CORS


What is CSRF?

  • Cross-Site Request Forgery

  • Attacker tricks user to perform unwanted action

Spring Security:

  • Enables CSRF protection by default (for web apps)

Disable for REST:

http.csrf().disable();

What is CORS?

  • Cross-Origin Resource Sharing

  • Allows frontend and backend on different domains

@CrossOrigin(origins = "http://localhost:3000")

Real-time:

  • React app calling Spring Boot API


Password Encoding


Why Use PasswordEncoder?

  • Never store plain passwords

  • Use BCrypt

@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

Session Management


Stateful vs Stateless

Stateful

  • Uses HTTP session

  • Stores authentication in server memory

Stateless

  • Uses JWT

  • No server session

  • Scalable


Method-Level Security


What is @PreAuthorize?

  • Secures specific methods

@PreAuthorize("hasAuthority('ADMIN')")

Enable:

@EnableMethodSecurity

Security Best Practices

  • Always use HTTPS

  • Use BCrypt for passwords

  • Use JWT expiry time

  • Validate tokens at gateway

  • Disable CSRF for REST APIs

  • Use role hierarchy carefully

  • Implement rate limiting


Advanced Security Concepts


What is AWT in Security Context?

If referring to authentication workflow:

  • Authentication → Authorization → Token validation

If referring to Java AWT:

  • Not related to Spring Security


What is SecurityContext?

  • Holds authentication object

  • Stored per request

SecurityContextHolder.getContext().getAuthentication();

What is GrantedAuthority?

  • Represents permission

  • Example: ROLE_ADMIN


Common Spring Security Interview Scenarios

  • Difference between Authentication and Authorization

  • How JWT works internally

  • How to secure microservices

  • How role hierarchy works

  • How filters work internally

  • Difference between OAuth2 and JWT

  • How to integrate Keycloak

  • Why CSRF is disabled in REST

  • How to implement RBAC


Spring Security Summary

Covers:

  • Authentication

  • Authorization (RBAC)

  • JWT

  • OAuth2

  • Keycloak

  • Filter chain

  • CSRF & CORS

  • Password encoding

  • Stateless vs Stateful security


Where should JWT be stored?

Options:

  • LocalStorage (XSS risk)

  • HttpOnly cookie (more secure)

Best practice:

  • HttpOnly + Secure cookie.


How to secure Actuator endpoints?

  • Restrict exposure:

management.endpoints.web.exposure.include=health,info
  • Protect via role-based access.


How to prevent brute-force attacks?

  • Rate limiting

  • Account lockout after attempts

  • CAPTCHA

  • Monitoring failed login attempts







7️⃣ Spring Batch 

Spring Batch is used for large-scale batch processing in enterprise applications.

Used in:

  • Banking systems

  • Payroll systems

  • Data migration

  • Report generation

  • ETL jobs


What is Spring Batch?

Answer:

  • Framework for processing large volumes of data

  • Handles:

    • Reading data

    • Processing data

    • Writing data

  • Supports transaction management

  • Provides restart & retry mechanisms

Real-time example:

  • Process 10 million bank transactions overnight


Core Concepts


What is a Job in Spring Batch?

Answer:

  • Top-level batch process

  • Contains one or more Steps

@Bean
public Job importUserJob(JobRepository jobRepository, Step step1) {
return new JobBuilder("importUserJob", jobRepository)
.start(step1)
.build();
}

What is a Step?

Answer:

  • Independent phase of a Job

  • Can be:

    • Chunk-oriented

    • Tasklet-based

Real-time:

  • Step 1 → Read file

  • Step 2 → Validate

  • Step 3 → Write to DB


Chunk-Oriented Processing


What is Chunk Processing?

Answer:

  • Processes data in chunks (groups)

  • Improves performance

  • Commits transaction per chunk

Flow:

  1. Read items

  2. Process items

  3. Write items

.stepBuilderFactory.get("step1")
.<Input, Output>chunk(100)
.reader(reader())
.processor(processor())
.writer(writer())

Real-time:

  • Read 1000 records

  • Commit every 100 records


What is ItemReader?

  • Reads data from:

    • File (CSV, XML)

    • Database

    • API

Example:

FlatFileItemReader

What is ItemProcessor?

  • Applies business logic

  • Can filter or transform data

Example:

  • Validate email

  • Convert currency


What is ItemWriter?

  • Writes processed data to:

    • Database

    • File

    • Message queue


Tasklet-Based Processing


What is Tasklet?

  • Single task execution

  • Not chunk-based

Example:

  • Delete temp files

  • Send email

public class CleanupTasklet implements Tasklet {}

Job Execution & Metadata


What is JobRepository?

  • Stores metadata:

    • Job status

    • Execution history

    • Restart data

Stored in DB tables like:

  • BATCH_JOB_INSTANCE

  • BATCH_JOB_EXECUTION


What is JobLauncher?

  • Starts a Job programmatically

jobLauncher.run(job, new JobParameters());

Restart & Retry


How Restart Works?

  • If job fails → restart from failed step

  • Uses metadata stored in DB

Real-time:

  • Failed at record 5000

  • Restart continues from 5001


What is Skip and Retry?

Skip

  • Skip invalid records

.skipLimit(10)
.skip(Exception.class)

Retry

  • Retry failed operation

.retryLimit(3)
.retry(SQLException.class)

Real-time:

  • Skip corrupted CSV row

  • Retry temporary DB failure


Parallel Processing


How to Achieve Parallel Processing?

  • Multi-threaded step

  • Partitioning

  • Remote chunking

Used for:

  • High-volume data processing


Transaction Management in Spring Batch

  • Each chunk runs in transaction

  • Rollback happens if error

  • Supports propagation and isolation

Real-time:

  • If record fails → rollback current chunk only


Scheduling Batch Jobs


How to Schedule Batch Jobs?

Using:

  • Spring Scheduler

  • Cron expression

  • External schedulers (Quartz, Control-M)

@Scheduled(cron = "0 0 1 * * ?")

Real-time:

  • Run payroll job at 1 AM daily


Performance Optimization

  • Use chunk size wisely

  • Use indexing in DB

  • Use partitioning

  • Avoid unnecessary logging

  • Tune commit interval


Common Spring Batch Interview Questions

  • Difference between Job and Step

  • What is chunk processing

  • How restart works

  • What tables Spring Batch creates

  • Difference between skip and retry

  • How to process millions of records

  • How to implement parallel processing

  • How transactions work in batch

  • When to use Tasklet


Spring Batch Summary

Spring Batch is used for:

  • Large-scale data processing

  • ETL jobs

  • Scheduled processing

  • Restartable batch jobs

  • Fault-tolerant processing







8️⃣ Spring WebFlux 

Spring WebFlux is used for reactive, non-blocking web applications.

It is an alternative to Spring MVC when:

  • High concurrency is required

  • Non-blocking I/O is needed

  • Streaming or real-time data is required


What is Spring WebFlux?

Answer:

  • Reactive web framework introduced in Spring 5

  • Supports non-blocking, asynchronous programming

  • Built on Project Reactor

Works with:

  • Netty (default server)

  • Tomcat (non-blocking mode)

  • Undertow

Real-time example:

  • Chat applications

  • Live stock price streaming

  • High-traffic APIs (thousands of concurrent users)


What is Reactive Programming?

Answer:

  • Asynchronous, non-blocking programming model

  • Based on Publisher-Subscriber pattern

  • Handles streams of data

Key concept:

  • Data flows as stream

  • Consumers react to data


What is Project Reactor?

Answer:

  • Reactive library used in WebFlux

  • Provides:

    • Mono (0 or 1 element)

    • Flux (0 to many elements)


What is Mono?

  • Represents 0 or 1 result

Mono<User> userMono = Mono.just(new User());

Used for:

  • Single database result

  • Single API response


What is Flux?

  • Represents multiple values

Flux<String> flux = Flux.just("A", "B", "C");

Used for:

  • Streaming data

  • Multiple records


Difference Between Mono and Flux?

MonoFlux
0 or 1 item0 to N items
Single responseStream response

WebFlux vs Spring MVC

Spring MVCSpring WebFlux
BlockingNon-blocking
Servlet-basedReactive runtime
Thread per requestEvent loop model
Good for normal appsGood for high concurrency

What is Non-Blocking I/O?

Answer:

  • Thread does not wait for operation to complete

  • Frees resources for other tasks

Blocking:

  • Thread waits for DB call

Non-blocking:

  • Thread registers callback

  • Continues processing


What is Event Loop Model?

  • Single thread handles multiple requests

  • Uses callbacks

  • Efficient resource usage

Used by:

  • Netty

  • Node.js


WebFlux Programming Models


1️⃣ Annotation-Based Model

Similar to Spring MVC

@RestController
public class UserController {

@GetMapping("/users")
public Flux<User> getUsers() {
return userService.getAll();
}
}

2️⃣ Functional Routing Model

Uses RouterFunction

@Bean
public RouterFunction<ServerResponse> routes() {
return RouterFunctions.route(
RequestPredicates.GET("/users"),
request -> ServerResponse.ok().body(userService.getAll(), User.class)
);
}

Used for:

  • Lightweight reactive APIs


What is Backpressure?

Answer:

  • Mechanism to control data flow

  • Prevents consumer from being overwhelmed

Example:

  • Fast producer

  • Slow consumer

  • Backpressure regulates speed


What is WebClient?

Answer:

  • Reactive HTTP client

  • Replaces RestTemplate

WebClient.create()
.get()
.uri("http://user-service/users")
.retrieve()
.bodyToFlux(User.class);

Real-time:

  • Service-to-service communication in microservices


What is Server-Sent Events (SSE)?

  • Real-time streaming from server to client

  • Used in:

    • Notifications

    • Live updates

@GetMapping(value="/stream", produces=MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> stream() {}

Error Handling in WebFlux

Use:

  • onErrorResume()

  • onErrorReturn()

return userService.getUser()
.onErrorResume(e -> Mono.empty());

Threading Model in WebFlux

  • Uses small number of threads

  • Event-loop based

  • Efficient under heavy load


When to Use WebFlux?

Use when:

  • High concurrent users

  • Streaming required

  • Reactive DB (R2DBC)

  • Non-blocking APIs

Avoid when:

  • Simple CRUD app

  • Blocking database driver used


Common WebFlux Interview Questions

  • Difference between MVC and WebFlux

  • What is Mono and Flux

  • What is backpressure

  • How non-blocking works

  • What is WebClient

  • When to use WebFlux

  • How threading works internally

  • Can we mix MVC and WebFlux? (Not recommended)


Spring WebFlux Summary

Spring WebFlux focuses on:

  • Reactive programming

  • Mono & Flux

  • Non-blocking I/O

  • Event loop model

  • Backpressure

  • Streaming APIs

  • High concurrency handling

What happens if blocking call used in WebFlux?

  • Blocks event loop thread.

  • Reduces scalability.

  • Breaks reactive benefits.

Solution:

  • Use reactive DB (R2DBC).

  • Avoid blocking APIs.


How backpressure works internally?

  • Controls data flow between producer and consumer.

  • Prevents memory overflow.

  • Managed by Reactive Streams specification.






9️⃣ Spring R2DBC

Spring R2DBC is used for reactive, non-blocking database access.

It is designed to work with:

  • Spring WebFlux

  • Reactive applications

  • High-concurrency systems


What is R2DBC?

Answer:

  • Reactive Relational Database Connectivity

  • Alternative to JDBC for reactive systems

  • Non-blocking database driver

JDBC → Blocking
R2DBC → Non-blocking

Real-time example:

  • High-traffic API using WebFlux

  • Need non-blocking DB calls to handle thousands of users


Why JDBC is Not Suitable for Reactive Systems?

Answer:

  • JDBC is blocking

  • Thread waits for DB response

  • Not scalable for high concurrency

Example:

  • 1000 concurrent requests

  • 1000 threads blocked waiting for DB


How R2DBC Solves This?

  • Uses reactive streams

  • Returns:

    • Mono

    • Flux

  • Non-blocking DB operations

  • Uses event-loop model


Supported Databases

  • PostgreSQL

  • MySQL

  • H2

  • MS SQL Server

  • MariaDB

Dependency example:

spring-boot-starter-data-r2dbc

What is Spring Data R2DBC?

Answer:

  • Reactive version of Spring Data JPA

  • Works with reactive repositories

  • Does NOT use Hibernate

  • No EntityManager


How is R2DBC Different from JPA?

JPAR2DBC
BlockingNon-blocking
Uses HibernateNo Hibernate
EntityManagerDatabaseClient
Lazy loading supportedNo lazy loading

What is ReactiveCrudRepository?

  • Similar to JpaRepository

  • Returns Mono and Flux

public interface UserRepo
extends ReactiveCrudRepository<User, Long> {
}

Example CRUD Operation

@GetMapping("/users")
public Flux<User> getUsers() {
return userRepo.findAll();
}

Insert:

public Mono<User> save(User user) {
return userRepo.save(user);
}

What is DatabaseClient?

  • Alternative to repository

  • Used for custom queries

databaseClient
.sql("SELECT * FROM users")
.map(row -> new User())
.all();

Used when:

  • Complex SQL needed


How Transactions Work in R2DBC?

  • Uses ReactiveTransactionManager

  • Must use transactional operator

@Transactional
public Mono<Void> process() {}

Important:

  • Entire chain must be reactive

  • Blocking inside transaction breaks flow


Limitations of R2DBC

  • No lazy loading

  • No advanced ORM features

  • No first-level cache

  • No second-level cache

  • No dirty checking like Hibernate

Best for:

  • Simple CRUD

  • Reactive microservices


When to Use R2DBC?

Use when:

  • Using WebFlux

  • Need non-blocking DB

  • High scalability required

Avoid when:

  • Complex ORM needed

  • Heavy relational mapping required


What is ConnectionFactory?

  • Similar to DataSource in JDBC

  • Manages DB connections

Configured in:

spring.r2dbc.url=r2dbc:postgresql://localhost:5432/test

What is Backpressure in DB Context?

  • Controls data flow from DB

  • Prevents overwhelming consumer

  • Important in streaming queries


Can We Mix JPA and R2DBC?

Yes, but:

  • Not in same transaction

  • Blocking + non-blocking together reduces performance

Best practice:

  • Choose one per service


Performance Considerations

  • Avoid blocking calls

  • Use reactive driver only

  • Use connection pooling

  • Handle errors properly

  • Monitor thread usage


Common R2DBC Interview Questions

  • Difference between JDBC and R2DBC

  • Why JPA not suitable for reactive apps

  • Can we use Hibernate with R2DBC? (No)

  • How transactions work in reactive systems

  • What are limitations of R2DBC

  • How to handle complex joins

  • How backpressure works with DB


Spring R2DBC Summary

Spring R2DBC focuses on:

  • Reactive database access

  • Non-blocking I/O

  • Mono & Flux DB operations

  • High concurrency handling

  • WebFlux integration

Why no lazy loading in R2DBC?

  • No Hibernate.

  • No session context.

  • Pure reactive driver.

  • Must fetch relations manually.


What happens if JPA used inside WebFlux?

  • Blocks thread.

  • Performance degradation.

  • Not fully reactive.






🔟 Best Practices, Design Patterns, and Advanced Spring Concepts


Spring Best Practices


Why Constructor Injection is Recommended?

  • Makes dependencies mandatory

  • Improves immutability

  • Easier unit testing

  • Avoids circular dependency issues

  • Encourages clean architecture

Best Practice:

  • Avoid field injection in production code


Why Singleton Beans Should Be Stateless?

  • Singleton shared across all requests

  • Stateful singleton → thread-safety issues

  • Race conditions possible

Bad Example:

@Service
class CounterService {
private int count; // Not thread-safe
}

Best Practice:

  • Store request-specific data in method scope


Why Avoid Circular Dependencies?

  • Indicates poor design

  • Hard to maintain

  • Constructor injection fails

Solution:

  • Refactor responsibilities

  • Use interface segregation


Proper Exception Handling Strategy

  • Use @ControllerAdvice for global handling

  • Avoid exposing internal stack traces

  • Return meaningful HTTP status codes

  • Use custom exception hierarchy


Logging Best Practices

  • Use SLF4J with Logback

  • Avoid System.out.println

  • Log levels properly:

    • ERROR → Critical failure

    • WARN → Potential issue

    • INFO → Important events

    • DEBUG → Development debugging


Configuration Best Practices

  • Use @ConfigurationProperties

  • Avoid hardcoding values

  • Separate Dev, Test, Prod profiles

  • Use centralized config (Spring Cloud Config)

What is API Idempotency?

  • Ensures duplicate requests do not duplicate action.

  • Critical for payments & order processing.


What are memory leak scenarios in Spring?

  • Static references.

  • Long-living caches.

  • Unclosed streams.

  • Large session objects.


Design Patterns in Spring


What Design Patterns Are Used in Spring?

Spring internally uses:

  • Singleton pattern

  • Factory pattern

  • Proxy pattern

  • Template pattern

  • Observer pattern

  • Dependency Injection pattern


What is Singleton Pattern in Spring?

  • Default bean scope

  • One instance per container

Important:

  • Not GoF singleton

  • Managed by container


What is Factory Pattern in Spring?

  • BeanFactory & ApplicationContext

  • Responsible for object creation


What is Proxy Pattern in Spring?

Used for:

  • AOP

  • Transactions

  • Security

Example:

  • @Transactional creates proxy

  • Method call intercepted

Important:

  • Final methods cannot be proxied


What is Template Pattern?

Example:

  • JdbcTemplate

  • RestTemplate

  • TransactionTemplate

Provides:

  • Common workflow

  • Customizable steps


Advanced Spring Concepts


How @Transactional Works Internally?

  • Uses AOP proxy

  • Wraps method in transaction boundary

  • Commits or rollbacks automatically

Important:

  • Only works for public methods

  • Self-invocation does not work


What is Self-Invocation Problem?

  • Calling transactional method inside same class

  • Proxy not triggered

Solution:

  • Move method to separate service


What is Open Session in View (OSIV)?

  • Keeps session open during view rendering

  • Avoids LazyInitializationException

Not recommended for:

  • High-performance systems


What is Lazy Initialization Problem?

  • Access lazy field outside transaction

  • Causes exception

Solution:

  • Use DTO projection

  • Use JOIN FETCH


How to Improve Performance in Spring?

  • Use connection pooling

  • Avoid N+1 queries

  • Use caching

  • Use pagination

  • Optimize queries

  • Avoid unnecessary synchronization


What is Caching in Spring?

Enable:

@EnableCaching

Use:

@Cacheable("users")

Used for:

  • Frequently accessed data

  • Reducing DB load


What is Idempotency?

  • Same request multiple times → Same result

  • Important in payment APIs

Implementation:

  • Use unique request ID

  • Store transaction state


How to Handle Distributed Transactions?

Options:

  • Saga pattern

  • Two-phase commit (Not recommended for microservices)

  • Event-driven architecture


Microservices Design Best Practices


Database Per Service

  • Each service owns its database

  • Avoid shared DB


API Versioning

  • Use /api/v1/

  • Prevents breaking changes


Circuit Breaker Usage

  • Prevent cascading failures

  • Use Resilience4j


Observability

  • Use:

    • Actuator

    • Prometheus

    • Grafana

    • Distributed tracing


Security Best Practices

  • Use HTTPS

  • Use JWT expiry

  • Implement RBAC properly

  • Secure Actuator endpoints

  • Disable unnecessary endpoints

  • Validate input properly


Testing Best Practices

  • Unit test services

  • Use @WebMvcTest for controller

  • Use @DataJpaTest for repository

  • Use Mockito for mocking

  • Avoid full context loading unnecessarily


Common Advanced Interview Questions

  • How Spring creates proxy objects

  • Why final methods cannot be transactional

  • How to handle high concurrency

  • How to optimize JPA performance

  • How to secure microservices

  • How to design scalable microservices

  • How Spring manages thread safety

  • How caching works internally


Production-Level Architecture Summary

A production-ready Spring system should have:

  • Clean layered architecture

  • Stateless services

  • Proper exception handling

  • Monitoring & logging

  • Caching strategy

  • Secure authentication

  • Fault tolerance

  • Scalability design