$ Spring Boot — Priority-Asked Interview Q&A
// Every question ever actually asked in an interview (Priority Count column) — consolidated from the master question bank, cross-referenced with the Spring Core / Boot / REST / JPA / Security cheat sheets in this folder
Target: TCS Java Spring Boot Developer interview, 20 Aug 2026 · Level: 5–8 years experience.
This single document is meant to be sufficient for full revision — every question below has a Priority Count in the master sheet, meaning it has genuinely come up in a past interview. Questions marked πŸ’Ό LinkedIn were specifically reported as asked via a LinkedIn-sourced interview experience.
42Total priority questions
60LinkedIn-sourced (πŸ’Ό)
14Topic sections
17Quick differences
Legend
πŸ’Ό LinkedIn Asked ×N ✓ Asked in Interview ×N Tracked (not yet asked) Level · YoE band
Spring Boot Fundamentals, Startup & Auto-Configuration (15 questions)
Deep-Dive — Auto-Configuration Internals (not in the priority list but frequently probed)
MechanismDetail
Spring Boot 2.xMETA-INF/spring.factories lists all EnableAutoConfiguration candidate classes.
Spring Boot 3.xMETA-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports replaces spring.factories for auto-configuration (faster startup, no per-class instantiation to check conditions).
@ConditionalOnClassBean is registered only if the given class is present on the classpath.
@ConditionalOnMissingBeanBacks off if the developer already defined a bean of that type — this is exactly how you override an auto-configured bean.
@ConditionalOnPropertyBean created only if a property matches (e.g. management.endpoint.health.enabled=true).
@AutoConfigureAfter/BeforeOrders auto-configuration classes relative to each other.
DevTools starter (spring-boot-devtools) adds: automatic restart on classpath change, LiveReload browser refresh, and disables template caching — excluded automatically from production repackaged JARs.
Spring Boot Fundamentals
✓ Asked in Interview ×1Fresher Β· 0–1 Year
Q. What is the purpose of the @SpringBootApplication annotation?
Also asked as:
  • Without @SpringBootApplication annotation will it work ?
  • Which annotations are included within @SpringBootApplication ?

used on the main class to bootstrap and start a Spring Boot application, combining @Configuration, @EnableAutoConfiguration, and @ComponentScan into a single annotation.

if No @SpringBootApplication β†’ Application may not work properly if Add: @Configuration, @EnableAutoConfiguration, @ComponentScan β†’ Works exactly the same

  • @Configuration β†’ Marks the class as a source of Spring bean definitions.
  • @EnableAutoConfiguration β†’ enables the Auto-Configuration mechanism & Auto-configures the Spring Boot based on the dependencies/libraries available in the classpath.
  • @ComponentScan β†’ Scans packages for Spring components (@Component, @Service, @Repository, @Controller) and registers them as Spring beans.
Basic Concepts
πŸ’Ό LinkedIn Asked ×1Fresher Β· 0–1 Year
Q. How do you run a Spring Boot application?
  • Using IDE (STS/IntelliJ/Eclipse) β†’ Run the main class containing the main() method and SpringApplication.run().
  • Using Maven β†’ Use Maven commands to start the application directly without creating a JAR file.
  • Using Gradle β†’ Use Gradle commands to build and run the application.
  • Using Executable JAR β†’ Package the application as a JAR file and run it independently using Java.
  • Using WAR Deployment β†’ Package the application as a WAR file and deploy it to an external application server such as Tomcat, WebLogic, or JBoss.
Spring Boot Internals
✓ Asked in Interview ×1Junior to Mid-Level Β· 1–3 Years
Q. What is the role of spring.factories?

Internal Flow:

  • Application starts with @SpringBootApplication.
  • @EnableAutoConfiguration is triggered.
  • Spring Boot reads the auto-configuration registrations. (spring.factories in older versions, AutoConfiguration.imports in Spring Boot 3.x).
  • It finds the list of AutoConfiguration classes.
  • Each AutoConfigurationclass is loaded.
  • Spring checks conditions like: - @ConditionalOnClass - @ConditionalOnMissingBean - @ConditionalOnProperty
  • If the conditions are satisfied, the required beans are created and registered in the ApplicationContext (IoC Container).
  • Your application starts with those beansavailable for use.
Spring Boot Internals
Tracked (not yet asked)Junior to Mid-Level Β· 1–3 Years
Q. What happens during application startup?

Startup Flow:

  • main() method executes and calls SpringApplication.run().
  • Spring Container is created.
  • Component Scanning scans and registers beans.
  • Dependency Injection injects required dependencies.
  • Auto-Configuration configures beans based on dependencies.
  • ApplicationContext is initialized.
  • Embedded Server (Tomcat) starts.
  • Application becomes ready to accept requests.
Spring Boot Internals
✓ Asked in Interview ×1Senior Β· 5–7 Years
Q. Explain the complete Spring Boot startup lifecycle.
main()
↓ Entry Point
SpringApplication.run()
↓ Start Application
Create ApplicationContext
↓ Create IoC Container
Load Configuration
↓ Load Properties/YAML
Component Scanning
↓ Find Components
Create Beans
↓ Instantiate Beans
Dependency Injection
↓ Inject Dependencies
Auto Configuration
↓ Configure Beans Automatically
Bean Initialization
↓ Run Init Methods
Embedded Tomcat Starts
↓ Start Web Server
Application Ready
Application Startup
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. CommandLineRunner vs ApplicationRunner

Both CommandLineRunner and ApplicationRunner execute code once after the Spring Boot application context is initialized. The difference is that : CommandLineRunner uses raw String... args, whereas ApplicationRunner uses the ApplicationArguments API for structured access to command-line arguments.

General
πŸ’Ό LinkedIn Asked ×1
Q. How do you optimize Spring application startup time?

Reduce Spring Boot startup time by enabling lazy initialization (spring.main.lazy-initialization=true), minimizing component scanning scope, avoiding unnecessary auto-configurations, excluding unneeded starters, and considering AOT/native compilation (Spring Native/GraalVM) for the most significant improvement.

Advanced Spring Boot
πŸ’Ό LinkedIn Asked ×2Mid-Level Β· 3–5 Years
Q. How can you exclude specific auto-configurations?
Also asked as:
  • disable specific auto-configuration?

Specific Auto-Configurations can be excluded using the exclude attribute of @SpringBootApplication or the spring.autoconfigure.exclude property in application.properties. This is commonly done when the default auto-configuration is not needed or a custom implementation is being used. @SpringBootApplication( exclude = {DataSourceAutoConfiguration.class} )

Auto Configuration
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. How do you override auto-configured beans in Spring Boot?

We can override an auto-configured bean by defining our own bean of the same type using @Bean method in a @Configuration class. Spring will use the custom bean instead of the auto-configured one (provided the auto-configuration is conditional).

Dependency Management
✓ Asked in Interview ×1Mid-Level Β· 3–5 Years
Q. What is the difference between Spring Boot Starter Dependencies and Manual Dependency Management?

Starter dependencies are predefined dependency packages that contains required libraries for a specific functionality : spring-boot-starter-web manual dependency management requires developers to add and maintain each dependency and its version individually. : jjwt-api

Dependency Management
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. spring-boot-starter-parent

spring-boot-starter-parent is the parent POM provided by Spring Boot. It manages dependency versions, plugin configurations, and default build settings, so we don't have to specify compatible versions manually.

Spring Boot Configuration
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. How do you disable the default web server in Spring Boot?
Also asked as:
  • Can we create a non-web application in Spring Boot?

We can disable the embedded web server by configuring the application as non-web. Using application.properties: spring.main.web-application-type=none

Yes. Spring Boot can be used to create a non-web application by disabling the web server using spring.main.web-application-type=none or WebApplicationType.NONE. This is commonly used for batch jobs, scheduled tasks, CLI applications, or Kafka consumers.

