35 Advanced Java Spring Boot Interview Questions for Experienced Developers

A set of 35 advanced Java Spring Boot interview questions crafted for both interviewers and seasoned developers, focusing on microservices, performance tuning, security, and real-world application design.
interview questions
Java Spring Boot Q&A Component

Jump to Category

⚙️ Spring Core & Boot Internals 💾 Data, Transactions & Caching
☁️ Microservices & Cloud-Native 🛡️ Security
⚡ Async, Reactive & Messaging 🧪 Testing

Spring Core & Boot Internals

1. How does Spring Boot’s auto-configuration mechanism work?

Auto-configuration is triggered by the `@EnableAutoConfiguration` annotation (which is part of `@SpringBootApplication`). Spring Boot scans the classpath for a file named `META-INF/spring.factories` inside dependency JARs. This file contains a list of `AutoConfiguration` classes. Each configuration class is evaluated based on conditions (e.g., presence of a specific class or property) using `@ConditionalOn…` annotations. If the conditions are met, the beans defined in that configuration class are created and added to the application context.

Read the official documentation on Auto-configuration.

2. Explain the difference between `@Component`, `@Service`, `@Repository`, and `@Controller`.

All these annotations mark a class as a Spring-managed bean. Functionally, `@Service`, `@Repository`, and `@Controller` are specializations of `@Component`.

  • `@Component`: A generic stereotype for any Spring-managed component.
  • `@Service`: Indicates that a class holds business logic. It’s mainly a semantic distinction.
  • `@Repository`: Used for persistence layers. It enables exception translation, turning platform-specific exceptions (like `SQLException`) into Spring’s unified `DataAccessException` hierarchy.
  • `@Controller` / `@RestController`: Marks a class as a web controller for handling incoming HTTP requests.

3. What is Aspect-Oriented Programming (AOP), and how does Spring use it?

AOP is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns (like logging, security, and transactions). Spring AOP uses proxies (either JDK dynamic proxies or CGLIB proxies) to intercept method invocations on target objects. When a method is called, the proxy can execute additional “advice” code before, after, or around the actual method call, based on a defined “pointcut” (an expression that matches methods).

Read the Spring Framework AOP documentation.

4. Explain the different bean scopes available in Spring.

  • Singleton (default): Only one instance of the bean is created per Spring IoC container.
  • Prototype: A new instance is created every time the bean is requested.
  • Request: Scopes a bean to the lifecycle of a single HTTP request (web applications only).
  • Session: Scopes a bean to a single HTTP session (web applications only).
  • Application: Scopes a bean to the lifecycle of the `ServletContext` (web applications only).
  • WebSocket: Scopes a bean to the lifecycle of a WebSocket session (web applications only).

5. What is the difference between constructor injection and setter injection? Which is preferred?

Constructor Injection: Dependencies are provided as arguments to the constructor. This allows for creating immutable objects and ensures that an object is created in a valid state with all its required dependencies present.

Setter Injection: Dependencies are injected through setter methods after the object has been constructed. This is used for optional dependencies.

Constructor injection is generally preferred because it guarantees that required dependencies are not null and makes objects immutable, which is better for thread safety and testability.

6. How would you create a custom Spring Boot starter?

  1. Create a new project for your starter. The naming convention is `spring-boot-starter-{name}`.
  2. Create an `@Configuration` class annotated with `@ConditionalOn…` annotations to define the beans that your starter will provide. This is the auto-configuration module.
  3. Create a `META-INF/spring.factories` file and list your auto-configuration class under the `org.springframework.boot.autoconfigure.EnableAutoConfiguration` key.
  4. The starter POM itself is usually empty and just declares dependencies, including the auto-configuration module.

7. What is the purpose of `@ConfigurationProperties`?

`@ConfigurationProperties` provides a type-safe way to bind external configuration from `application.properties` or `application.yml` files to a Java object. It allows you to group related properties into a dedicated POJO, making configuration strongly typed, easier to manage, and less prone to errors compared to injecting individual values with `@Value`.

Data, Transactions & Caching

8. Explain the N+1 selects problem in JPA/Hibernate and how to solve it.

The N+1 problem occurs when you fetch a list of parent entities (1 query) and then lazily access a related collection for each of them, resulting in N additional queries to fetch the child entities.

Solutions include:

  • Using JOIN FETCH: In a JPQL or HQL query, this fetches the parent and its related collection in a single query using a SQL join.
  • Using `@EntityGraph`: A JPA 2.1 feature that allows you to define a graph of associations to be fetched eagerly.
  • Using Batch Fetching: Hibernate’s `@BatchSize` annotation can fetch lazy collections for multiple parent entities in a single, batched query.

