Tutorials Logic, IN info@tutorialslogic.com
Spring Boot

Top 50 Spring Boot Interview Questions

Curated questions covering auto-configuration, dependency injection, REST APIs, JPA, security, actuator, and microservices.

01

What is Spring Boot and how does it differ from Spring Framework?

Spring Boot is an opinionated extension of Spring Framework that simplifies application setup. Spring Framework requires manual configuration of beans, data sources, and servers. Spring Boot provides auto-configuration, embedded servers (Tomcat/Jetty), starter dependencies, and production-ready features out of the box.

02

What is auto-configuration in Spring Boot?

Auto-configuration automatically configures Spring beans based on the dependencies present on the classpath. For example, if spring-boot-starter-data-jpa is on the classpath and a DataSource bean is defined, Spring Boot auto-configures a JPA EntityManagerFactory. Use @EnableAutoConfiguration or @SpringBootApplication to enable it.

03

What does @SpringBootApplication do?

@SpringBootApplication is a convenience annotation combining three annotations.

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

What is dependency injection in Spring?

Dependency Injection (DI) is a design pattern where objects receive their dependencies from an external source. Spring implements DI via the IoC container. Three types: constructor injection (recommended), setter injection, and field injection (@Autowired).

Example
@Service
public class OrderService {
  private final PaymentService paymentService;

  // Constructor injection (preferred)
  public OrderService(PaymentService paymentService) {
    this.paymentService = paymentService;
  }
}
05

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

  • @Component - generic stereotype for any Spring-managed component.
  • @Service - marks business logic layer. No extra behavior but improves readability.
  • @Repository - marks data access layer. Enables automatic exception translation (DataAccessException).
  • @Controller - marks MVC controller. Works with @RequestMapping to handle HTTP requests.
06

What is the difference between @RestController and @Controller?

@Controller returns view names resolved by a ViewResolver (for MVC/Thymeleaf). @RestController is @Controller + @ResponseBody - it serializes return values directly to JSON/XML response body. Use @RestController for REST APIs.

Example
@RestController
@RequestMapping("/api/users")
public class UserController {
  @GetMapping("/{id}")
  public User getUser(@PathVariable Long id) {
    return userService.findById(id); // auto-serialized to JSON
  }
}
07

What are Spring Boot starters?

Starters are curated dependency descriptors that bundle related libraries. Instead of manually adding multiple dependencies, you add one starter and Spring Boot manages compatible versions.

  • spring-boot-starter-web - Spring MVC, Tomcat, Jackson.
  • spring-boot-starter-data-jpa - Hibernate, Spring Data JPA.
  • spring-boot-starter-security - Spring Security.
  • spring-boot-starter-test - JUnit 5, Mockito, AssertJ.
  • spring-boot-starter-actuator - production monitoring endpoints.
08

What is Spring Data JPA?

Spring Data JPA reduces boilerplate data access code by providing repository interfaces. Extend JpaRepository to get CRUD operations, pagination, and sorting for free.

Example
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
  List<User> findByEmail(String email);
  List<User> findByAgeGreaterThan(int age);

  @Query("SELECT u FROM User u WHERE u.name LIKE %:name%")
  List<User> searchByName(@Param("name") String name);
}
09

What is the difference between @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and @PatchMapping?

  • @GetMapping - retrieve a resource. Idempotent.
  • @PostMapping - create a new resource.
  • @PutMapping - replace an entire resource. Idempotent.
  • @PatchMapping - partially update a resource.
  • @DeleteMapping - delete a resource. Idempotent.
10

What is Spring Boot Actuator?

Actuator provides production-ready monitoring and management endpoints. Common endpoints: /actuator/health (app health), /actuator/metrics (JVM, HTTP metrics), /actuator/info (app info), /actuator/env (environment properties), /actuator/beans (all beans). Secure sensitive endpoints in production.

11

What is the difference between application.properties and application.yml?

Both configure Spring Boot applications. application.yml uses YAML format (hierarchical, less repetition). application.properties uses flat key=value pairs. Both support profiles (application-dev.yml, application-prod.yml). YAML is preferred for complex nested configurations.

Example
# application.properties
server.port=8080
spring.datasource.url=jdbc:mysql://localhost/mydb

# application.yml equivalent
server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost/mydb
12

What are Spring profiles?

Profiles allow different configurations for different environments (dev, test, prod). Activate with spring.profiles.active=prod. Use @Profile("dev") on beans to conditionally register them.