Embedded Server
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. How do you override or replace the embedded Tomcat server in Spring Boot?
Also asked as:
  • What if you don't want to use any embedded server?

Spring Boot uses Tomcat as the default embedded server. To replace it, we exclude spring-boot-starter-tomcat and add another embedded server dependency such as spring-boot-starter-jetty or spring-boot-starter-undertow.

If I don't want to use an embedded server, I can package the application as a WAR file, exclude the embedded Tomcat dependency, and deploy it to an external application server such as Apache Tomcat, JBoss/WildFly, or WebLogic.

Embedded Server
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. Which servers does Spring Boot support?

Spring Boot supports multiple embedded servers. The default is Tomcat, and it also supports Jetty and Undertow. It can also be deployed as a WAR file to external application servers.

Packaging & Deployment
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. JAR vs WAR

JAR (Java ARchive) is a standalone executable package that contains an embedded server like Tomcat. WAR (Web ARchive) is deployed to an external application server such as Tomcat, JBoss, or WebLogic.

IoC, Dependency Injection, Beans & Core Annotations (14 questions)
Dependency Injection & Beans
✓ Asked in Interview ×1Fresher Β· 0–1 Year
Q. What is Dependency Injection?
Also asked as:
  • How dependency injection work internally?

Dependency Injection (DI) is a design pattern where Spring creates and injects dependent objects (beans) into a class instead of the class creating them itself, reducing tight coupling and improving maintainability.

Internally :

  • Component Scanning β†’ Spring uses @ComponentScan to scan classes annotated with @Component, @Service, @Controller, and @Repository.
  • Bean Creation β†’ Based on the scanning, Spring creates and registersbeans in the IoC Container.
  • Dependency Resolution β†’ When a beanrequiresanotherbean as a dependency, Springsearches the IoC Container for the corresponding bean and resolves the dependency.
  • Dependency Injection β†’ Spring injects the required bean automatically using @Autowired or Constructor Injection.
  • Bean Ready for Use β†’ The fully initialized bean is readyfor use.
Dependency Injection & Beans
✓ Asked in Interview ×1Fresher Β· 0–1 Year
Q. What is the difference between @Component, @Controller, @Service, and @Repository?
  • @Component β†’ Generic bean. Create an bean of this class and manage its lifecycle in the Spring IoC Container.
  • @Controller β†’ Handles HTTP requests in Spring MVC and returns a view (or works with @ResponseBody).
  • @Service β†’ Business logic layer.
  • @Repository β†’ Database layer and provides exception translation for persistence exceptions.
Dependency Injection & Beans
✓ Asked in Interview ×2Fresher Β· 0–1 Year
Q. What is a Spring Bean?
Also asked as:
  • How does Spring manage bean lifecycle?

A Spring Bean is an object that is created, managed, and maintained by the Spring IoC Container.

  • Bean Creation β†’ Based on the scanning, Spring creates and registers beans in the IoC Container.
  • Dependency Injection β†’ Spring injects the required bean automatically using@Autowired or Constructor Injection.
  • Bean Initialization β†’ Initialization methods are executed (@PostConstruct, init-method).
  • Bean Ready for Use β†’ The fully initializedbean is ready for use.
  • Bean Destruction β†’ Before application shutdown, destruction methods are called (@PreDestroy, destroy-method).
Dependency Injection & Beans
πŸ’Ό LinkedIn Asked ×1Fresher Β· 0–1 Year
Q. What is the default scope of a Spring Bean?

singleton → One object/bean for Spring container (Default) - ApplicationContext prototype → New object/bean every request to Spring container - ApplicationContext request → One object/bean per HTTP request session → One object/bean per user session application→ One object/bean per web application - ServletContext websocket → One object/bean per WebSocket session

Dependency Injection & Beans
✓ Asked in Interview ×1Mid-Level Β· 3–5 Years
Q. What is @Resource Annotation?

β€’ @Resource is a Jakarta dependency injection annotation used to inject beans into a Spring-managed class. It performs dependency injection by bean name first and falls back to type-based resolution if no matching bean name is found.

Bean Configuration
✓ Asked in Interview ×1Mid-Level Β· 3–5 Years
Q. Difference between @Configuration and @Component?

a @Component creates a Spring-managed bean a @Configuration is used to define and manage other beans through @Bean methods.

Spring Container
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. How do you get the list of all beans in a Spring Boot application?

Spring stores all managed beans in the ApplicationContext. We can retrieve all bean names using applicationContext.getBeanDefinitionNames() and the total number of beans using getBeanDefinitionCount(). For runtime inspection, Spring Boot Actuator also provides the /actuator/beans endpoint.

Spring Core Annotations
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. What are the basic Spring Core annotations?
  • @Component -> Generic Spring bean
  • @Service -> Business logic layer
  • @Repository -> Data access layer
  • @Controller -> MVC controller
  • @RestController -> REST API controller (@Controller + @ResponseBody )
  • @Autowired -> Inject dependency
  • @Qualifier -> Select a specific bean when multiple exists
  • @Primary -> Default bean among multiple candidates
  • @Bean -> Creates a bean manually
  • @Configuration -> Configuration class containing @Bean methods
  • @ComponentScan -> Scans packages for Spring components
  • @Value -> Inject property values
  • @Scope -> Defines bean scope (Singleton, Prototype, etc.)
  • @PostConstruct -> Executes after bean initialization
  • @PreDestroy -> Executes before bean destruction
Core Annotations
πŸ’Ό LinkedIn Asked ×1
Q. What happens when we don't use stereotypes annotations in our spring boot application.

Without stereotype annotations (@Component, @Service, @Repository, @Controller), Spring's component scanning won't detect the class as a bean, so it won't be registered in the application context, and any attempt to @Autowire it elsewhere will fail with a NoSuchBeanDefinitionException.

Core Annotations
πŸ’Ό LinkedIn Asked ×1
Q. Spring Boot annotations

Common Spring Boot annotations include @SpringBootApplication (entry point), @RestController/@Controller, @Service, @Repository, @Component, @Autowired, @RequestMapping/@GetMapping/@PostMapping, @Transactional, and @Configuration/@Bean - each marks a class's role or wires behavior for Spring to manage automatically.

Core Annotations
πŸ’Ό LinkedIn Asked ×1
Q. Why we use those annotations

These annotations let Spring auto-detect, instantiate, and wire components without manual configuration - they declare intent (this is a service, this is a REST endpoint) so Spring's component scanning and dependency injection can manage the object lifecycle and relationships automatically, reducing boilerplate.

General
πŸ’Ό LinkedIn Asked ×1
Q. What is the Spring IoC Container?

The IoC Container is the core of Spring that manages the lifecycle and configuration of application objects (beans) - it creates, wires (injects dependencies into), and manages beans based on configuration (XML, annotations, or Java config), implemented via BeanFactory (basic) or ApplicationContext (advanced, most commonly used).

General
πŸ’Ό LinkedIn Asked ×1
Q. What are bean scopes in Spring?

