Top 50 Spring Boot Interview Questions and Answers

Commonly asked Spring Boot interview questions, from fundamentals to advanced concepts.

1.What is Spring Boot?

Spring Boot is a framework built on top of the Spring Framework that simplifies building production-ready Java applications.

  • Provides auto-configuration, embedded servers, and opinionated defaults to minimize boilerplate setup.
  • Lets you run a standalone Spring application with just java -jar, without deploying to an external application server.

2.What are the main advantages of using Spring Boot over the traditional Spring Framework?

Spring Boot removes much of the manual configuration Spring traditionally required:

  • Auto-configuration: sensible defaults configured automatically based on dependencies on the classpath.
  • Embedded servers (Tomcat, Jetty): no need to deploy WAR files to an external server.
  • Starter dependencies: curated dependency bundles (e.g., spring-boot-starter-web) that avoid manual version management.
  • Production-ready features: health checks, metrics via Actuator, out of the box.

3.What is auto-configuration in Spring Boot?

Auto-configuration automatically configures Spring beans based on the dependencies present on the classpath and existing configuration.

  • Example: if spring-boot-starter-web is on the classpath, Spring Boot automatically configures an embedded Tomcat server and Spring MVC.
  • Can be overridden or disabled by defining your own beans, which take precedence over auto-configured ones.

4.What is the purpose of the @SpringBootApplication annotation?

@SpringBootApplication is a convenience annotation combining three others:

  • @Configuration: marks the class as a source of bean definitions.
  • @EnableAutoConfiguration: enables Spring Boot's auto-configuration mechanism.
  • @ComponentScan: scans the package (and sub-packages) for Spring components.
@SpringBootApplication
public class MyApp {
  public static void main(String[] args) {
    SpringApplication.run(MyApp.class, args);
  }
}

5.What is a Spring Boot Starter?

A Starter is a curated set of dependencies bundled together for a specific purpose, simplifying Maven/Gradle configuration.

  • Examples: spring-boot-starter-web (REST APIs), spring-boot-starter-data-jpa (database access), spring-boot-starter-security.
  • Ensures compatible dependency versions are pulled in together, avoiding manual version conflicts.

6.What is the difference between @Component, @Service, @Repository, and @Controller?

All four register a class as a Spring-managed bean, but signal different roles:

  • @Component: generic stereotype for any Spring-managed bean.
  • @Service: marks a class containing business logic.
  • @Repository: marks a data-access class, and enables automatic exception translation for persistence errors.
  • @Controller: marks a class handling web requests (returns views); @RestController combines it with @ResponseBody for REST APIs.

7.What is Dependency Injection, and how does Spring Boot implement it?

Dependency Injection (DI) is a design pattern where an object's dependencies are provided externally rather than created internally.

  • Spring's IoC container manages object creation and injects required dependencies automatically.
  • Reduces tight coupling between classes and makes testing easier (dependencies can be mocked).
@Service
public class OrderService {
  private final PaymentService paymentService;
  public OrderService(PaymentService paymentService) {
    this.paymentService = paymentService;
  }
}

8.What are the different types of Dependency Injection in Spring?

Spring supports three main injection styles:

  • Constructor Injection: dependencies passed via the constructor — recommended, supports immutability.
  • Setter Injection: dependencies set via setter methods — useful for optional dependencies.
  • Field Injection: @Autowired directly on a field — concise but discouraged (harder to test, allows mutable dependencies).

9.What is the Spring IoC (Inversion of Control) Container?

The IoC Container is the core of Spring, responsible for creating, configuring, and managing the lifecycle of application objects (beans).

  • "Inversion of Control" means the framework — not your code — controls object creation and wiring.
  • Configured via annotations (@Component, @Bean), XML, or Java config classes.

10.What is the difference between BeanFactory and ApplicationContext?

Both are Spring IoC container implementations, but ApplicationContext is more feature-rich:

  • BeanFactory: basic container, lazily instantiates beans only when requested.
  • ApplicationContext: extends BeanFactory with additional features — event publishing, internationalization, AOP integration, and (usually) eager singleton instantiation at startup.
  • Almost all modern Spring Boot applications use ApplicationContext.

11.What is the default embedded server in Spring Boot?

Apache Tomcat is the default embedded server when using spring-boot-starter-web.

  • Runs inside the application's JVM process — no separate server installation needed.
  • The application becomes a self-contained executable JAR that starts its own server on java -jar app.jar.

12.How do you change the default embedded server in Spring Boot?