Example
@Configuration
@Profile("dev")
public class DevConfig {
  @Bean
  public DataSource dataSource() {
    return new EmbeddedDatabaseBuilder().setType(H2).build();
  }
}
13

What is the difference between @Bean and @Component?

  • @Component - class-level annotation. Spring auto-detects via component scanning.
  • @Bean - method-level annotation inside @Configuration class. You control instantiation. Used for third-party classes you cannot annotate.
Example
@Configuration
public class AppConfig {
  @Bean
  public ObjectMapper objectMapper() { // third-party class
    return new ObjectMapper().findAndRegisterModules();
  }
}
14

What is Spring Security and how do you secure a REST API?

Spring Security provides authentication and authorization. For REST APIs, common approaches: HTTP Basic Auth, JWT tokens, or OAuth2. Configure via SecurityFilterChain bean.

Example
@Configuration
@EnableWebSecurity
public class SecurityConfig {
  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http
      .csrf(csrf -> csrf.disable())
      .authorizeHttpRequests(auth -> auth
        .requestMatchers("/api/public/**").permitAll()
        .anyRequest().authenticated())
      .sessionManagement(s -> s.sessionCreationPolicy(STATELESS))
      .build();
  }
}
15

What is @Transactional and how does it work?

@Transactional declaratively manages transactions. Spring creates a proxy that begins a transaction before the method and commits or rolls back after. Auto-rollback on RuntimeException by default.

Example
@Service
public class OrderService {
  @Transactional
  public void placeOrder(Order order) {
    orderRepo.save(order);
    inventoryService.deduct(order.getItems());
    // auto-rollback if any exception is thrown
  }
}
16

What is the difference between FetchType.LAZY and FetchType.EAGER?

  • EAGER - related entities are loaded immediately with the parent query. Can cause N+1 problems.
  • LAZY - related entities are loaded only when accessed. Default for @OneToMany and @ManyToMany.
  • Use LAZY by default and fetch eagerly with JOIN FETCH in JPQL when needed.
17

What is the N+1 query problem?

The N+1 problem occurs when fetching N parent entities triggers N additional queries to load their related entities. Fix with JOIN FETCH in JPQL, @EntityGraph, or @BatchSize.

Example
// Problem: 1 query for orders + N queries for each customer
List<Order> orders = orderRepo.findAll();

// Fix: single JOIN FETCH query
@Query("SELECT o FROM Order o JOIN FETCH o.customer")
List<Order> findAllWithCustomer();
18

What is @ExceptionHandler and @ControllerAdvice?

@ExceptionHandler handles exceptions in a specific controller. @ControllerAdvice (or @RestControllerAdvice) handles exceptions globally across all controllers.

Example
@RestControllerAdvice
public class GlobalExceptionHandler {
  @ExceptionHandler(ResourceNotFoundException.class)
  @ResponseStatus(HttpStatus.NOT_FOUND)
  public ErrorResponse handleNotFound(ResourceNotFoundException ex) {
    return new ErrorResponse(404, ex.getMessage());
  }
}
19

What is Spring Boot DevTools?

DevTools improves development experience with automatic application restart on classpath changes, LiveReload for browser refresh, and relaxed property defaults (disabled caching). Add spring-boot-devtools as a dependency - it is automatically excluded from production builds.

20

What is the difference between @PathVariable and @RequestParam?

  • @PathVariable - extracts values from the URI path: /users/{id}.
  • @RequestParam - extracts query string parameters: /users?page=1&size=10.
Example
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) { ... }

@GetMapping("/users")
public Page<User> listUsers(
  @RequestParam(defaultValue = "0") int page,
  @RequestParam(defaultValue = "10") int size) { ... }
21

What is the difference between @RequestBody and @ResponseBody?

  • @RequestBody - deserializes the HTTP request body (JSON/XML) into a Java object.
  • @ResponseBody - serializes the return value of a method to the HTTP response body.
  • @RestController includes @ResponseBody on all methods automatically.
Example
@PostMapping("/users")
public User createUser(@RequestBody UserDto dto) {
  return userService.create(dto); // @ResponseBody implicit in @RestController
}
22

What is the difference between @OneToMany and @ManyToOne?

  • @ManyToOne - many entities reference one entity. The foreign key is on this side (owning side).
  • @OneToMany - one entity has a collection of related entities. Use mappedBy to point to the owning side.
  • Always define the owning side with @JoinColumn to control the foreign key column.
Example
@Entity
public class Order {
  @ManyToOne
  @JoinColumn(name = "customer_id")
  private Customer customer;
}

