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
newkeyword 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
@Qualifierif 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:
-
Bean instantiation
-
Dependency injection
-
@PostConstruct -
Ready for use
-
@PreDestroy -
Destroy
Customization:
-
InitializingBean
-
DisposableBean
Real-time:
-
Opening DB connection on init
-
Closing resources on destroy
What is BeanFactory vs ApplicationContext?
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 injectUsed 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,
StripePaymentServicewill be injected because it is marked with@Primary.Using @Qualifier
@Autowired
@Qualifier("paypalPaymentService")
private PaymentService paymentService;Here,
PaypalPaymentServicewill be injected explicitly.
When to Use
@Primary→ When one implementation should act as default
@Qualifier→ When you need specific implementationInterview Summary
@Primarydefines the default bean among multiple candidates, while@Qualifierallows 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 existsExample using @ConditionalOnProperty
@Configuration
class FeatureConfig {
@Bean
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
public FeatureService featureService() {
return new FeatureService();
}
}application.properties:
feature.enabled=trueBean 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
@Conditionalannotations 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.
@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?
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:
-
Client calls
transfer() -
Proxy starts transaction
-
Target method executes
-
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:
-
Client sends request
-
DispatcherServlet receives
-
Finds handler using HandlerMapping
-
Calls controller
-
Returns response
Real-time example:
-
All API calls like
/login,/users,/ordersgo 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 apps | Used in REST APIs / Microservices |
Needs @ResponseBody for JSON | @ResponseBody applied automatically |
| Mostly used in monolithic web apps | Common 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?
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?
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 controller | Global across application |
| Defined inside controller | Defined in separate class |
| Used for specific cases | Used for centralized error handling |
| Harder to manage if many controllers | Clean 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
@ResponseBodyif 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;
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?
What is REST API Best Practice?
Use proper HTTP methods
-
GET → Read
-
POST → Create
-
PUT → Update
-
DELETE → Delete
-
-
Use plural nouns for resources
-
/usersinstead of/user -
/ordersinstead 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?
How to handle large file upload in spring?
How to implement API versioning?
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:
-
Transient → Not managed
-
Persistent → Managed by EntityManager
-
Detached → Previously managed
-
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
deletedflag 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?
-
User logs in
-
Server validates credentials
-
Server generates JWT
-
Client sends JWT in every request
-
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