Top 50 Spring Boot Interview Questions
Curated questions covering auto-configuration, dependency injection, REST APIs, JPA, security, actuator, and microservices.
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.
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.
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.
@SpringBootApplication\npublic class MyApp {\n public static void main(String[] args) {\n SpringApplication.run(MyApp.class, args);\n }\n}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).
@Service\npublic class OrderService {\n private final PaymentService paymentService;\n\n // Constructor injection (preferred)\n public OrderService(PaymentService paymentService) {\n this.paymentService = paymentService;\n }\n}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.
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.
@RestController\n@RequestMapping("/api/users")\npublic class UserController {\n @GetMapping("/{id}")\n public User getUser(@PathVariable Long id) {\n return userService.findById(id); // auto-serialized to JSON\n }\n}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.
What is Spring Data JPA?
Spring Data JPA reduces boilerplate data access code by providing repository interfaces. Extend JpaRepository
@Repository\npublic interface UserRepository extends JpaRepository<User, Long> {\n List<User> findByEmail(String email);\n List<User> findByAgeGreaterThan(int age);\n\n @Query("SELECT u FROM User u WHERE u.name LIKE %:name%")\n List<User> searchByName(@Param("name") String name);\n}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.
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.
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.
# application.properties\nserver.port=8080\nspring.datasource.url=jdbc:mysql://localhost/mydb\n\n# application.yml equivalent\nserver:\n port: 8080\nspring:\n datasource:\n url: jdbc:mysql://localhost/mydbWhat 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.
@Configuration\n@Profile("dev")\npublic class DevConfig {\n @Bean\n public DataSource dataSource() {\n return new EmbeddedDatabaseBuilder().setType(H2).build();\n }\n}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.
@Configuration\npublic class AppConfig {\n @Bean\n public ObjectMapper objectMapper() { // third-party class\n return new ObjectMapper().findAndRegisterModules();\n }\n}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.
@Configuration\n@EnableWebSecurity\npublic class SecurityConfig {\n @Bean\n public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {\n return http\n .csrf(csrf -> csrf.disable())\n .authorizeHttpRequests(auth -> auth\n .requestMatchers("/api/public/**").permitAll()\n .anyRequest().authenticated())\n .sessionManagement(s -> s.sessionCreationPolicy(STATELESS))\n .build();\n }\n}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.
@Service\npublic class OrderService {\n @Transactional\n public void placeOrder(Order order) {\n orderRepo.save(order);\n inventoryService.deduct(order.getItems());\n // auto-rollback if any exception is thrown\n }\n}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.
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.
// Problem: 1 query for orders + N queries for each customer\nList<Order> orders = orderRepo.findAll();\n\n// Fix: single JOIN FETCH query\n@Query("SELECT o FROM Order o JOIN FETCH o.customer")\nList<Order> findAllWithCustomer();What is @ExceptionHandler and @ControllerAdvice?
@ExceptionHandler handles exceptions in a specific controller. @ControllerAdvice (or @RestControllerAdvice) handles exceptions globally across all controllers.
@RestControllerAdvice\npublic class GlobalExceptionHandler {\n @ExceptionHandler(ResourceNotFoundException.class)\n @ResponseStatus(HttpStatus.NOT_FOUND)\n public ErrorResponse handleNotFound(ResourceNotFoundException ex) {\n return new ErrorResponse(404, ex.getMessage());\n }\n}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.
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.
@GetMapping("/users/{id}")\npublic User getUser(@PathVariable Long id) { ... }\n\n@GetMapping("/users")\npublic Page<User> listUsers(\n @RequestParam(defaultValue = "0") int page,\n @RequestParam(defaultValue = "10") int size) { ... }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.
@PostMapping("/users")\npublic User createUser(@RequestBody UserDto dto) {\n return userService.create(dto); // @ResponseBody implicit in @RestController\n}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.
@Entity\npublic class Order {\n @ManyToOne\n @JoinColumn(name = "customer_id")\n private Customer customer;\n}\n\n@Entity\npublic class Customer {\n @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)\n private List<Order> orders;\n}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.
@WebMvcTest(UserController.class)\nclass UserControllerTest {\n @Autowired MockMvc mockMvc;\n @MockBean UserService userService;\n\n @Test\n void getUser_returnsUser() throws Exception {\n given(userService.findById(1L)).willReturn(new User(1L, "Alice"));\n mockMvc.perform(get("/api/users/1"))\n .andExpect(status().isOk())\n .andExpect(jsonPath("$.name").value("Alice"));\n }\n}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.
@Component\npublic class Tasks {\n @Scheduled(cron = "0 0 8 * * MON-FRI")\n public void dailyReport() { ... }\n\n @Async\n public CompletableFuture<String> processAsync() {\n return CompletableFuture.completedFuture("done");\n }\n}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.
@ConfigurationProperties(prefix = "app")\n@Component\npublic class AppConfig {\n private String name;\n private int timeout;\n private List<String> allowedOrigins;\n // getters/setters\n}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).
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.
// Field injection (avoid)\n@Autowired\nprivate UserService userService;\n\n// Constructor injection (preferred)\nprivate final UserService userService;\npublic MyService(UserService userService) {\n this.userService = userService;\n}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.
@Bean @Primary\npublic DataSource primaryDataSource() { ... }\n\n@Bean\npublic DataSource secondaryDataSource() { ... }\n\n// Inject specific one\n@Autowired @Qualifier("secondaryDataSource")\nprivate DataSource dataSource;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).
@Bean\n@Scope("prototype")\npublic ExpensiveObject expensiveObject() {\n return new ExpensiveObject();\n}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.
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 table name. Optional; defaults to the class name.
@Entity\n@Table(name = "users", indexes = {\n @Index(name = "idx_email", columnList = "email")\n})\npublic class User {\n @Id @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(nullable = false, unique = true)\n private String email;\n}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.
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.
// For WAR deployment\n@SpringBootApplication\npublic class MyApp extends SpringBootServletInitializer {\n @Override\n protected SpringApplicationBuilder configure(SpringApplicationBuilder b) {\n return b.sources(MyApp.class);\n }\n}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).
@Transactional(readOnly = true)\npublic List<User> findAllUsers() {\n return userRepository.findAll(); // no dirty checking overhead\n}\n\n@Transactional // readOnly=false by default\npublic User createUser(UserDto dto) { ... }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.
@Component\npublic class CustomHealthIndicator implements HealthIndicator {\n @Override\n public Health health() {\n boolean serviceUp = checkExternalService();\n return serviceUp\n ? Health.up().withDetail("service", "available").build()\n : Health.down().withDetail("service", "unavailable").build();\n }\n}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.
@HttpExchange("/api/users")\npublic interface UserClient {\n @GetExchange("/{id}")\n User getUser(@PathVariable Long id);\n\n @PostExchange\n User createUser(@RequestBody UserDto dto);\n}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.
@Entity\npublic class Student {\n @ManyToMany\n @JoinTable(name = "student_course",\n joinColumns = @JoinColumn(name = "student_id"),\n inverseJoinColumns = @JoinColumn(name = "course_id"))\n private Set<Course> courses;\n}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).
@Service\npublic class OrderService {\n private final Counter orderCounter;\n\n public OrderService(MeterRegistry registry) {\n this.orderCounter = registry.counter("orders.created");\n }\n\n public void createOrder(Order o) {\n orderCounter.increment();\n orderRepo.save(o);\n }\n}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.
// Spring Boot 3 - automatic Problem Details\n@ExceptionHandler(UserNotFoundException.class)\npublic ProblemDetail handleNotFound(UserNotFoundException ex) {\n ProblemDetail pd = ProblemDetail.forStatusAndDetail(\n HttpStatus.NOT_FOUND, ex.getMessage());\n pd.setTitle("User Not Found");\n pd.setProperty("userId", ex.getUserId());\n return pd;\n}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.
# Build native image\n./mvnw -Pnative native:compile\n\n# Run native executable\n./target/myapp # starts in ~50ms vs ~3s for JVMWhat 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.
@Cacheable(value = "users", key = "#id")\npublic User findById(Long id) { return repo.findById(id).orElseThrow(); }\n\n@CachePut(value = "users", key = "#user.id")\npublic User update(User user) { return repo.save(user); }\n\n@CacheEvict(value = "users", key = "#id")\npublic void delete(Long id) { repo.deleteById(id); }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.
# application.properties\nspring.threads.virtual.enabled=true\n\n# Or programmatically\n@Bean\npublic TomcatProtocolHandlerCustomizer<?> virtualThreads() {\n return handler -> handler.setExecutor(\n Executors.newVirtualThreadPerTaskExecutor());\n}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.
What is the difference between Spring Boot @ConditionalOnProperty and @ConditionalOnClass?
- @ConditionalOnProperty - registers a bean only if a specific property is set to a specific value.
- @ConditionalOnClass - registers a bean only if a specific class is on the classpath.
- These are used internally by Spring Boot auto-configuration.
@Bean\n@ConditionalOnProperty(name = "feature.cache.enabled", havingValue = "true")\npublic CacheManager cacheManager() { return new CaffeineCacheManager(); }\n\n@Bean\n@ConditionalOnClass(name = "com.redis.clients.jedis.Jedis")\npublic RedisTemplate<?,?> redisTemplate() { ... }What is the difference between Spring Boot @EventListener and ApplicationListener?
- ApplicationListener
- interface-based. Register as a Spring bean. - @EventListener - annotation-based. Simpler. Can listen to multiple event types.
- Both listen to Spring application events (ContextRefreshedEvent, ApplicationReadyEvent, etc.).
@Component\npublic class StartupListener {\n @EventListener(ApplicationReadyEvent.class)\n public void onReady() {\n System.out.println("Application is ready!");\n }\n}What is the difference between Spring Boot @Validated and @Valid?
- @Valid (javax/jakarta) - triggers Bean Validation on method parameters and return values.
- @Validated (Spring) - supports validation groups. Can be used on class level to enable method-level validation.
@PostMapping("/users")\npublic User create(@Valid @RequestBody UserDto dto) {\n // dto is validated before method executes\n return userService.create(dto);\n}\n\npublic class UserDto {\n @NotBlank @Email\n private String email;\n @Min(0) @Max(150)\n private int age;\n}What is the difference between Spring Boot Flyway and Liquibase?
- Flyway - SQL-based migrations. Simple, version-based (V1__init.sql). Easy to understand.
- Liquibase - XML/YAML/JSON/SQL migrations. More features (rollback, diff, checksums). More complex.
- Both integrate with Spring Boot auto-configuration.
# Flyway migration file: db/migration/V1__create_users.sql\nCREATE TABLE users (\n id BIGINT AUTO_INCREMENT PRIMARY KEY,\n email VARCHAR(255) NOT NULL UNIQUE\n);What is the difference between Spring Boot @Lazy and eager initialization?
- Eager initialization (default) - all singleton beans are created at application startup. Faster first request. Startup errors caught early.
- @Lazy - bean is created only when first requested. Faster startup. Errors caught later.
- spring.main.lazy-initialization=true enables lazy initialization globally.
@Bean @Lazy\npublic ExpensiveService expensiveService() {\n return new ExpensiveService(); // created only when first injected\n}What is the difference between Spring Boot 3 RestClient and WebClient?
- WebClient - reactive, non-blocking. Part of Spring WebFlux. Returns Mono/Flux.
- RestClient (Spring Boot 3.2+) - synchronous, fluent API. Replacement for RestTemplate. Simpler than WebClient for blocking code.
// RestClient (Spring Boot 3.2+)\nRestClient client = RestClient.create();\nUser user = client.get()\n .uri("https://api.example.com/users/{id}", 1)\n .retrieve()\n .body(User.class);What is the difference between Spring Boot @Transactional propagation REQUIRED and REQUIRES_NEW?
- REQUIRED (default) - joins existing transaction if one exists. Creates new one if not.
- REQUIRES_NEW - always creates a new transaction. Suspends existing transaction.
- NESTED - creates a savepoint within existing transaction.
@Transactional(propagation = Propagation.REQUIRES_NEW)\npublic void auditLog(String action) {\n // always runs in its own transaction\n // committed even if outer transaction rolls back\n auditRepo.save(new AuditLog(action));\n}