@Entity
public class Customer {
  @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
  private List<Order> orders;
}
23

What is Spring Boot testing support?

Spring Boot provides @SpringBootTest for full integration tests, @WebMvcTest for controller layer tests, @DataJpaTest for repository tests (in-memory DB), and @MockBean to replace beans with Mockito mocks.

Example
@WebMvcTest(UserController.class)
class UserControllerTest {
  @Autowired MockMvc mockMvc;
  @MockBean UserService userService;

  @Test
  void getUser_returnsUser() throws Exception {
    given(userService.findById(1L)).willReturn(new User(1L, "Alice"));
    mockMvc.perform(get("/api/users/1"))
           .andExpect(status().isOk())
           .andExpect(jsonPath("$.name").value("Alice"));
  }
}
24

What is the difference between @Scheduled and @Async?

  • @Scheduled - runs a method on a fixed schedule (cron, fixedRate, fixedDelay). Enable with @EnableScheduling.
  • @Async - runs a method asynchronously in a separate thread. Enable with @EnableAsync. Returns void or Future/CompletableFuture.
Example
@Component
public class Tasks {
  @Scheduled(cron = "0 0 8 * * MON-FRI")
  public void dailyReport() { ... }

  @Async
  public CompletableFuture<String> processAsync() {
    return CompletableFuture.completedFuture("done");
  }
}
25

What is the difference between @Value and @ConfigurationProperties?

  • @Value("${property}") - injects a single property. Simple but verbose for many properties.
  • @ConfigurationProperties(prefix = "app") - binds a group of properties to a POJO. Type-safe. Better for complex configuration.
Example
@ConfigurationProperties(prefix = "app")
@Component
public class AppConfig {
  private String name;
  private int timeout;
  private List<String> allowedOrigins;
  // getters/setters
}
26

What is the difference between Spring Boot 2.x and 3.x?

  • Spring Boot 3.0 requires Java 17+.
  • Spring Boot 3.0 uses Jakarta EE 9+ (javax.* renamed to jakarta.*).
  • Native image support via GraalVM.
  • Improved observability with Micrometer.
  • HTTP interface clients (declarative HTTP clients).
  • Problem Details for HTTP APIs (RFC 7807).
27

What is the difference between @Autowired and constructor injection?

  • @Autowired on field - works but hides dependencies. Cannot be used with final fields. Harder to test.
  • Constructor injection - explicit dependencies. Works with final fields. Easier to test (no Spring context needed). Recommended.
Example
// Field injection (avoid)
@Autowired
private UserService userService;

// Constructor injection (preferred)
private final UserService userService;
public MyService(UserService userService) {
  this.userService = userService;
}
28

What is the difference between @Primary and @Qualifier?

  • @Primary - marks a bean as the default when multiple beans of the same type exist.
  • @Qualifier("beanName") - specifies exactly which bean to inject when multiple exist.
Example
@Bean @Primary
public DataSource primaryDataSource() { ... }

@Bean
public DataSource secondaryDataSource() { ... }

// Inject specific one
@Autowired @Qualifier("secondaryDataSource")
private DataSource dataSource;
29

What is the difference between @Scope singleton and prototype?

  • singleton (default) - one instance per Spring container. Shared across all requests.
  • prototype - new instance created every time the bean is requested.
  • request/session - one instance per HTTP request/session (web applications only).
Example
@Bean
@Scope("prototype")
public ExpensiveObject expensiveObject() {
  return new ExpensiveObject();
}
30

What is the difference between Spring MVC and Spring WebFlux?

  • Spring MVC - synchronous, blocking I/O. Thread-per-request model. Backed by Servlet API.
  • Spring WebFlux - asynchronous, non-blocking I/O. Reactive programming with Project Reactor. Better for high-concurrency with fewer threads.
  • Use MVC for traditional apps; WebFlux for high-throughput reactive applications.
31

What is the difference between @Entity and @Table in JPA?

  • @Entity - marks a class as a JPA entity (mapped to a database table).
  • @Table(name = "users") - specifies the tl-table name. Optional; defaults to the class name.
Example
@Entity
@Table(name = "users", indexes = {
  @Index(name = "idx_email", columnList = "email")
})
public class User {
  @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(nullable = false, unique = true)
  private String email;
}
32