9. Describe the propagation levels in Spring’s `@Transactional` annotation.

Propagation levels define how a transactional method relates to an existing transaction.

  • REQUIRED (default): Joins an active transaction or creates a new one if none exists.
  • SUPPORTS: Joins an active transaction, but runs non-transactionally if none exists.
  • MANDATORY: Throws an exception if there is no active transaction.
  • REQUIRES_NEW: Always starts a new, independent transaction, suspending the current one if it exists.
  • NOT_SUPPORTED: Suspends the current transaction and executes non-transactionally.
  • NEVER: Throws an exception if there is an active transaction.
  • NESTED: Starts a nested transaction if one exists, which acts like a savepoint. If no transaction exists, it behaves like `REQUIRED`.
Read about Transaction Propagation in the Spring Docs.

10. What’s the difference between `save()`, `saveAndFlush()`, and `flush()` in Spring Data JPA?

  • `save(entity)`: Makes a transient instance persistent. The changes might not be synchronized with the database immediately; Hibernate may batch them in memory.
  • `flush()`: Forces the synchronization of the persistence context with the underlying database, executing any pending SQL statements (INSERT, UPDATE, DELETE).
  • `saveAndFlush(entity)`: Combines `save()` and `flush()` in one call. It saves the entity and then immediately flushes the changes to the database.

11. How does Spring’s caching abstraction with `@Cacheable` work?

When a method annotated with `@Cacheable` is called, Spring AOP intercepts the call. It checks a configured cache (like EhCache, Caffeine, or Redis) for an entry corresponding to the method’s arguments (the key). If a value is found in the cache, it’s returned immediately without executing the method. If not, the method is executed, and its return value is placed in the cache before being returned to the caller. Other annotations like `@CachePut` and `@CacheEvict` manage updating and removing cache entries.

12. Explain the difference between optimistic and pessimistic locking.

Pessimistic Locking: Assumes that concurrent conflicts are likely. It locks a database record when it’s read, preventing any other transaction from modifying or reading it until the lock is released. This can cause performance bottlenecks.

Optimistic Locking: Assumes conflicts are rare. It doesn’t lock the record but uses a version column (e.g., `@Version` annotation). When updating, it checks if the version number has changed since it was read. If it has, an `OptimisticLockException` is thrown, and the transaction is rolled back, indicating a conflict.

Microservices & Cloud-Native

13. What is the role of an API Gateway in a microservices architecture?

An API Gateway (like Spring Cloud Gateway) acts as a single entry point for all client requests. Its responsibilities include:

  • Routing: Directing incoming requests to the appropriate downstream microservice.
  • Cross-cutting Concerns: Offloading common functionalities like authentication, SSL termination, rate limiting, and request logging.
  • API Composition: Aggregating results from multiple microservices into a single response.
  • Protocol Translation: Translating between client-facing protocols and internal protocols.

14. What is a Circuit Breaker pattern and how does Resilience4j implement it?

The Circuit Breaker pattern prevents an application from repeatedly trying to execute an operation that is likely to fail, such as calling a remote service that is down. It works like an electrical circuit breaker.

Resilience4j implements this with a state machine:

  1. CLOSED: Requests are allowed. If failure rates exceed a threshold, it transitions to OPEN.
  2. OPEN: Requests are immediately rejected without calling the remote service. After a configured wait time, it transitions to HALF_OPEN.
  3. HALF_OPEN: A limited number of trial requests are allowed. If they succeed, it moves to CLOSED; if they fail, it goes back to OPEN.
Explore the Resilience4j Circuit Breaker documentation.

15. Explain service discovery and its implementation with Spring Cloud.

In a microservices architecture, service instances have dynamic network locations. Service discovery is the process of figuring out the IP addresses and ports of these instances. Spring Cloud provides integrations with discovery servers like Eureka, Consul, or Zookeeper. Services register themselves with the discovery server on startup and send periodic heartbeats. Client services can then query the discovery server to find available instances of a service they need to call.

16. What is the purpose of Spring Cloud Config Server?

Spring Cloud Config Server provides a centralized place to manage external configuration for applications across all environments. It typically uses a Git repository as a backend. Client applications connect to the Config Server on startup to fetch their configuration, which allows for dynamic config updates without needing to redeploy the applications.

17. What is distributed tracing and how does Micrometer/Spring Cloud Sleuth help?

