Interview questions · free
Spring Boot Developer interview questions and answers
30 questions Spring Boot Developer interviews in India ask, grouped by the 7 skills they test, with a short model answer for each. Then the HR round every job has. Try each one out loud before you open the answer.
- 30 questions
- 7 skills
- 15 for freshers
- Updated 30 Oct 2026
First mock interview free: 3 questions, a score and feedback on each · No card needed
Answer out loud first. Read the question, say your answer as you would in the room, then open the model answer and compare. Interviewers ask follow-ups, so learn the reasoning, not the words.
Spring Boot · Core skill
Fundamentals
This is the heart of a Spring Boot interview: interviewers check that you know what Boot does for you behind the annotations, and can fix it when it goes wrong.
What is the difference between Spring and Spring Boot?Fresher
Spring is the framework underneath: the container that creates beans and injects dependencies, plus modules for web (Spring MVC), data access, transactions and security. On its own it needs you to configure a lot, such as the server, the data source and how JSON is converted.
Spring Boot sits on top and makes those choices for you. Auto-configuration sets up sensible defaults from the libraries on the classpath, starters give you a tested set of dependencies, an embedded server like Tomcat lets you run the app as a single jar, and Actuator adds health checks and metrics. Boot doesn't replace Spring; it configures it, and you can override any default.
What is a Spring Boot starter? Which ones have you used?Fresher
A starter is a single dependency that brings in a set of libraries that work together, with versions managed by Spring Boot, so you don't pick each version yourself. spring-boot-starter-web brings Spring MVC, Jackson for JSON and embedded Tomcat. spring-boot-starter-data-jpa brings Spring Data JPA and Hibernate. spring-boot-starter-validation adds Bean Validation, spring-boot-starter-security adds Spring Security, spring-boot-starter-actuator adds health and metrics endpoints, and spring-boot-starter-test bundles JUnit 5, Mockito, AssertJ and Spring's test support.
Adding a starter also switches on the matching auto-configuration. Name the starters from your own project and what each did there; that's more convincing than a list.
What are bean scopes in Spring? Which is the default, and what should you be careful about?Fresher
The default is singleton: one instance per application context, shared by everyone who injects it. Prototype creates a new instance every time the bean is requested. Web applications also have request, session and application scopes, tied to an HTTP request, a user's session or the servlet context.
Because a singleton serves every request at the same time, it must be stateless or thread-safe: don't keep user-specific data in its fields. Another trap is injecting a prototype bean into a singleton: injection happens once, so the singleton keeps the same instance forever. If you really need a fresh one each time, inject an ObjectProvider and call getObject().
How does auto-configuration work, and how do you find out why a bean was or wasn't created?1-6 years
Spring Boot ships auto-configuration classes, listed in a file under META-INF/spring in its jars. Each one is guarded by conditions, such as @ConditionalOnClass (a library is on the classpath), @ConditionalOnMissingBean (you haven't defined your own) and @ConditionalOnProperty (a setting is switched on). So if a JDBC driver is present and you haven't declared a DataSource, Boot creates one from your spring.datasource properties; declare your own and Boot backs off.
To debug, start the app with --debug or debug=true, which prints the condition evaluation report: what matched and what didn't, and why. Actuator's conditions endpoint shows the same at runtime. Exclude one with @SpringBootApplication(exclude = ...).
Two beans implement the same interface, and the application fails to start. Why, and how do you fix it?1-6 years
Spring finds two candidates for one injection point and can't choose, so startup fails with NoUniqueBeanDefinitionException, saying it expected a single matching bean but found two. Common fixes: mark the usual one with @Primary, so it's used unless someone asks otherwise; or name the one you want with @Qualifier("smsNotifier") at the injection point.
Often the better design is to inject all of them: a List of the interface, or a Map from bean name to bean, and pick at runtime. That's the strategy pattern, for example choosing an SMS, email or WhatsApp notifier from the user's preference, and adding a channel becomes a new class. Say which fix you'd choose and why.
Spring Boot · Core skill
REST APIs
Most Spring Boot jobs are building REST APIs, so expect detailed questions on controllers, validation, error responses and securing endpoints.
What is the difference between @Controller and @RestController? And between @PathVariable and @RequestParam?Fresher
@RestController is @Controller plus @ResponseBody: whatever a method returns is written to the response body, usually as JSON through Jackson. A plain @Controller returns view names for server-rendered pages, such as Thymeleaf templates.
@PathVariable reads part of the URL path: in @GetMapping("/orders/{id}"), the id in /orders/42. @RequestParam reads the query string, like ?page=2&size=20; it's required by default, so set required = false or a defaultValue for optional ones. @RequestBody reads the JSON body of a POST or PUT. A good rule: path variables identify a resource, and query parameters filter, sort or page it.
How do you validate a request body in a Spring Boot API?Fresher
Add spring-boot-starter-validation, put constraints on the request DTO's fields, such as @NotBlank, @Email, @Size(max = 100) and @Positive, and mark the controller parameter with @Valid @RequestBody. If validation fails, Spring throws MethodArgumentNotValidException before your method runs, and returns 400 Bad Request by default.
To return a useful message, handle that exception in a @RestControllerAdvice and send back a list of field names and errors. Put @Valid on nested objects and lists too, or their fields aren't checked. For rules that need the database, such as "email already registered", check in the service layer and return 409 Conflict. Never rely only on front-end validation.
Why should a REST API return DTOs instead of JPA entities?Fresher
Returning entities ties your API to your database design, so renaming a column can break the mobile app. It can leak fields you never meant to show, like a password hash or internal flags. Serialising an entity can also trigger lazy loading, causing extra queries or a LazyInitializationException, and bidirectional relationships can loop forever in JSON.
Accepting entities as input is risky too: a user could send "role": "ADMIN" and have it saved (mass assignment). A DTO, often a Java record, holds exactly the fields that endpoint needs, with its own validation. Map between them in the service layer, by hand or with a tool like MapStruct.
How do you return consistent error responses from every controller in a Spring Boot API?1-6 years
Use one @RestControllerAdvice class with @ExceptionHandler methods, so controllers don't need try-catch blocks. Map each exception to a status and a standard body: your OrderNotFoundException to 404, MethodArgumentNotValidException to 400 with the field errors, a duplicate-record exception to 409, and a final handler for Exception that returns 500 with a generic message while logging the full details and a request ID.
Spring 6 and Boot 3 support the Problem Details standard through the ProblemDetail class, which gives every error the same shape: type, title, status and detail. Whatever format you choose, the clients should be able to rely on it. Never return stack traces or SQL errors to the caller.
How would you use Spring Security so that only admins can delete records and every other endpoint needs a logged-in user?1-6 years
In Spring Security 6, define a SecurityFilterChain bean. In authorizeHttpRequests, add requestMatchers(HttpMethod.DELETE).hasRole("ADMIN"), which matches DELETE on any path, and then anyRequest().authenticated(); the order matters, because the first matching rule wins. Configure how users authenticate, for example a JWT resource server with oauth2ResourceServer() or form login for a web app. The old WebSecurityConfigurerAdapter has been removed.
For rules that depend on the data, enable method security with @EnableMethodSecurity and use @PreAuthorize("hasRole('ADMIN')") on service methods. Return 401 when the user isn't authenticated and 403 when they are but aren't allowed, and write a test for each role.
Spring Boot
JPA and Hibernate
Almost every Spring Boot service uses JPA and Hibernate, and many production problems, slow pages and missing data, come from not knowing how it loads and saves.
How do Spring Data JPA repositories work? How would you find active users by email domain without writing SQL?Fresher
You declare an interface that extends JpaRepository, with your entity and its ID type, and Spring creates the implementation at runtime. You get save, findById, findAll, deleteById, paging and sorting for free.
For custom queries, Spring Data derives the query from the method name: List<User> findByEmailEndingWithAndActiveTrue(String domain) becomes a query with a LIKE and active = true. Add a Pageable parameter to page the results. When a name gets too long or the query needs joins, write it with @Query in JPQL, with named parameters like :domain, or as a native query. Interviewers often ask what happens with a typo in a method name: the app fails at startup, which is a good thing.
What is the difference between lazy and eager loading, and what causes a LazyInitializationException?1-6 years
Eager loading fetches a related entity together with its owner; lazy loading fetches it only when you first access it, through a proxy. By default @ManyToOne and @OneToOne are eager, and @OneToMany and @ManyToMany are lazy. Most teams make @ManyToOne lazy as well, to avoid loading data they don't need.
A LazyInitializationException happens when you touch a lazy relationship after the persistence context has closed, for example in a controller or while converting to JSON, outside the transaction. Fix it by fetching what the use case needs in the query, with JOIN FETCH or an @EntityGraph, or by mapping to a DTO inside a @Transactional service method. Making everything eager or relying on open-in-view hides the problem and often causes N+1 queries.
A method annotated with @Transactional doesn't roll back when something fails. What are the common reasons?1-6 years
First, by default Spring rolls back only for unchecked exceptions (RuntimeException and Error). A checked exception commits the transaction unless you set rollbackFor = Exception.class. Second, the exception may be caught and swallowed inside the method, so Spring never sees it. Third, self-invocation: @Transactional works through a proxy, so calling the method from another method in the same class bypasses the proxy and starts no transaction. Move it to another bean.
Other causes: the method is private, the object was created with new instead of being a Spring bean, or the table's storage engine doesn't support transactions, such as MySQL's MyISAM. Enabling debug logging for the transaction manager shows when transactions begin and end.
Core Java
OOP
Spring is built on interfaces, proxies and well-behaved objects, so interviewers check the OOP basics through the lens of a Spring application.
What is the difference between == and equals() in Java? What does the default equals() do?Fresher
== compares references for objects: it's true only if both variables point to the same object in memory. For primitives like int, it compares values. equals() is meant to compare the contents, but the default version inherited from Object does the same as ==, so a class must override it to compare fields.
String is the classic example: new String("abc") == new String("abc") is false, while equals() is true. Literals may give true with == because they share the string pool, which is why the bug can hide in testing. The same trap applies to Integer objects outside a small cached range. Always use equals() for objects, or Objects.equals() when either side could be null.
Why do Spring applications usually depend on interfaces, such as NotificationService, rather than concrete classes?Fresher
It's polymorphism and loose coupling at work. If OrderService depends on a NotificationService interface, the actual implementation, email, SMS or a fake one, can be swapped without changing OrderService. Spring injects whichever bean is configured, perhaps a different one per profile, and in unit tests you pass a mock.
This is the dependency inversion principle: high-level business code depends on an abstraction, not on low-level details. Spring's proxies can still add transactions or security behind the scenes. Don't overdo it, though: an interface with only one implementation that will never change adds little, and modern Spring can proxy classes too, so use interfaces where there's a real reason to swap.
Your JPA entity overrides equals() and hashCode() using its generated ID. What problems can that cause?1-6 years
The ID is null until the entity is saved. If you put a new entity into a HashSet, its hash code is computed from a null ID; after saving, the ID is set, the hash code changes, and the set can no longer find it. Two different unsaved entities may also count as equal because both IDs are null.
Common solutions: use a natural business key that never changes, such as an email or a PAN, if one exists; or compare by ID only when it isn't null, and return a constant hash code for the class, so it doesn't change after saving. Also avoid Lombok's @Data on entities: its equals() and hashCode() use every field, including lazy relationships.
Reading an answer isn't the same as giving one
In a mock interview you answer new Spring Boot Developer questions out loud or typed, and every answer is scored, with what to fix and a stronger answer.
Testing
Unit testing
Spring Boot teams expect tests with every pull request, and interviewers ask how you test each layer without starting the whole application every time.
How would you unit test a service class that depends on a Spring Data repository?Fresher
Test it as a plain Java class, without starting Spring. With constructor injection, create the service yourself and pass in a Mockito mock of the repository, or use @ExtendWith(MockitoExtension.class) with @Mock and @InjectMocks. Then stub the repository: when(userRepository.findById(1L)).thenReturn(Optional.of(user)), call the service method and assert on the result.
Test the unhappy paths too: when findById returns Optional.empty(), assert that the service throws UserNotFoundException. Use verify() to check that save() was called with the right data, or never called when validation fails. These tests run in milliseconds. Leave database queries to repository tests against a real database.
What is the difference between @SpringBootTest, @WebMvcTest and @DataJpaTest? When do you use each?1-6 years
@SpringBootTest starts the whole application context, so it's the closest to production and the slowest; use it for a few end-to-end integration tests. @WebMvcTest loads only the web layer: controllers, controller advice, filters and JSON conversion, with MockMvc to send requests. Services aren't loaded, so you mock them, with @MockitoBean in Spring Boot 3.4 and later or @MockBean in earlier versions. @DataJpaTest loads only JPA: entities, repositories and an embedded database by default, and rolls back each test.
These slices keep tests fast and focused. For repository tests, many teams use Testcontainers to run the real database, such as PostgreSQL or MySQL, because an in-memory database can behave differently.
How would you test a REST controller's validation and error responses?1-6 years
Use @WebMvcTest for that controller, mock its service, and send requests with MockMvc. For example: mockMvc.perform(post("/api/users").contentType(MediaType.APPLICATION_JSON).content(json)), then andExpect(status().isBadRequest()) and andExpect(jsonPath("$.errors[0].field").value("email")) for an invalid email.
Cover each case the API promises: 201 Created with a Location header for valid input, 400 with field errors for invalid input, 404 when the service throws a not-found exception, and 401 or 403 when security applies. Also verify that the service is never called when validation fails. These tests document the API contract, so a change that breaks a client fails the build.
Application security
Secure coding (OWASP)
Spring Boot APIs often handle payments and personal data, so interviewers check that you know the common vulnerabilities and how Spring helps you avoid them.
Where should you keep secrets like database passwords and API keys in a Spring Boot application?Fresher
Not in application.properties committed to Git, because anyone with the repository, and its history, can read them. Keep only placeholders or local development values there. On servers, supply secrets through environment variables, which Boot maps to properties, so SPRING_DATASOURCE_PASSWORD sets spring.datasource.password, or through a secrets manager such as AWS Secrets Manager, Azure Key Vault or HashiCorp Vault, or Kubernetes secrets.
Also make sure secrets never appear in logs or error responses, and don't expose Actuator endpoints like env publicly. If a secret is ever committed, removing the file isn't enough: rotate it at once. Mention secret scanning in CI if your team used it.
How does Spring Security protect against CSRF, and why is it often disabled for REST APIs?1-6 years
In a CSRF attack, a malicious site makes the victim's browser send a request to your site, and the browser attaches the victim's cookies automatically. Spring Security enables CSRF protection by default: state-changing requests such as POST, PUT and DELETE must carry a secret token that the other site can't read.
For a stateless API where clients send a bearer token in the Authorization header, the browser doesn't add that token automatically, so CSRF isn't a risk and disabling it is reasonable. But if your API uses session cookies, for example a single-page app logging in with a cookie, keep CSRF on, for instance with CookieCsrfTokenRepository. A common mistake is disabling it blindly because a tutorial did.
Your endpoint GET /api/orders/{id} returns any customer's order if a user changes the ID in the URL. What is this, and how do you fix it?1-6 years
It's broken access control, often called an insecure direct object reference (IDOR): the API checks that the user is logged in, but not that the order belongs to them. It's one of the most common API vulnerabilities.
Fix it in the service layer, on every request: fetch the order with the current user in the query, such as findByIdAndCustomerId(id, currentUserId), and return 404 if it isn't theirs, so you don't reveal that it exists. Admin access is a separate, explicit rule. Method security with @PreAuthorize or @PostAuthorize can express such checks too. Random UUIDs make IDs harder to guess but aren't a fix. Add a test where user A requests user B's order.
Cloud
Cloud platforms and containers
Spring Boot services are usually deployed as containers on AWS, Azure or GCP, so interviewers expect you to know how your app runs there, not only on your laptop.
How would you package a Spring Boot application as a Docker image?Fresher
The simplest way: build the jar with mvn package, then write a Dockerfile that starts from a Java runtime image, such as eclipse-temurin with Java 21 JRE, copies target/app.jar into the image, and sets ENTRYPOINT ["java", "-jar", "/app.jar"]. Build it with docker build -t orders-service . and run it with docker run -p 8080:8080.
Spring Boot can also build an image without a Dockerfile: mvn spring-boot:build-image uses Cloud Native Buildpacks. Good practice: run as a non-root user, pass configuration and secrets as environment variables rather than baking them in, use a multi-stage build or layered jars so dependency layers are cached, and expose Actuator's health endpoint for the platform's health checks.
Users upload profile photos to your Spring Boot app, which runs on two cloud instances. Where should the files be stored?Fresher
In object storage, such as Amazon S3, Azure Blob Storage or Google Cloud Storage, not on the server's disk. With two instances, a photo saved on one isn't on the other, and containers lose their local files whenever they are replaced or rescaled. Object storage is shared, durable, cheap per gigabyte and scales without you managing disks.
Store the file under a unique key and save only that key in the database. For large files, let the browser upload or download directly with a pre-signed URL that expires, so the traffic doesn't pass through your app. Keep the bucket private unless the files are meant to be public, and put a CDN in front for images that are viewed often.
You need to deploy a Spring Boot service to the cloud. How do you choose between a VM, a managed container service and Kubernetes, and keep costs under control?1-6 years
A VM, such as EC2, gives full control, but you patch the OS and handle scaling yourself; fine for a single small app. A managed container service, such as AWS ECS with Fargate, Azure Container Apps or Google Cloud Run, runs your image without servers to manage, and suits most teams with a few services. Kubernetes (EKS, AKS, GKE) pays off with many services and a team that can run it; otherwise it's overhead. Pair any of them with a managed database like RDS rather than one on a VM.
For cost: right-size CPU and memory from real metrics, autoscale, switch off dev environments at night, use reserved pricing for steady load, and set budget alerts.
Every job
HR and behavioural round
For Spring Boot roles the HR round often blends into the project discussion: interviewers want to hear what you built yourself and how you behave when production breaks.
Walk me through a Spring Boot project on your resume. Which part did you build yourself?Fresher
Start with the problem, then the design, then your part, then a result. For example: "I built [project], an app for [users] to [do what]. It's a Spring Boot REST API with [MySQL/PostgreSQL] and a [React/Angular] front end, deployed on [platform]. I wrote the [order and payment module]: the controllers, the service logic, the JPA entities and the tests. The hardest part was [a specific problem, like handling duplicate payments], which I solved by [how]."
Be precise about what you did versus the team, and be ready to draw the design or open the code: interviewers will go deep on whatever you mention.
Are you comfortable supporting production issues outside office hours or working in shifts?Fresher
Many backend teams have an on-call rotation or shifts for clients in other time zones, so answer honestly. If you can, say yes and show you understand why it matters: "Yes. I understand that when a service is down, customers and the business are affected, so I'm comfortable being part of an on-call rotation. I'd also want to help reduce the alerts over time, through better monitoring and fixing root causes."
If you have a real constraint, such as caring for a family member, mention it politely now and ask how the rotation works. Agreeing now and backing out later causes more problems.
How do you keep your skills up to date as Spring and Java keep changing?1-6 years
Show a real habit with recent examples rather than "I read blogs". For example: "I follow the Spring release notes and upgrade guides, and when our team moved from Spring Boot 2 to 3, I handled the javax-to-jakarta changes and the new Spring Security configuration. I build a small side project when something new comes out, such as virtual threads in Java 21, so I learn by doing. I also read our dependencies' changelogs before upgrading."
Mention one thing you learned recently and how you used it at work. Interviewers often follow up with "What changed in the latest version?", so be ready.
Tell me about a production incident you were part of. What did you do?1-6 years
Use STAR, and focus on calm, ordered steps and what changed afterwards. For example: "After a release, our order API started timing out at peak hours (situation). I was on call (task). I checked the dashboards and saw the database connection pool exhausted; a new report endpoint held connections during a slow external call. We rolled back first to restore service, then I moved the external call outside the transaction and added a timeout (action). Errors stopped, and we added a pool usage alert and a load test to our release checklist (result)."
Show that you restored service first, then fixed the cause, and shared what you learned without blaming anyone.
What are your salary expectations?1-6 years
Do your homework first: check the range for your experience, skills and city on salary sites and with people in similar roles. Then give a range rather than one number, linked to the role: "Based on my [n] years with Spring Boot and microservices and the market for this role, I'm looking for [range]. I'm flexible depending on the overall package and the work." If asked about your current CTC, give the true figure; companies often verify it with payslips.
Don't name a figure far above your range without a reason, and don't accept or reject an offer on the spot; ask for the full breakup of fixed pay, variable pay and benefits.
Free interview questions, roadmaps and mock interviews: https://myskillgrid.com/interview-questions/spring-boot-developer/
Ready to answer them for real?
Your first Spring Boot Developer mock interview is free: 3 questions, a score and feedback for each, and a stronger answer to learn from, in about 10 minutes.