Exclude the default Tomcat starter and include the desired server's starter instead:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
  </exclusions>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

13.What is application.properties / application.yml used for?

Both files configure application settings externally, without changing code.

server:
  port: 8081
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/mydb
  • .yml uses a hierarchical, more readable structure; .properties uses flat key-value pairs.
  • Values can be injected into code via @Value or @ConfigurationProperties.

14.What are Spring Profiles, and how do you use them?

Profiles let you define environment-specific configuration (dev, test, prod) that activates conditionally.

# application-prod.yml
spring:
  datasource:
    url: jdbc:postgresql://prod-host:5432/db
  • Activate a profile via spring.profiles.active=prod or the SPRING_PROFILES_ACTIVE environment variable.
  • @Profile("prod") can also conditionally enable specific beans.

15.What is the @RestController annotation, and how does it differ from @Controller?

@RestController combines @Controller and @ResponseBody.

  • @Controller: methods typically return a view name to be rendered (e.g., an HTML template).
  • @RestController: methods return data directly (JSON/XML) as the HTTP response body — ideal for REST APIs.
@RestController
public class UserController {
  @GetMapping("/users")
  public List<User> getUsers() { ... }
}

16.What is the difference between @RequestMapping and @GetMapping/@PostMapping?

Both map HTTP requests to handler methods, but with different specificity:

  • @RequestMapping: generic, requires specifying the HTTP method explicitly (method = RequestMethod.GET).
  • @GetMapping / @PostMapping / @PutMapping / @DeleteMapping: shorthand annotations for specific HTTP methods, introduced for readability.
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) { ... }

17.What is @PathVariable, and how does it differ from @RequestParam?

Both extract values from an HTTP request, but from different parts of the URL:

  • @PathVariable: extracts a value from the URL path itself (e.g., /users/{id}).
  • @RequestParam: extracts a value from query string parameters (e.g., /users?id=5).
@GetMapping("/users/{id}")
public User get(@PathVariable Long id, @RequestParam(required = false) String filter) { ... }

18.What is @RequestBody, and how is it used?

@RequestBody binds the HTTP request body (typically JSON) to a Java object parameter.

@PostMapping("/users")
public User createUser(@RequestBody User user) {
  return userService.save(user);
}
  • Spring automatically deserializes the JSON payload into the specified object using Jackson.

19.How do you handle exceptions globally in Spring Boot?

Use @ControllerAdvice combined with @ExceptionHandler methods to centralize exception handling across all controllers.

@ControllerAdvice
public class GlobalExceptionHandler {
  @ExceptionHandler(UserNotFoundException.class)
  public ResponseEntity<String> handleNotFound(UserNotFoundException ex) {
    return ResponseEntity.status(404).body(ex.getMessage());
  }
}

20.What is @ControllerAdvice?

@ControllerAdvice is a specialized @Component that applies cross-cutting logic (like exception handling or data binding) across all @Controller classes.

  • Commonly paired with @ExceptionHandler for centralized, global error handling.
  • Can also be scoped to specific packages or controller types if needed.

21.What is Spring Data JPA?

Spring Data JPA simplifies data access by generating repository implementations automatically from interfaces.

public interface UserRepository extends JpaRepository<User, Long> {
  List<User> findByEmail(String email);
}
  • No implementation needed — Spring generates the query from the method name or a custom @Query annotation.

22.What is the difference between JpaRepository and CrudRepository?

Both provide generic data-access methods, but JpaRepository extends further:

  • CrudRepository: basic CRUD operations (save, findById, delete, etc.).
  • JpaRepository: extends CrudRepository (and PagingAndSortingRepository) with additional JPA-specific methods like batch operations and flush().

23.What is the @Entity annotation used for?

@Entity marks a Java class as a JPA-managed entity, mapping it to a database table.

@Entity
public class User {
  @Id @GeneratedValue
  private Long id;
  private String name;
}
  • Combined with @Id to designate the primary key field.

24.What is the difference between @OneToMany, @ManyToOne, and @ManyToMany?

These annotations define JPA entity relationships:

  • @OneToMany: one entity relates to many of another (e.g., one Customer has many Orders).
  • @ManyToOne: the inverse side — many entities relate to one (e.g., many Orders belong to one Customer).
  • @ManyToMany: entities on both sides can relate to multiple entities on the other (e.g., Students and Courses), typically requiring a join table.

25.What is Lazy Loading vs Eager Loading in JPA?