Spring bean scopes control how many instances of a bean are created: singleton (one instance per container, default), prototype (new instance every time it's requested), and web-aware scopes like request, session, and application for web applications.

General
πŸ’Ό LinkedIn Asked ×1
Q. What are circular dependencies in Spring?

A circular dependency occurs when two or more beans depend on each other (directly or through a chain). Spring can usually resolve this for singleton beans via setter injection (partially constructed beans exposed early), but constructor injection circular dependencies fail at startup - resolved by refactoring the design, using @Lazy, or switching to setter injection.

Configuration, Profiles & Externalization (3 questions)
Deep-Dive — Property Source Precedence (highest wins)
1Command-line arguments (--server.port=8081)
2SPRING_APPLICATION_JSON / JNDI attributes
3OS environment variables
4application-{profile}.properties / .yml (profile-specific, outside jar > inside jar)
5application.properties / .yml (outside jar > inside jar)
6@PropertySource on @Configuration classes
7Default properties set via SpringApplication.setDefaultProperties
This is exactly why "I changed application.properties but nothing changed in production" (see Troubleshooting section) is so common — an env var or CLI flag higher in this order silently wins.
Configuration & Properties
✓ Asked in Interview ×1Fresher Β· 0–1 Year
Q. How do you read a property using @Value?
Also asked as:
  • how to fetch value from application.properties or application.yml file?

Values from application.properties or application.yml can be accessed using @Value, @ConfigurationProperties, or the Environment interface. Single Property β†’ @Value("${app.name}") Multiple Properties β†’ @ConfigurationProperties(prefix = "app") Dynamic Access β†’ Environment (String appName = environment.getProperty("app.name"); )

Configuration & Properties
✓ Asked in Interview ×3Fresher Β· 0–1 Year
Q. How can you define environment-specific configurations?
Also asked as:
  • What are Spring Profiles?
  • How do you activate a specific profile?
  • How do you manage configurations across environments?
  • What is the purpose of application-dev.properties?

Spring Profiles are used to manage environment-specific configurations and beans for different environments such as Development, Testing, STQA, and Production. Example : application-dev.properties, application-stqa.properties, and application-prod.properties Activate a profile: spring.profiles.active=dev

A specific Spring Profile can be activated using the spring.profiles.active property, which tells Spring Boot which environment configuration to load.

application-dev.properties is used to store environment-specific configuration settings for the Development environment.

Configuration & Profiles
✓ Asked in Interview ×2Junior to Mid-Level Β· 1–3 Years
Q. What is Externalization in Java?
Also asked as:
  • How do you externalize configuration?
  • How does Spring Boot handle externalized configuration?
  • Externalization is the practice of keeping configuration values outside the application code.
  • Configuration is externalized by storing configuration values outside the application code using properties files, YAML files, environment variables, or command-line arguments.
  • Spring Boot handles externalized configuration by loading configuration values from properties files, YAML files, environment variables, command-line arguments, and Spring Profiles.
Spring MVC & REST API (10 questions)
REST API Basics
πŸ’Ό LinkedIn Asked ×1Fresher Β· 0–1 Year
Q. What is REST?

REST (REpresentational State Transfer) is an architectural style for web services that enables communication between client and server using HTTP methods such as GET, POST, PUT, and DELETE. GET β†’ Retrieve data POST β†’ Create data PUT β†’ Update entire resource PATCH β†’ Partial update DELETE β†’ Delete data

REST API Basics
πŸ’Ό LinkedIn Asked ×1Fresher Β· 0–1 Year
Q. What is @RequestParam?
Also asked as:
  • How do you receive query parameters in Spring Boot?

β€’ @RequestParam is used to extract query parameter values from the request URL path and bind them to method parameters. eg: /employee?id=101 UseCase: filter, search, sort, paginate, or pass optional data

REST APIs
✓ Asked in Interview ×1Junior to Mid-Level Β· 1–3 Years
Q. What is pagination in Spring Data JPA ?
Also asked as:
  • How do you implement pagination in REST APIs?
  • What is pagination and sorting in Spring Data JPA?

Pagination is a technique used to retrieve data in smaller chunks (pages) instead of loading all records at once, improving performance and reducing memory consumption. Pagination is implemented using Spring Data JPA's Pageable interface and Page<T> response.

REST APIs
✓ Asked in Interview ×1Junior to Mid-Level Β· 1–3 Years
Q. What is sorting in Spring Data JPA ?
Also asked as:
  • How do you implement sorting in Spring Data JPA?
  • What is pagination and sorting in Spring Data JPA?

Sorting is the process of retrieving data in a specific order based on one or more fields, such as ascending or descending order. Sorting is implemented using Spring Data JPA's Sort class OR by combining Pageable with sorting parameters.

Spring MVC & REST
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. MVC vs REST API

Spring MVC is a web framework that follows the Model-View-Controller pattern to build server-side web applications by returning views like JSP or Thymeleaf. REST is an architectural style used to build stateless web services that return data, typically in JSON or XML format.

REST & JSON
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. How does JSON conversion happen in Spring Boot?
Also asked as:
  • HttpMessageConverter?

In Spring Boot, JSON conversion is handled automatically by HttpMessageConverter. By default, Spring Boot uses the Jackson library to convertJava objects to JSON and JSON to Java objects.

REST & JSON
✓ Asked in Interview ×1Mid-Level Β· 3–5 Years
Q. How REST calls work
  • Client sends request.
  • Spring's DispatcherServlet receives it.
  • Request is mapped to the appropriate Controller method.
  • Controller calls Service.
  • Service calls Repository.
  • Repository fetches data from DB.
  • Data travels back to Controller.
  • Spring converts Java Object to JSON using Jackson.
  • Response is returned to the client
General
✓ Asked in Interview ×1Junior to Mid-Level Β· 1–3 Years
Q. how to create post api in spring boot?

A POST API is created using the @PostMapping annotation. It is typically used to create new resources in the database. The request data is typically received using @RequestBody, processed in the Service layer, saved through the Repository layer, and a response is returned to the client.

REST APIs
πŸ’Ό LinkedIn Asked ×1
Q. How to make external API call from service class.

Inject a RestTemplate or WebClient bean into the service class and use it to make the HTTP call (e.g., restTemplate.getForObject(url, ResponseType.class)), keeping the call encapsulated within the service layer rather than the controller so business logic and external integration stay separated.

General
πŸ’Ό LinkedIn Asked ×1
Q. What is HandlerInterceptor?

HandlerInterceptor is a Spring MVC interface used to intercept HTTP requests before, after, or once a controller handler completes (preHandle, postHandle, afterCompletion) - commonly used for cross-cutting concerns like logging, authentication checks, or request timing without modifying controller code.

Validation & Exception Handling (4 questions)
Exception Handling
πŸ’Ό LinkedIn Asked ×1Junior to Mid-Level Β· 1–3 Years
Q. How do you implement global exception handling?

Global exception handling is implemented using @ControllerAdvice and @ExceptionHandler. It centralizes exception handling across the application and returns consistent error responses to clients.

Exception Handling
✓ Asked in Interview ×3Junior to Mid-Level Β· 1–3 Years
Q. What is @ControllerAdvice?

β€’ @ControllerAdvice β†’ Handles exceptions globally across all controllers. It works with @ExceptionHandler to catch exceptions from all controllers and return a common error response.

Validation
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. what is a @Valid vs @Validated

a @Valid is used for basic bean validation a @Validated extends it by supporting validation groups and method-level validation.

Exception
✓ Asked in Interview ×2Mid-Level Β· 3–5 Years
Q. how to handle custom exception in spring?
Also asked as:
  • how to handle exception using annotation in spring application?

Custom exceptions are handled by creating a custom exception class that extends RuntimeException and implementing global exception handling using @ControllerAdvice and @ExceptionHandler, which returncustomerrorresponses.

Spring Data JPA, Hibernate, Transactions & DB Access (13 questions)
Deep-Dive — Propagation, Isolation, Locking & Entity Lifecycle
PropagationBehavior
REQUIRED ⭐Join existing transaction, or create a new one if none exists (default).
REQUIRES_NEWAlways suspends the current transaction and starts a brand-new one — used for audit-logging that must persist even if the outer transaction rolls back.
SUPPORTSJoins if a transaction exists, otherwise runs non-transactionally.
MANDATORYMust run inside an existing transaction, else throws an exception.
NOT_SUPPORTEDSuspends any existing transaction and runs non-transactionally.
NEVERThrows an exception if a transaction already exists.
NESTEDRuns within a savepoint of the outer transaction — a failure here can roll back to the savepoint without rolling back the whole outer transaction.
Isolation LevelPrevents
READ_UNCOMMITTEDNothing — allows dirty reads.
READ_COMMITTED ⭐Dirty reads (DB default for most engines, incl. PostgreSQL/Oracle).
REPEATABLE_READDirty reads + non-repeatable reads (MySQL InnoDB default).
SERIALIZABLEDirty, non-repeatable & phantom reads — safest, slowest, transactions effectively run one at a time.
Optimistic Locking (@Version)
Detects conflicts at update time by comparing a version column. Admin A reads v1, Admin B reads v1, A saves → v2. B tries to save with v1 → Hibernate throws OptimisticLockException. Best for low-contention, high-read scenarios (no DB lock held).
Pessimistic Locking (SELECT ... FOR UPDATE)
Locks the row for the duration of the transaction so nobody else can read/write it. Best for high-contention scenarios like account-balance withdrawals where lost updates are unacceptable.
Transient new Entity(), not attached to any session
↓ persist()
Persistent / Managed tracked by the Persistence Context
↓ session / EntityManager closes
Detached still has an ID, no longer tracked
↓ remove()
Removed
Dirty Checking: for a managed entity, Hibernate compares its current state to a snapshot taken at load time; any changed field is automatically included in the UPDATE at flush time — no explicit save() call needed inside a transaction. Flush vs Commit: flush synchronizes the persistence context with the DB (sends SQL) but doesn't end the transaction; commit ends the transaction (making changes durable) and triggers a flush first. save() just schedules the entity for persistence at next flush; saveAndFlush() forces an immediate flush — useful when you need the DB-generated ID or a trigger-computed value right away.
Spring Data JPA
✓ Asked in Interview ×1Junior to Mid-Level Β· 1–3 Years
Q. What is the difference between CrudRepository and JpaRepository?

CrudRepository provides basic CRUD operations JpaRepository provides CRUD operations along with advanced JPA features such as pagination and sorting.

Spring Data JPA
πŸ’Ό LinkedIn Asked ×1Junior to Mid-Level Β· 1–3 Years
Q. What is the purpose of the @Query annotation?

β€’ @Query is used to write custom JPQL or native SQL queries in a repository when derived query methods are not sufficient.

Spring Data JPA
✓ Asked in Interview ×2Junior to Mid-Level Β· 1–3 Years
Q. What is the difference between JPQL and SQL?

JPQL is an object-oriented query language that works with JPA entities and their fields. SQL works directly with database tables and columns.

JPA & Database Optimization
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. What is the N+1 query problem?

The N+1 query problem occurs when Hibernate executes one query to fetch the parent entities and then executes one additional query for each parent entity to fetch its related child entities, resulting in a total of N+1 queries. causes performance issues due to excessive database calls.

Example: Suppose we have a Department entity, and each department has multiple Employee entities. When we fetch all departments, Hibernate executes one query to fetch the departments and then one additionalquery for the employees of eachdepartment. If there are N departments, a total of N+1 queries are executed. This performance issue is called the N+1 Query Problem.

JPA & Database Optimization
✓ Asked in Interview ×1Mid-Level Β· 3–5 Years
Q. How do transactions work in Spring Boot?
Also asked as:
  • How does @Transactional work internally?
  • Why @Transaction needed?.

β€’ @Transactional is used to ensure data consistency by treating multiple database operations as a single unit of work. If alloperations succeed, the transaction is committed; if anyoperation fails, all changes are rolled back.

Internally, Spring uses AOP to create a proxy for methods annotated with @Transactional. Every call first goes to the proxy, which starts the transaction, executes the business method, and then commits the transaction if everything succeeds or rolls it back if an exception occurs.

Transaction Management
πŸ’Ό LinkedIn Asked ×1Senior Β· 5–7 Years
Q. Why does self-invocation break transactions?

Spring's @Transactional (and @Async, @Cacheable, etc.) works via proxies - when a method calls another method on 'this' within the same class, the call bypasses the proxy entirely and goes directly to the target object, so the transactional advice never gets applied. Fix by calling through a self-injected proxy, or moving the method to a separate bean.

Transaction Management
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. @Transactional is present but rollback did not happen. Why?

If @Transactional doesn't roll back, I check the exception type(it should be unchecked exception), ensure the exception isn't swallowed, verify proxy-based transaction behavior (such as self-invocation), and configure rollbackFor when handling checked exceptions.

JPA & Hibernate
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. Lazy loading causes an exception in production but not locally. Why?

This is usually caused by a LazyInitializationException. It happens when a lazily loaded entity is accessed after the Hibernate session has been closed. It may work locally because of different configurations (such as Open Session in View enabled), but fail in production where the session is closed before the lazy association is accessed.

General
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. JPA vs Hibernate

JPA is a specification that defines standards for ORM in Java, while Hibernate is the most popular implementation of JPA. In Spring Boot, we usually write code using JPA APIs, and Hibernateperforms the actual database operationsbehind the scenes.

General
✓ Asked in Interview ×1Mid-Level Β· 3–5 Years
Q. How do you get data from the database?

Data is retrieved from the database using the Repository layer. The Controller calls the Service layer, the Service calls the Repository, and the Repository fetches the data from the database using JPA/Hibernate.

General
✓ Asked in Interview ×1Mid-Level Β· 3–5 Years
Q. how to do database connection through spring

Database connectivity in Spring Boot is configured using datasource properties. During startup, Spring Boot reads these properties, creates a DataSource bean, configures a connection pool (HikariCP by default), and provides databaseconnections to JPA or JDBC components.

General
✓ Asked in Interview ×1
Q. How can multiple data sources be configured?

In Spring Boot, multiple data sources are configured by defining separate DataSource beans for each database and, when using JPA, separate EntityManagerFactory and transaction manager configurations. @Primary defines the default data source and @Qualifier allows explicit selection. Each repository package can then be associated with the appropriate EntityManager. Common use cases include multiple databases, read/write separation, legacy database integration, and reporting databases. In microservices, however, the preferred approach is usually database-per-service rather than having one service directly access multiple service-owned databases.

General
πŸ’Ό LinkedIn Asked ×1
Q. How does Spring integrate with JDBC?

Spring integrates with JDBC through JdbcTemplate, which handles boilerplate like opening/closing connections, exception translation into Spring's DataAccessException hierarchy, and resource cleanup, letting you focus on writing SQL and mapping results via RowMapper instead of manual JDBC plumbing.

Spring Security & JWT (6 questions)
Deep-Dive — JWT Structure, OAuth2/OIDC, CSRF & Method Security
JWT = Header.Payload.Signature
Header → token type + signing algorithm (HS256/RS256). Payload → claims: sub, roles, iat, exp. Signature → HMAC/RSA over encoded header+payload using a secret/private key, so the server can detect tampering without a DB lookup (stateless).
OAuth2 vs OpenID Connect
OAuth2 → Authorization framework; grants an app an Access Token to call an API on the user's behalf (e.g. "Sign in with Google" reading your calendar). OIDC → Authentication layer built on top of OAuth2; adds an ID Token (JWT) that proves who the user is.
CSRF
Attack where a malicious site tricks an authenticated browser into firing a state-changing request using the victim's session cookie. Spring Security issues a per-session CSRF token validated on every POST/PUT/PATCH/DELETE. Enabled by default for cookie/session auth; typically disabled for stateless JWT APIs since there's no session cookie to ride on.
MechanismUse
hasRole() / hasAuthority()URL-level authorization inside SecurityFilterChain config.
@PreAuthorizeMethod-level, evaluated before invocation — supports SpEL, e.g. @PreAuthorize("hasRole('ADMIN')").
@PostAuthorizeEvaluated after method execution — can inspect the return value.
@SecuredSimpler, legacy role-based method security (no SpEL).
@EnableMethodSecurityEnables method-level annotations (Spring Security 6+).
Refresh tokens: short-lived access token (minutes) + longer-lived refresh token stored securely (HttpOnly cookie or DB-tracked) to mint new access tokens without re-login; rotate the refresh token on every use and blacklist old ones to limit replay if stolen.
Security
✓ Asked in Interview ×1Junior to Mid-Level Β· 1–3 Years
Q. What is Spring Security?

Spring Security is a framework that provides authentication, authorization, and protection against common security vulnerabilities for Spring applications.

Security
✓ Asked in Interview ×2Junior to Mid-Level Β· 1–3 Years
Q. What is Authentication?

Authentication is the process of verifying the identity of a user before granting access to an application, ensuring that the user is who they claim to be. User enters username and password -> System validates the credentials -> If valid, the user is authenticated.

For example, in the Candidate Registration Portal, when a candidate enters a username and password, the Authentication Service verifies the credentials. If they are valid, the user is authenticated and allowed to access the portal.

Authentications Different Methods:

  • Session-Based Authentication
  • JWT Authentication
  • OAuth2 Authentication
  • LDAP(Lightweight Directory Access Protocol) Authentication
  • Basic Authentication
  • OTP Authentication
Security
✓ Asked in Interview ×2Junior to Mid-Level Β· 1–3 Years
Q. What is Authorization?

Authorization is the process of determining what resources or actions an authenticated user is allowed to access/perform.

For example, in the Candidate Registration Portal, after a user logs in, the system checks their role. An Admin can manage users, while a Candidate can only register for exams and view certificates. If a Candidate tries to access an Admin-only feature, the system denies access.

Security
✓ Asked in Interview ×2Mid-Level Β· 3–5 Years
Q. What is JWT?
Also asked as:
  • How does JWT authentication work?
  • How do you implement JWT in Spring Boot?

In JWT authentication, a user logs in with valid credentials, and the server generates a signed JWT token. The client sends this token in the Authorization header with each request. Spring Security validates the token, extracts user details and roles, and authenticates the request withoutmaintaining server-side sessions.

User Login β†’ Validate Credentials β†’ Generate Signed JWT β†’ Client sends "Authorization: Bearer <JWT>" β†’ Validates Token β†’ Extract User & Roles β†’ Authorize Request

To implement JWT in Spring Boot, I authenticate the user using Spring Security, generate a JWT token upon successful login, create a JWT filter to validate tokens for incoming requests, and configure Spring Security to use stateless authentication with JWT tokens instead of sessions.

Security
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. How does Spring Security filter chain work?
Also asked as:
  • How does the SecurityFilterChain work internally?

Spring Security intercepts every request through the SecurityFilterChainbefore it reaches the Controller. The request passes through multiple filters that perform authentication, authorization, token validation, session management, and exception handling. If authentication and authorization succeed, the request proceeds to the Controller; otherwise, an error response is returned.

Security
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. How to store custom sensitive data like account information in DB?

I store sensitive data in encrypted form using algorithms like AES-256, keep encryption keys in a secure key management system, and decrypt the data only when it is required.

Caching, Async & Scheduling (3 questions)
Caching
✓ Asked in Interview ×2Mid-Level Β· 3–5 Years
Q. What is caching?
Also asked as:
  • How does Cache work?
  • How do you enable caching in Spring Boot?

Caching is a technique used to store frequently accessed data in memory to reduce database calls and improve application performance. On the first request, data is fetched from the database and stored in the cache. Subsequentrequests are served directly from the cache until the cache is updated or invalidated.

  • Caching is enabled in Spring Boot using the @EnableCaching annotation. After enabling caching, below annotations used to manage cached data.
  • @EnableCaching β†’ Enablescaching in the Spring Boot application.
  • @Cacheable β†’ Reads from cache; on Cache Miss, executes the method and stores the result in the cache.
  • @CachePut β†’ Always executes the method and updates the cache.
  • @CacheEvict β†’Removes specific cache data or clears the entire cache.
  • @Caching β†’ Combines multiple cache operations on a single method.
Multithreading
✓ Asked in Interview ×2Mid-Level Β· 3–5 Years
Q. what is @Async annotation?

β€’ @Async is used to execute methods asynchronously in a separate thread. It is commonly used for long-running tasks such as sending emails, file processing, and external API calls to improve application responsiveness. Save User in DB β†’ Return Response β†’ Send Email in Background

Scheduling
πŸ’Ό LinkedIn Asked ×1
Q. Full view of Schedular Mechanism.

Spring's scheduling is enabled via @EnableScheduling on a configuration class, then methods annotated with @Scheduled (using fixedRate, fixedDelay, or a cron expression) run automatically on a background thread pool at the specified interval, useful for periodic tasks like cleanup jobs or batch processing.

Microservices & Resilience (3 questions)
Deep-Dive — Resilience4j Patterns & Inter-Service Communication
PatternPurpose
Circuit BreakerStops calling a repeatedly failing downstream service for a cool-down period, failing fast instead of piling up threads.
RetryRe-attempts a failed call a bounded number of times, usually with backoff, for transient failures.
BulkheadCaps concurrent calls to a dependency so one slow downstream can't exhaust the whole thread pool.
Rate LimiterRestricts number of calls in a time window.
Time LimiterBounds how long a call is allowed to take before it's treated as a failure.
FallbackAlternate response/logic executed when the primary call ultimately fails.
RestTemplate
Synchronous, blocking. Legacy — in maintenance mode since Spring 5.
WebClient
Reactive, non-blocking. Preferred for new code, especially high-concurrency/streaming.
OpenFeign ⭐
Declarative interface-based HTTP client, integrates directly with Eureka/load-balancer and Resilience4j — most common choice inside a microservices stack.
Kafka basics: Producer publishes to a Topic (partitioned) → Consumer(s) in a Consumer Group read from partitions (each partition consumed by only one member of a group, giving horizontal scalability); offset tracks each consumer's read position, enabling replay. @KafkaListener subscribes a method to a topic.
Scalability & Reliability
πŸ’Ό LinkedIn Asked ×1Senior Β· 5–7 Years
Q. How would you implement rate limiting?

Implement rate limiting using a token-bucket or sliding-window algorithm, either in application code (e.g., Bucket4j) or at the gateway/infrastructure level (API Gateway, Nginx, Redis-backed distributed limiter for multi-instance deployments) - track request counts per client/API key within a time window and reject or throttle once the limit is exceeded.

Scalability & Reliability
✓ Asked in Interview ×1Senior Β· 5–7 Years
Q. How does Resilience4j work?

Resilience4j works by decorating application calls with fault-tolerance mechanisms. For example, when Booking Service calls Payment Service, Resilience4j can apply a timeout to prevent indefinite waiting, retry temporary failures, use a circuit breaker to stop calls after repeated failures, limit concurrent calls using a bulkhead, restrict request rates with a rate limiter, and execute a fallback when the call ultimately fails. These mechanisms prevent cascading failures and improve the resilience and availability of microservices.

Microservices
✓ Asked in Interview ×2Mid-Level Β· 3–5 Years
Q. How do you call a different service in Spring Boot?

A different service can be called using HTTP clients such as RestTemplate, WebClient, or Feign Client. RestTemplate is typically used in legacy applications. WebClient is preferred for new applications because it supports non-blocking communication. Feign Client is commonly used In microservices architectures, because it simplifiesservice-to-service communication and reduces boilerplate code.

Testing, Quality & Tooling (3 questions)
Deep-Dive — Test Slices & TestContainers
AnnotationLoads
@WebMvcTestOnly the web/MVC layer (controllers, filters, converters) — services/repos mocked with @MockBean.
@DataJpaTest ⭐Only the JPA layer against an in-memory H2 DB by default; each test runs in a transaction that's rolled back afterward.
@SpringBootTestFull application context — real end-to-end integration test, slower.
@Mock / @InjectMocksPure Mockito unit tests with no Spring context at all — fastest, ideal for service-layer logic.
MockMvcTests controllers/REST endpoints without starting a real HTTP server.
TestContainers: spins up real Docker containers (MySQL, PostgreSQL, Redis, Kafka) for integration tests, avoiding the "works on H2, breaks on real MySQL" class of bugs caused by dialect/behavior differences.
Testing & Quality
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. How do you test service-layer logic?

Service-layer logic is tested using JUnit and Mockito. Dependencies such as repositories and external services are mocked, allowing the test to focus only on business logic, validations, calculations, and exception handling within the service layer.

Junit
πŸ’Ό LinkedIn Asked ×1
Q. How does JUnit help improve code quality?

JUnit improves code quality by catching bugs early through automated regression testing, encouraging modular/testable design, enabling safe refactoring (tests confirm behavior didn't break), and serving as executable documentation of expected behavior.

Build / Tooling
✓ Asked in Interview ×2
Q. SonarQube: class exceeds line-limit rule β€” how to resolve (specific scenario)

If SonarQube reports that a class exceeds the line limit, I would first analyze the class and identify different responsibilities inside it. Instead of simply increasing or suppressing the SonarQube limit, I would refactor the class into smaller, focused classes following Single Responsibility Principle. For example, if a service class handles validation, payment processing, notification, reporting, and database operations, I would extract those responsibilities into separate services or components.

Performance, Monitoring, Actuator & JVM (7 questions)
Deep-Dive — HikariCP Tuning & Actuator Endpoints
PropertyMeaning
maximum-pool-sizeHard cap on total connections — size it to ((core_count * 2) + effective_spindle_count) as a starting heuristic, then load-test; bigger isn't always faster because of DB-side contention.
minimum-idleConnections kept ready even when idle.
connection-timeoutMax wait for a connection from the pool before throwing an exception.
idle-timeoutHow long a connection can sit idle before being retired.
max-lifetimeMax connection age before it's recycled (should be a few minutes less than any DB/firewall imposed connection timeout).
leak-detection-thresholdLogs a warning if a connection is checked out longer than this, which usually points to a leak (not returned to the pool).
EndpointShows
/actuator/healthLiveness/readiness, DB & downstream health indicators.
/actuator/metricsJVM, HTTP, DataSource metrics (usually scraped by Prometheus).
/actuator/envResolved environment properties (sensitive values sanitized).
/actuator/beansAll beans in the ApplicationContext.
/actuator/loggersView/change log levels at runtime without a redeploy.
/actuator/threaddump & /heapdumpLive diagnostics for stuck threads / memory investigations.
Custom endpoint: annotate a bean with @Endpoint(id="myendpoint") and expose read operations with @ReadOperation. JVM triage checklist for "memory keeps growing": capture a heap dump, compare object histograms across two snapshots, check for unbounded caches/static collections/unclosed streams, and watch GC logs for rising old-gen occupancy after full GCs (a real leak, vs. sawtooth pattern which is normal).
Basic Concepts
✓ Asked in Interview ×2Fresher Β· 0–1 Year
Q. What is Spring Boot Actuator?
Also asked as:
  • What are Actuator endpoints?
  • What are health endpoints?
  • How do you monitor application health?
  • How do you expose custom Actuator endpoints?

Actuator endpoints are production-ready REST endpoints provided by Spring Boot Actuator for monitoring and managing application health, metrics, and runtime status/actuator/health β†’ Shows application health status. /actuator/info β†’ Displays application information. /actuator/metrics β†’ Provides application metrics. /actuator/env β†’ Shows environment properties. /actuator/beans β†’ Lists all Spring beans.

Spring Boot Actuators provides the health endpoint to check the health & availability status of an application and its dependentservices.

Custom Actuator endpoints can be exposed by creating a class annotated with @Endpoint and exposing it through Spring Boot Actuator.

Performance & Monitoring
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. What metrics should be monitored in production?

In production, I monitor application, JVM, database, infrastructure, and businessmetrics to ensure system health, performance, and availability.

  • Application Metrics: API Response Time, Request Count (TPS/RPS), Error Rate (4xx/5xx), Throughput, API Latency
  • JVM Metrics: Heap Memory, Non-Heap Memory, Garbage Collection (GC), Thread Count, CPU Usage
  • Database Metrics: Query Execution Time, Slow Queries, Active Connections, HikariCP Connection Pool Usage, Database Response Time, Deadlocks
  • Infrastructure Metrics: CPU Utilization, Memory Usage, Disk Usage, Network Traffic, Container/VM Health
  • Business Metrics: Successful Payments, Failed Payments, Seat Bookings, Admit Card Downloads, Certificate Generation
Logging & Debugging
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. How do you enable debugging logs in Spring Boot?

We can enable debugging logs by setting debug=true or configuring the logging level in application.properties. DEBUG is mainly used during development to troubleshoot issues. In production, we usually enable DEBUG only for specific packages.

JVM Performance
πŸ’Ό LinkedIn Asked ×2Mid-Level Β· 3–5 Years
Q. Application memory usage keeps increasing over time. What would you do?

If the application's memory usage keeps increasing, I would first determine whether it's a memory leak or normal memory growth. I would monitor JVM heap usage, analyze GC logs, capture a heap dump, and identify objects consuming memory. Then I would fix issues such as memory leaks, unclosed resources, large caches, or excessive object creation.

Performance Tuning
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. REST API returns data but response time is inconsistent. Why?

If a REST API returns data but the response time is inconsistent, I would investigate whether the latency is caused by slow database queries, external API calls, thread or connection pool contention,garbage collection pauses, network latency, or varying server load. I would use application logs, APM tools, SQL execution plans, and JVM metrics to identify the bottleneck.

Performance & Async Processing
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. Background jobs are affecting API response time. How do you isolate them?

I isolate background jobs by moving them to dedicated thread pools, asynchronous workers, or message queues so they do not compete with REST APIs for CPU, threads, or database connections.

General
✓ Asked in Interview ×1Mid-Level Β· 3–5 Years
Q. How to Optimize the Rest API?
Also asked as:
  • API is fast locally but slow in production. How do you debug?

APIs can be optimized by optimizing database queries, using pagination and caching, returning DTOs, tuning connection pools, optimizing external API calls, using asynchronous processing, and continuously monitoring application performance.

  • Optimize Database Queries: Add indexes, avoid full table scans, optimize joins, fix N+1 query issues, and use Fetch Join or Entity Graph.
  • UsePagination: Instead of loading all records at the same time, fetch data in smaller pages.
  • ImplementCaching: Cache frequently accessed data to reduce database calls.
  • Return DTOs: Instead of returning entire entities, return DTOs containing only the required fields.
  • OptimizeExternal API Calls: Configure timeouts, use retries carefully, and use @Async processing when appropriate.
  • Connection Pool Tuning: Configure and tune the connection pool (e.g., HikariCP) to efficiently manage database connections and avoid connection exhaustion.
  • Asynchronous Processing: Use @Async, Kafka, or message queues for long-running operations such as email sending, notifications, and report generation.
  • Monitor : Use Spring Boot Actuator and monitoring tools such as Grafana and Prometheus to identify performance bottlenecks.
Production Troubleshooting (Realtime Scenarios) (11 questions)
Realtime
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. Spring Boot works locally but fails in deployment/production.

If a Spring Boot application works locally but fails in production, I start by checking the logs, then verify the environment configuration, database connectivity, dependencies, external services, and server resources to identify and resolve the root cause.

Realtime
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. You changed application.properties but nothing changed in production. Why?

If changes to application.properties are not reflected in production, I would check whether the application was restarted, whether the correct configuration file is being used, if environment variables are overriding the properties, whether the correct Spring profile is active, and if the latest build was actually deployed.

Realtime
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. Under high traffic, your service crashed even though CPU usage is low. Why?

Low CPU usage doesn't necessarily mean the application is healthy. The service may crash due to database connection pool exhaustion, thread pool exhaustion, memory issues, blocked threads, external API delays, or resource limits. I would analyze logs, thread dumps, heap usage, connection pools, and external dependencies to identify the bottleneck.

Realtime
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. Multiple beans of the same type exist and the application fails to start. How do you fix it?

When multiple beans of the same type exist, Spring cannot determine which bean to inject and throws a NoUniqueBeanDefinitionException. I can resolve this by using @Qualifier, marking one bean as @Primary, or injecting a specific bean by its name.

Realtime
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. API is randomly returning 401/403. What should you check?

I would first determine whether it's a 401 (Authentication) or 403 (Authorization) issue. Then I would verify the JWT token, user roles/permissions, Spring Security configuration, token expiration, request Authorization headers, and application logs to identify the root cause.

Realtime
πŸ’Ό LinkedIn Asked ×2Mid-Level Β· 3–5 Years
Q. Database connection pool is suddenly exhausted. How do you identify and fix it?

I would first check the application logs and monitor the connection pool metrics to confirm that all database connections are in use. Then I would identify the root cause, such as connection leaks, slow SQL queries, long-running transactions, or increased traffic. Finally, I would optimize queries, ensure connections are properly released, tune the HikariCP pool configuration, and scale the application if necessary.

Deployment
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. Users still see old behavior after a new deployment. What went wrong?

If users still see the old behavior after deployment, I would verify that the new version was actually deployed, the application was restarted successfully, caches were refreshed, the correct configuration/profile is beingused, and the load balancer or reverse proxy is routing traffic to the updatedinstances.

Logging & Monitoring
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. Logs are missing in production. What should you check?

If logs are missing in production, I would verify the logging configuration, log level, log file path, application permissions, active Spring profile, log rotation settings, and whether logs are being forwarded correctly to the centralized logging system.

Deployment
πŸ’Ό LinkedIn Asked ×2Mid-Level Β· 3–5 Years
Q. What is Zero Downtime Deployment? How do you achieve it?

Zero Downtime Deployment is a deployment strategy where a new application version is released without interrupting service or causing downtime for users. This is achieved by deploying the new version alongside the existing one and switching user traffic only after the new version is verified to be healthy.

Docker & Deployment
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. Application behaves differently in Docker than locally. Why?

If an application behaves differently in Docker than locally, I compare the runtime environments. Common causes include different environment variables, Spring profiles, Java versions, Docker networking, mounted volumes, file paths, resource limits, or missing dependencies. I verify the container configuration, inspect logs, and compare both environments to identify the difference.

Production Best Practices
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. What are the most common Spring Boot mistakes that break production?

Most production issues are caused by configuration mistakes, inefficient database access, poor exception handling, resource leaks, security misconfigurations, and inadequate monitoring. Preventing these issues requires proper testing, monitoring, logging, and following Spring Boot best practices.

Real-World / System Design Scenarios (7 questions)
Deep-Dive — Idempotency, Soft Delete, Audit Logging & Zero-Downtime Deploys
Idempotency — executing the same request N times has the same effect as executing it once; implemented via a client-supplied Idempotency-Key header checked against a DB unique constraint before processing.
Soft Delete — add a deleted/is_active flag instead of a physical DELETE; Hibernate's @SQLDelete rewrites the delete into an update, and @Where transparently filters deleted rows out of every query.
Audit Logging — capture who/what/when/where for sensitive actions (login, create, update, delete); can be done declaratively with Spring Data JPA Auditing (@CreatedBy/@LastModifiedBy/@CreatedDate), an AOP aspect around service methods, or a dedicated audit-event table/service.
Blue-Green Deployment — two identical environments; deploy to the idle one, validate, then flip the router/load-balancer — instant rollback by flipping back.
Canary Deployment — route a small % of live traffic to the new version first, watch error rates/latency, then ramp up.
Rolling / Kubernetes Rolling Update — replace instances/pods a few at a time while keeping enough healthy replicas to serve traffic throughout.
Real-World Scenarios
πŸ’Ό LinkedIn Asked ×13–5 Years
Q. How would you handle duplicate API requests?
Also asked as:
  • How would you handle duplicate payments?

I would handle duplicate API requests using idempotency keys, unique database constraints, and validation checks. Beforeprocessing a request, the system verifies whether the request has already been processed. If it has, the previouslystored response is returned instead of executing the operation again.

Real-World Scenarios
✓ Asked in Interview ×2Mid-Level Β· 3–5 Years
Q. How would you troubleshoot slow API responses?
Also asked as:
  • suppose api taking time how to do analysis and resolve.
  • why the application is getting slow?.

I would start by identifying whether the delay is coming from the database, application code, external services, or infrastructure. I would analyze logs, SQL queries, CPU and memory usage, connectionpools, and downstream servicecalls. Once the bottleneck is identified, I would optimize the relevant component and measure the improvement.

System Design & Scalability
✓ Asked in Interview ×1Mid-Level Β· 3–5 Years
Q. Q. How do you generate unique IDs for uploading thousands of images on cloud/database? each time have to generate uniqueid so how to achive.

DB Sequernce I would use UUIDs because they are globally unique and avoid collisions, even when thousands or millions of images are uploaded concurrently across multiple servers. (Universally Unique IDentifier)

Encryption
✓ Asked in Interview ×1Mid-Level Β· 3–5 Years
Q. How to Encrypt Data?
Also asked as:
  • What is Symmetric Encryption & Asymmetric Encryption?

Data can be encrypted using encryption algorithms that convertplain text into ciphertext, ensuring that only authorized users can read the data. Symmetric Encryption β†’ Same key for encryption and decryption. (AES , DES , 3DES) Asymmetric Encryption β†’ Different keys for encryption and decryption. (RSA, ECC) (Encrypt -> Public Key) (Decrypt -> Private Key)

System Design / Integration
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. How to implement a payment gateway?

In our Candidate Registration Portal:

  • First, we integrate the payment gatewayAPIs/SDK (e.g., SBI ePay, ICICI Eazypay, Razorpay, Stripe, or PayU).
  • When the candidate clicksProceed, a payment record is created in the database with the status PENDING.
  • The candidate is then redirected to the payment gateway page to complete the payment.
  • After the payment is completed, the payment gateway sends a callback/webhook to our application.
  • We verify the digital signature, validate the response, and update the payment status and transactiondetails in the database.
  • If the payment is successful, we display a success message, send email/SMS notifications, and allow the candidate to proceed to the next step.
  • If the payment fails, we display a failure message and allow the candidate to retry the payment by creating a new payment attempt.
  • If the payment is completed but the callback is not received (e.g., due to a network issue), a scheduled reconciliation job runs every 30 minutes, checks all PENDING transactions using the payment gateway's Transaction Status API, and updates their final status in the database.
Real-World Scenarios
πŸ’Ό LinkedIn Asked ×1Mid-Level Β· 3–5 Years
Q. handle large dataset in app ?

To handle large datasets, I use pagination, query optimization, indexing, DTO projections, streaming, batch processing, caching, and asynchronous processing. The goal is to avoid loading all data into memory and minimize database and network overhead.

Real-World Scenarios
✓ Asked in Interview ×1Mid-Level Β· 3–5 Years
Q. Tell me about a critical production issue you handled.
Also asked as:
  • suggest some critical production issue?.

Issue: Candidates reported that payment and seat booking were successful, but admit cards were not being generated. Investigation: Traced the flow of Payment Success β†’ Seat Confirmation β†’ Admit Card Generation. Found that the admit card generation service was failingdue to a missing configuration. Fix:Fixed the configuration and regenerated pending admit cards through a batch job. Result: All affected candidates received their admit cards successfully.

Issue: Admin reports were loading very slowly. Investigation: Analyzed SQL queries and found missingindexes and unnecessary joins. Fix: Added indexes, optimized queries, and implemented pagination. Result: Response time reduced from 30 seconds to 2 seconds.

Issue: Admins complained that the candidate approval screens were slow. Investigation: Enabled Hibernate SQL logs and found an N+1 query issue while loading candidate documents. Fix: Used Join Fetch/ Entity Graph and optimized data retrieval. Result: The approval screen became significantly faster.

Issue: Candidates complained that the payment was deducted, but the seat was not booked. Investigation: Checked the transaction flow. The payment service succeeded, but the seat booking servicefailed due to a timeout. Fix: Added a retry mechanism, implemented a reconciliation job, and added compensation handling. Result: Payment and seat booking remained synchronized.

Issue: The exam center showed available seats even though all seats were booked. Investigation: Checked the booking and seat allocation tables. Found that concurrent bookings were updating seat counts incorrectly. Fix: Added transaction management and implemented optimistic locking. Result: Seat counts remained consistent.

Architecture & Design Patterns (3 questions)
Design Pattern
✓ Asked in Interview ×1Mid-Level Β· 3–5 Years
Q. Design Pattern in SpringBoot

Spring Boot internally uses several design patterns such as Singleton, Factory, Dependency Injection (IoC), Proxy, Template, Observer, and MVC patterns to provide loose coupling, maintainability, and scalability.

Architecture Layers
πŸ’Ό LinkedIn Asked ×1
Q. Spring DAO and DTO.

DAO (Data Access Object) encapsulates database access logic (queries, persistence) behind a clean interface, isolating the rest of the app from persistence details. DTO (Data Transfer Object) is a simple object used to carry data between layers (e.g., API request/response) without exposing internal entity structure.

General
✓ Asked in Interview ×1
Q. Design Patterns in Spring

Spring itself is built on several design patterns - Singleton (default bean scope), Factory (BeanFactory creates beans), Proxy (AOP and transactional/security proxies), Template Method (JdbcTemplate, RestTemplate), Observer (ApplicationEvent/ApplicationListener), and Dependency Injection/Inversion of Control as its foundational pattern.

Quick-Fire Differences (the pairs interviewers love)
JPA vs Hibernate vs Spring Data JPA
JPA is a specification (interfaces/rules). Hibernate is the most-used implementation of that spec, doing the actual SQL generation. Spring Data JPA sits above both, generating repository implementations from interface method names so you rarely write boilerplate DAO code.
CrudRepository vs JpaRepository
CrudRepository gives basic save/find/delete CRUD. JpaRepository extends PagingAndSortingRepository (which extends CrudRepository), adding pagination, sorting and batch operations like flush/deleteInBatch.
GET vs POST vs PUT vs PATCH vs DELETE
GET retrieves (safe, idempotent, cacheable). POST creates (not idempotent). PUT replaces an entire resource (idempotent). PATCH partially updates a resource (not guaranteed idempotent). DELETE removes a resource (idempotent).
PUT vs PATCH
PUT sends the full resource representation and replaces it wholesale — calling it twice with the same body leaves the same end state (idempotent). PATCH sends only the fields to change, which may or may not be idempotent depending on the operation (e.g. increment counter is not).
Authentication vs Authorization
Authentication answers who are you (verifying identity via credentials/token). Authorization answers what are you allowed to do (checking permissions/roles for an already-authenticated user).
JWT vs OAuth2 vs OpenID Connect
JWT is just a token format (signed, self-contained claims). OAuth2 is an authorization framework describing how tokens are issued/exchanged. OpenID Connect is an authentication layer built on top of OAuth2 that standardizes an ID Token (usually a JWT) to prove user identity.
RestTemplate vs WebClient vs OpenFeign
RestTemplate: synchronous/blocking, legacy. WebClient: reactive/non-blocking, modern general-purpose client. OpenFeign: declarative interface-style client, best fit inside a microservices stack with service discovery/load-balancing.
Optimistic vs Pessimistic Locking
Optimistic assumes conflicts are rare — detects them at commit time via a @Version column, no DB lock held (better throughput). Pessimistic assumes conflicts are likely — locks the row up front with SELECT ... FOR UPDATE, blocking other transactions until release (safer under high contention, costs concurrency).
Eager vs Lazy Loading
EAGER loads the association immediately with the parent (simpler but risks over-fetching and slower queries). LAZY loads on first access, keeps the initial query cheap but requires the session/transaction to still be open when accessed, otherwise LazyInitializationException.
@Component vs @Configuration
@Component marks a class itself as a Spring-managed bean (via component scanning). @Configuration marks a class as a source of bean definitions, whose @Bean methods are proxied by CGLIB so calling one @Bean method from another still returns the same singleton instance.
@Autowired vs @Resource
@Autowired resolves by type first, then @Qualifier/name to break ties. @Resource (JSR-250/Jakarta) resolves by name first, falling back to type if no name match is found.
@Valid vs @Validated
@Valid (Jakarta Bean Validation) triggers basic validation on a request body/bean, including nested objects. @Validated (Spring's own) adds support for validation groups and enables method-level validation on non-@RequestBody parameters.
@Cacheable vs @CachePut vs @CacheEvict
@Cacheable skips the method on a cache hit and returns the cached value (reads). @CachePut always runs the method and updates the cache with the result (writes-through). @CacheEvict removes one or all entries from a cache.
Singleton vs Prototype scope
Singleton: exactly one shared instance per Spring container (default). Prototype: a brand-new instance is created every time the bean is requested/injected — Spring does not manage its full lifecycle (no destroy callback) after creation.
Monolith vs Microservices
Monolith: single deployable unit, one codebase/database, simpler to develop and test but scales and deploys as one block. Microservices: independently deployable services (often database-per-service), scale/deploy/fail independently, at the cost of distributed-systems complexity (network calls, eventual consistency, observability).
Fetch Join vs @EntityGraph
Fetch Join is written explicitly in JPQL (JOIN FETCH) inside a custom @Query — very controllable but couples the query to one specific graph. @EntityGraph is declared at the repository-method level to specify which associations to eagerly fetch without hand-writing JPQL, keeping the repository cleaner and reusable across queries.
BeanFactory vs ApplicationContext
BeanFactory is the basic IoC container (lazy bean instantiation). ApplicationContext extends it with eager singleton instantiation, event publishing, internationalization, AOP integration and more — effectively always the one used in real applications.
Night-Before / 15-Minute Rapid Revision
Startup & Core
main() → SpringApplication.run() → ApplicationContext → load config → component scan → create beans → DI → auto-configuration → bean init (@PostConstruct) → embedded Tomcat starts → app ready
@SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan
Auto-config reads AutoConfiguration.imports (Boot 3) / spring.factories (Boot 2) → filters via @Conditional* → registers beans
REST & Data
Request → DispatcherServlet → Controller → Service → Repository → DB → Jackson serializes response
N+1 fix: Fetch Join / @EntityGraph / DTO projection. Always paginate large result sets (Pageable + Page<T>).
@Transactional works via a CGLIB/JDK proxy — self-invocation (this.method()) bypasses the proxy, so the advice never runs.
Security
Request → SecurityFilterChain (auth filters → JWT filter → authorization filter) → Controller
401 = who are you (authentication failed) · 403 = you can't do that (authorization failed)
RBAC: hasRole() at URL level, @PreAuthorize at method level; BCrypt for password hashing.
Production Reflexes
Slow API → check DB (slow query/missing index), then pool exhaustion, then external calls, then GC pauses.
Config not applied → check restart happened, right profile active, env var not overriding, latest build actually deployed.
Memory growth → heap dump + GC logs → look for unbounded caches / unclosed resources / static collections.
What TCS (5–8 YoE) Will Actually Probe
Explain internals, not just definitions — how auto-configuration/DI/transactions work, not just what they are.
Real production incidents you personally debugged, with the investigation steps and the actual fix.
Performance trade-offs: N+1, indexing, pagination, caching, connection pool sizing.
Transaction correctness: propagation, isolation, why a rollback silently didn't happen.
Security end-to-end: JWT flow, filter chain order, RBAC, why an API randomly 401/403s.
Comfort naming design patterns Spring itself uses (Singleton, Factory, Proxy, Template, Observer).