What is the difference between CascadeType.ALL and CascadeType.MERGE?

  • CascadeType.PERSIST - save child when parent is saved.
  • CascadeType.MERGE - merge child when parent is merged.
  • CascadeType.REMOVE - delete child when parent is deleted.
  • CascadeType.REFRESH - refresh child when parent is refreshed.
  • CascadeType.ALL - all of the above.
  • Use CascadeType.ALL carefully - CascadeType.REMOVE can delete unintended data.
33

What is the difference between Spring Boot embedded server and external server?

  • Embedded server - Tomcat/Jetty/Undertow bundled in the JAR. Run with java -jar app.jar. No external server needed. Default in Spring Boot.
  • External server (WAR deployment) - package as WAR, deploy to external Tomcat/JBoss. Requires extending SpringBootServletInitializer.
Example
// For WAR deployment
@SpringBootApplication
public class MyApp extends SpringBootServletInitializer {
  @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder b) {
    return b.sources(MyApp.class);
  }
}
34

What is the difference between @Transactional readOnly=true and default?

  • readOnly=false (default) - full transaction with read and write support.
  • readOnly=true - hints to the database and JPA provider that no writes will occur. Can improve performance (no dirty checking, optimized queries).
Example
@Transactional(readOnly = true)
public List<User> findAllUsers() {
  return userRepository.findAll(); // no dirty checking overhead
}

@Transactional // readOnly=false by default
public User createUser(UserDto dto) { ... }
35

What is the difference between Spring Boot health indicators?

Health indicators report the health of application components. Built-in: DiskSpaceHealthIndicator, DataSourceHealthIndicator, RedisHealthIndicator. Create custom indicators by implementing HealthIndicator.

Example
@Component
public class CustomHealthIndicator implements HealthIndicator {
  @Override
  public Health health() {
    boolean serviceUp = checkExternalService();
    return serviceUp
      ? Health.up().withDetail("service", "available").build()
      : Health.down().withDetail("service", "unavailable").build();
  }
}
36

What is the difference between Spring Boot 3 HTTP interface clients and RestTemplate?

  • RestTemplate - synchronous HTTP client. Deprecated in favor of WebClient.
  • WebClient - reactive, non-blocking HTTP client.
  • HTTP Interface (Spring Boot 3) - declarative HTTP client using @HttpExchange annotations. Similar to Feign.
Example
@HttpExchange("/api/users")
public interface UserClient {
  @GetExchange("/{id}")
  User getUser(@PathVariable Long id);

  @PostExchange
  User createUser(@RequestBody UserDto dto);
}
37

What is the difference between @ManyToMany and @OneToMany?

  • @OneToMany - one entity has a collection of another. One-to-many relationship. Foreign key in the child table.
  • @ManyToMany - both entities can have collections of each other. Requires a join table.
Example
@Entity
public class Student {
  @ManyToMany
  @JoinTable(name = "student_course",
    joinColumns = @JoinColumn(name = "student_id"),
    inverseJoinColumns = @JoinColumn(name = "course_id"))
  private Set<Course> courses;
}
38

What is the difference between Spring Boot Actuator metrics and custom metrics?

  • Built-in metrics - JVM memory, CPU, HTTP request counts, database connection pool stats. Auto-configured.
  • Custom metrics - use MeterRegistry to record application-specific metrics (counters, gauges, timers).
Example
@Service
public class OrderService {
  private final Counter orderCounter;

  public OrderService(MeterRegistry registry) {
    this.orderCounter = registry.counter("orders.created");
  }

  public void createOrder(Order o) {
    orderCounter.increment();
    orderRepo.save(o);
  }
}
39

What is the difference between Spring Boot 3 Problem Details and custom error responses?

Problem Details (RFC 7807, Spring Boot 3) is a standardized error response format. Spring Boot 3 auto-configures ProblemDetail responses for common exceptions when spring.mvc.problemdetails.enabled=true.

Example
// Spring Boot 3 - automatic Problem Details
@ExceptionHandler(UserNotFoundException.class)
public ProblemDetail handleNotFound(UserNotFoundException ex) {
  ProblemDetail pd = ProblemDetail.forStatusAndDetail(
    HttpStatus.NOT_FOUND, ex.getMessage());
  pd.setTitle("User Not Found");
  pd.setProperty("userId", ex.getUserId());
  return pd;
}
40

What is the difference between Spring Boot native image and JVM deployment?

  • JVM deployment - standard JAR. Slower startup (seconds). Higher memory. JIT compilation improves performance over time.
  • Native image (GraalVM) - compiled to native executable. Instant startup (milliseconds). Lower memory. No JIT. Requires Spring Boot 3 and AOT processing.