They control when related entity data is fetched from the database:

  • Lazy Loading (default for collections): related data is fetched only when accessed, reducing unnecessary queries.
  • Eager Loading: related data is fetched immediately along with the parent entity, which can hurt performance if not needed.
@OneToMany(fetch = FetchType.LAZY)
private List<Order> orders;

26.What is the N+1 select problem in JPA, and how do you avoid it?

The N+1 problem occurs when fetching a list of N parent entities triggers N additional queries to fetch each one's related data individually.

  • Fix by using JOIN FETCH in a JPQL query, or @EntityGraph, to fetch related data in a single query instead of one per parent.
@Query("SELECT u FROM User u JOIN FETCH u.orders")
List<User> findAllWithOrders();

27.What is Spring Boot Actuator?

Actuator exposes production-ready monitoring and management endpoints for a Spring Boot application.

  • Endpoints like /actuator/health, /actuator/metrics, and /actuator/info give insight into application status without custom code.
  • Widely used for health checks in container orchestration (e.g., Kubernetes liveness/readiness probes).

28.What is the purpose of the @Value annotation?

@Value injects a value from a properties file, environment variable, or a SpEL expression directly into a field.

@Value("${server.port}")
private int port;
  • Useful for injecting single configuration values without creating a full @ConfigurationProperties class.

29.What is @ConfigurationProperties?

@ConfigurationProperties binds a group of related configuration properties to a strongly-typed Java object, instead of injecting individual values one by one.

@ConfigurationProperties(prefix = "app.mail")
public class MailProperties {
  private String host;
  private int port;
}
  • Preferred over multiple @Value annotations for structured, related configuration.

30.What is Spring Security, and what does it provide out of the box?

Spring Security is Spring's framework for handling authentication, authorization, and common security concerns.

  • Provides built-in protection against CSRF, session fixation, and clickjacking.
  • Supports form login, HTTP Basic, OAuth2, and JWT-based authentication out of the box, plus fine-grained method/URL-level authorization.

31.How does Spring Boot handle authentication and authorization?

Spring Security (typically auto-configured via spring-boot-starter-security) intercepts requests through a filter chain.

  • Authentication: verifies who the user is (e.g., checking credentials against a database or JWT).
  • Authorization: determines what an authenticated user is allowed to do, often via @PreAuthorize or URL-based rules in a SecurityFilterChain bean.

32.What is JWT, and how is it typically used in a Spring Boot application?

JWT (JSON Web Token) is a compact, signed token used to represent claims (like user identity) between parties.

  • After login, the server issues a signed JWT to the client, who includes it in the Authorization: Bearer <token> header on subsequent requests.
  • A Spring Security filter validates the token's signature and extracts the authenticated user, avoiding server-side session storage — ideal for stateless REST APIs.

33.What is the difference between @Autowired and constructor injection?

Both achieve dependency injection, but differently:

  • @Autowired (on a field or setter): Spring injects the dependency after object construction, via reflection.
  • Constructor injection: dependencies are passed as constructor arguments, allowing fields to be declared final and ensuring the object is never in an incomplete state.
  • Since Spring 4.3, if a class has only one constructor, @Autowired on it is even optional.

34.Why is constructor injection generally preferred over field injection?

Constructor injection has several practical advantages:

  • Enables immutable dependencies (final fields), preventing accidental reassignment.
  • Makes dependencies explicit and required — the class can't be instantiated without them.
  • Much easier to unit test without a Spring context, since dependencies can be passed directly via the constructor (e.g., mocks).

35.What is a Bean's scope in Spring? List common scopes.

A bean's scope defines its lifecycle and how many instances exist.

  • singleton (default): one shared instance per Spring container.
  • prototype: a new instance created every time it's requested.
  • request / session: web-aware scopes tied to an HTTP request or session lifecycle.

36.What is the default bean scope in Spring?

The default scope is singleton — Spring creates only one instance of the bean per application context, shared across the entire application.

  • Explicit override: @Scope("prototype") if a new instance is needed per injection/request.

37.What is the @Transactional annotation used for?

@Transactional wraps a method's database operations in a single transaction, ensuring atomicity.

@Transactional
public void transferFunds(Long fromId, Long toId, BigDecimal amount) {
  debit(fromId, amount);
  credit(toId, amount);
}
  • If any exception occurs, the entire transaction is rolled back, undoing all changes made within the method.

38.What happens if an exception occurs inside a @Transactional method?

By default, Spring rolls back the transaction only for unchecked exceptions (RuntimeException and its subclasses).

  • Checked exceptions do not trigger a rollback by default — you must explicitly configure it: @Transactional(rollbackFor = Exception.class).
  • This default behavior often surprises developers relying on checked exceptions for error handling.