Distributed tracing is a method used to profile and monitor applications, especially those built using a microservices architecture. It traces a single request as it travels through multiple services. Spring Cloud Sleuth (now integrated into Micrometer Tracing) automatically instruments requests by adding a unique **trace ID** and **span ID** to log entries and HTTP headers. This allows tools like Zipkin or Jaeger to stitch together the entire request journey, making it easy to debug latency issues and errors in a distributed system.

18. How do you ensure idempotency in a REST API?

Idempotency means that making the same request multiple times produces the same result as making it once. While `GET`, `PUT`, and `DELETE` are naturally idempotent, `POST` is not. To make a `POST` operation idempotent, the client can generate a unique **idempotency key** (e.g., a UUID) and send it in a custom header (`Idempotency-Key`). The server then stores the result of the first request for that key and simply returns the stored response for any subsequent requests with the same key, without re-executing the operation.

Security

19. Describe the high-level architecture of Spring Security.

Spring Security is based on a chain of servlet filters. The core components are:

  • `SecurityFilterChain`: A chain of filters that a request must pass through. Each filter handles a specific concern (e.g., CSRF protection, session management, authentication).
  • `AuthenticationManager`: The central component that processes an `Authentication` request. It delegates to a list of configured `AuthenticationProvider`s.
  • `AuthenticationProvider`: Responsible for a specific authentication strategy (e.g., username/password or JWT). It validates credentials and returns a fully populated `Authentication` object.
  • `SecurityContextHolder`: A thread-local storage that holds the `SecurityContext`, which contains the `Authentication` object for the currently authenticated user.
Read the official Spring Security Architecture overview.

20. What is the difference between authentication and authorization?

  • Authentication is the process of verifying who a user is. This is typically done with a username/password, JWT, or API key.
  • Authorization is the process of determining if an authenticated user has permission to access a specific resource or perform an action. This is usually handled by checking roles or permissions (e.g., `@PreAuthorize(“hasRole(‘ADMIN’)”)`).

21. How do you implement JWT-based authentication in Spring Boot?

  1. Create an endpoint (e.g., `/login`) where a user can authenticate with credentials.
  2. Upon successful authentication, generate a signed JWT containing user details (like username and roles) and return it to the client.
  3. Create a custom filter that intercepts all subsequent requests. This filter extracts the JWT from the `Authorization: Bearer` header.
  4. The filter validates the JWT’s signature and expiration. If valid, it creates an `Authentication` object and sets it in the `SecurityContextHolder`.
  5. Configure Spring Security to use this custom filter in its filter chain.

22. What is method security and how do you enable it?

Method security allows you to secure individual methods with authorization rules. It is enabled by adding the `@EnableMethodSecurity` annotation to a configuration class. You can then use annotations like `@PreAuthorize`, `@PostAuthorize`, `@Secured`, and `@RolesAllowed` directly on your service methods to control access based on the authenticated user’s roles or permissions.

23. What is CSRF (Cross-Site Request Forgery) and how does Spring Security protect against it?

CSRF is an attack that tricks a user into submitting a malicious request to a web application where they are currently authenticated. Spring Security protects against this by default for stateful applications (using sessions) with its **Synchronizer Token Pattern**. It generates a unique, random token (`_csrf`) for each session and requires that this token be included in all state-changing requests (POST, PUT, DELETE). Since an attacker’s site cannot access this token, it cannot forge a valid request.

For stateless REST APIs using tokens like JWT, CSRF protection is typically disabled as they are not vulnerable to this specific attack vector.

Async, Reactive & Messaging

24. What is Spring WebFlux and how does it differ from traditional Spring MVC?

Spring WebFlux is a fully non-blocking, reactive web framework for building asynchronous applications. It is an alternative to Spring MVC.

Differences:

  • Concurrency Model: MVC uses a thread-per-request model from a thread pool. WebFlux uses an event loop with a small, fixed number of threads to handle a large number of concurrent requests.
  • API Style: MVC uses imperative, blocking code. WebFlux uses a reactive programming model with `Mono` and `Flux` publishers from Project Reactor.
  • Use Case: MVC is simpler and suitable for most traditional applications. WebFlux excels in high-concurrency scenarios, streaming APIs, and when calling other reactive services.
Read the official Spring WebFlux documentation.

25. Explain `Mono` and `Flux` in Project Reactor.

`Mono` and `Flux` are the two main publisher types in Project Reactor.

  • `Mono`: Represents a stream of **0 or 1** elements. It is used for asynchronous operations that will produce at most one result, like a database query for a single entity or an HTTP API call that returns a single object.
  • `Flux`: Represents a stream of **0 to N** elements. It is used for handling multiple results over time, such as a list of entities from a database, streaming data from a file, or messages from a WebSocket.

26. How does the `@Async` annotation work in Spring?