Example
# Build native image
./mvnw -Pnative native:compile

# Run native executable
./target/myapp  # starts in ~50ms vs ~3s for JVM
41

What is the difference between @Cacheable, @CachePut, and @CacheEvict?

  • @Cacheable - returns cached result if available. Executes method only on cache miss.
  • @CachePut - always executes the method and updates the cache.
  • @CacheEvict - removes entries from the cache.
Example
@Cacheable(value = "users", key = "#id")
public User findById(Long id) { return repo.findById(id).orElseThrow(); }

@CachePut(value = "users", key = "#user.id")
public User update(User user) { return repo.save(user); }

@CacheEvict(value = "users", key = "#id")
public void delete(Long id) { repo.deleteById(id); }
42

What is the difference between Spring Boot 3 virtual threads and platform threads?

Spring Boot 3.2+ supports Java 21 virtual threads (Project Loom). Virtual threads are lightweight (millions possible), managed by the JVM, and block without consuming OS threads. Enable with spring.threads.virtual.enabled=true.

Example
# application.properties
spring.threads.virtual.enabled=true

# Or programmatically
@Bean
public TomcatProtocolHandlerCustomizer<?> virtualThreads() {
  return handler -> handler.setExecutor(
    Executors.newVirtualThreadPerTaskExecutor());
}
43

What is the difference between Spring Data JPA and Spring Data JDBC?

  • Spring Data JPA - uses Hibernate ORM. Full JPA features (lazy loading, caching, complex mappings). More overhead.
  • Spring Data JDBC - simpler, no ORM. Direct SQL mapping. No lazy loading or caching. Faster for simple use cases.
  • Use JPA for complex domain models; JDBC for simple data access with full control.
44

What is the difference between @Controller and @RestController?

  • @Controller - used for MVC controllers that return views or model data.
  • @RestController - combines @Controller and @ResponseBody, so methods return response data directly as JSON/XML.
  • Use @RestController for REST APIs and @Controller for server-rendered pages.
Example
@RestController
@RequestMapping("/api/users")
class UserController {
  @GetMapping("/{id}")
  User getUser(@PathVariable Long id) { return service.find(id); }
}
45

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

  • @Component - generic Spring bean stereotype.
  • @Service - marks business/service layer classes and improves readability.
  • @Repository - marks persistence layer classes and enables exception translation for data access errors.
46

What is the difference between constructor injection and field injection?

  • Constructor injection - dependencies are required, immutable, easier to test, and recommended by Spring.
  • Field injection - shorter but hides dependencies, makes testing harder, and prevents final fields.
  • Setter injection - useful when a dependency is optional or can change after construction.
Example
@Service
class OrderService {
  private final OrderRepository repo;

  OrderService(OrderRepository repo) {
    this.repo = repo;
  }
}
47

What is the difference between @Transactional propagation REQUIRED and REQUIRES_NEW?

  • REQUIRED - joins the existing transaction if present; otherwise creates a new one.
  • REQUIRES_NEW - suspends the current transaction and starts a separate new transaction.
  • Use REQUIRES_NEW carefully for audit logs or independent operations that must commit separately.
48

What is the difference between application.properties and application.yml?

Both files configure Spring Boot applications. application.properties uses key-value lines, while application.yml uses hierarchical YAML. YAML is cleaner for nested configuration, but properties are simple and widely used.

Example
# application.properties
server.port=8081
spring.datasource.url=jdbc:mysql://localhost/app

# application.yml
server:
  port: 8081
spring:
  datasource:
    url: jdbc:mysql://localhost/app
49

What is the difference between Spring Profiles and feature flags?

  • Spring Profiles - activate different beans or configuration for environments like dev, test, and prod.
  • Feature flags - turn product behavior on or off at runtime or per user/group.
  • Profiles are environment configuration; feature flags are release and experimentation controls.
Example
@Profile("dev")
@Bean
DataSource devDataSource() {
  return DataSourceBuilder.create().url("jdbc:h2:mem:test").build();
}
50

What is the difference between validation using @Valid and manual validation?

  • @Valid - triggers Jakarta Bean Validation annotations such as @NotNull, @Email, and @Size automatically.
  • Manual validation - custom checks written in service or controller code.
  • Use @Valid for standard request validation and manual validation for domain-specific rules.
Example
public record UserRequest(
  @NotBlank String name,
  @Email String email
) {}

@PostMapping("/users")
User create(@Valid @RequestBody UserRequest request) {
  return service.create(request);
}

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.