39.What is Spring Boot DevTools?

DevTools is a development-time dependency that improves the developer feedback loop.

  • Provides automatic restart of the application when code changes are detected.
  • Enables LiveReload for browser auto-refresh, and disables certain production caching to speed up development iteration.

40.What is the purpose of the @Async annotation?

@Async runs a method asynchronously on a separate thread, instead of blocking the calling thread.

@Async
public void sendEmail(String to) { ... }
  • Requires @EnableAsync on a configuration class.
  • The method typically returns void, Future<T>, or CompletableFuture<T>.

41.How do you schedule tasks in Spring Boot?

Use @Scheduled on a method, combined with @EnableScheduling on a configuration class.

@Scheduled(fixedRate = 60000)
public void runEveryMinute() { ... }

@Scheduled(cron = "0 0 * * * *")
public void runHourly() { ... }

42.What is Spring Boot's CommandLineRunner interface?

CommandLineRunner defines a callback that executes once, right after the Spring application context has fully started.

@Component
public class StartupRunner implements CommandLineRunner {
  public void run(String... args) {
    System.out.println("Application started!");
  }
}
  • Useful for running initialization logic like seeding data or verifying configuration at startup.

43.What is the difference between WAR and JAR deployment in Spring Boot?

They differ in packaging and how the app is run:

  • JAR (default in Spring Boot): a self-contained executable with an embedded server — run directly with java -jar.
  • WAR: packaged for deployment to an external application server (like Tomcat or WebSphere) — requires extending SpringBootServletInitializer.

44.How do you write unit tests in Spring Boot using @SpringBootTest?

@SpringBootTest loads the full (or partial) Spring application context for integration-style testing.

@SpringBootTest
class UserServiceTest {
  @Autowired
  private UserService userService;

  @Test
  void testFindUser() {
    assertNotNull(userService.findById(1L));
  }
}
  • Heavier than pure unit tests (which mock dependencies directly) since it boots up the actual Spring context.

45.What is MockMvc used for in Spring Boot testing?

MockMvc simulates HTTP requests to test Spring MVC controllers without starting a real server.

mockMvc.perform(get("/users/1"))
  .andExpect(status().isOk())
  .andExpect(jsonPath("$.name").value("Alice"));
  • Faster than full end-to-end tests since no actual network/server is involved.

46.What is the difference between @Mock, @MockBean, and @InjectMocks?

All relate to mocking in tests, but serve different purposes:

  • @Mock (Mockito): creates a plain mock object, used in pure unit tests without a Spring context.
  • @MockBean (Spring Boot Test): creates a mock and replaces the real bean in the Spring application context — used in @SpringBootTest.
  • @InjectMocks: automatically injects @Mock-annotated fields into the object under test.

47.What is Spring Cloud, and how does it relate to microservices?

Spring Cloud provides tools built on Spring Boot for common distributed-systems/microservices patterns.

  • Includes solutions for service discovery (Eureka), API gateways (Spring Cloud Gateway), centralized configuration (Config Server), and distributed tracing.
  • Simplifies building resilient, scalable microservice architectures without reinventing common cross-cutting infrastructure.

48.What is Circuit Breaker pattern, and how is it implemented in Spring?

The Circuit Breaker pattern prevents a failing service from being repeatedly called, avoiding cascading failures across a distributed system.

  • After a threshold of failures, the circuit "opens," causing calls to fail fast instead of waiting on a struggling downstream service.
  • In Spring, commonly implemented with Resilience4j using the @CircuitBreaker annotation.
@CircuitBreaker(name = "paymentService", fallbackMethod = "fallback")
public String callPaymentService() { ... }

49.What is the difference between monolithic and microservices architecture?

They differ in how an application is structured and deployed:

  • Monolithic: the entire application is built and deployed as a single unit — simpler initially, but harder to scale/deploy parts independently.
  • Microservices: the application is split into small, independently deployable services (often Spring Boot apps), communicating via APIs — more scalable and flexible, but adds operational complexity (networking, service discovery, distributed data).

50.What is Spring Boot's @Cacheable annotation used for?

@Cacheable caches the result of a method call, so subsequent calls with the same arguments return the cached value instead of re-executing the method.

@Cacheable("users")
public User findById(Long id) {
  return userRepository.findById(id).orElseThrow();
}
  • Requires @EnableCaching and a configured CacheManager (e.g., backed by Redis, Caffeine, or a simple in-memory map).