The `@Async` annotation allows a method to be executed asynchronously in a separate thread. When an annotated method is called, Spring AOP intercepts the call and submits it to a `TaskExecutor` (typically a thread pool) to run in the background. The caller receives a `Future` or `CompletableFuture` object immediately, which can be used to track the result of the asynchronous execution. To enable this, you must add `@EnableAsync` to a configuration class.

27. What is R2DBC and how does it relate to Spring WebFlux?

R2DBC** (Reactive Relational Database Connectivity) is a specification that defines a non-blocking API for accessing relational databases. Traditional database drivers like JDBC are blocking, which would negate the benefits of a reactive stack. R2DBC provides reactive drivers for databases like PostgreSQL, MySQL, and SQL Server, allowing fully non-blocking data access that integrates seamlessly with Spring WebFlux applications.

28. When would you use a message queue (like RabbitMQ or Kafka) in a Spring Boot application?

You would use a message queue to decouple services and handle asynchronous communication. Key use cases include:

  • Asynchronous Task Processing: Offloading long-running tasks (like video encoding) from the main application thread.
  • Service Decoupling: Allowing microservices to communicate without being directly aware of each other, improving resilience.
  • Load Leveling: Smoothing out peaks in workload by queuing requests for a downstream service to process at its own pace.
  • Event-Driven Architecture: Broadcasting events to multiple interested consumers.
Spring Boot provides excellent integration via Spring AMQP (for RabbitMQ) and Spring for Apache Kafka.

Testing

29. What is the difference between `@SpringBootTest` and `@WebMvcTest`?

  • `@SpringBootTest`: An integration test annotation that loads the entire Spring `ApplicationContext`. It starts up the full application, making it suitable for end-to-end tests.
  • `@WebMvcTest`: A slice test annotation that focuses only on the web layer. It auto-configures Spring MVC components (`@Controller`, `Filter`, etc.) but does not load other beans like `@Service` or `@Repository`. It’s faster and used for testing controllers in isolation.

30. How does `@MockBean` work and when should you use it?

`@MockBean` creates a Mockito mock of a specific bean and replaces the real bean in the Spring `ApplicationContext`. It’s used in integration tests (`@SpringBootTest`) or slice tests to mock dependencies that are external to the component you are testing. For example, in a `@WebMvcTest`, you would use `@MockBean` to mock the service layer to test the controller’s logic without actually executing the business logic.

31. What are slice tests in Spring Boot? Give some examples.

Slice tests are a type of integration test that focuses on a specific “slice” or layer of the application, loading only the relevant parts of the Spring context. This makes them much faster than loading the entire application with `@SpringBootTest`.

Examples include:

  • `@WebMvcTest`: For the web/controller layer.
  • `@DataJpaTest`: For the persistence/JPA layer. It provides an in-memory database by default.
  • `@JsonTest`: For testing JSON serialization and deserialization.

32. What is Testcontainers and why is it useful?

Testcontainers is a Java library that provides lightweight, disposable instances of common databases, message brokers, or anything else that can run in a Docker container. It allows you to run integration tests against real services (like a real PostgreSQL database or Kafka instance) instead of relying on in-memory alternatives (like H2), making your tests more reliable and closer to the production environment.

Visit the Testcontainers official website.

33. What is the purpose of Spring Boot Actuator?

Spring Boot Actuator provides production-ready features for monitoring and managing your application. It exposes several endpoints over HTTP or JMX. Key endpoints include:

  • `/health`: Shows application health information.
  • `/info`: Displays arbitrary application info.
  • `/metrics`: Provides detailed metrics like memory usage, HTTP request stats, etc.
  • `/env`: Displays the current environment properties.
  • `/loggers`: Allows viewing and changing log levels at runtime.

34. How does Spring’s `@DirtiesContext` annotation work in tests?

The `@DirtiesContext` annotation indicates that a test method or class “dirties” the Spring `ApplicationContext`, meaning it has made changes to the context (like modifying a bean’s state) that might affect other tests. When a test with this annotation completes, Spring will close and rebuild the application context before running the next test, ensuring test isolation at the cost of slower execution.

35. What is the Spring Expression Language (SpEL)? Provide an example of its use.

SpEL is a powerful expression language that supports querying and manipulating an object graph at runtime. It can be used throughout the Spring Framework.

A common example is in method security with `@PreAuthorize`, where you can write complex authorization rules: @PreAuthorize("#username == authentication.principal.username"). This expression checks if the `username` path variable matches the username of the currently authenticated principal.

Remote hiring made easy

75%
faster to hire
58%
cost savings
800+
hires made
Explore More