Spring Boot Interview QnA (2026)- Spring Boot 3.x Included Interview java Spring Boot Spring Boot 3 by devs5003 - May 13, 20260 Spring Boot Interview QnA (2026) Spring Boot is now the default choice for building Java backend and microservices applications, so it appears in almost every Java interview. This article collects the most important Spring Boot interview questions with simple explanations, diagrams, and code examples so even beginners can follow along. Table of Contents Toggle Basics of Spring Boot: Spring Boot Interview QnAAuto‑Configuration and @SpringBootApplicationStarters and DependenciesConfiguration, Properties, and ProfilesBuilding REST APIs with Spring BootData Access with Spring Boot and JPAError Handling and ValidationSpring Boot Actuator and MonitoringSpring Boot and MicroservicesSecurity in Spring BootTesting Spring Boot ApplicationsCommon Tricky/Senior‑Level QuestionsAdvanced Spring Boot 3.x Interview Questions (2026)Final Tips for Your Spring Boot InterviewRelated Basics of Spring Boot: Spring Boot Interview QnA 1. What is Spring Boot? Short answer: Spring Boot is a framework built on top of the Spring Framework that makes it easy to create production‑ready, stand‑alone applications with minimal configuration. Simple explanation: Traditional Spring needs a lot of XML/Java configuration, manual server setup, and dependency management. Spring Boot gives you sensible defaults, auto‑configuration, and embedded servers (like Tomcat), so you can focus on writing business logic instead of infrastructure code. 2. How is Spring Boot different from the Spring Framework? Spring is a general‑purpose dependency injection and application framework. Spring Boot is an opinionated layer on top of Spring that: Provides auto‑configuration. Ships with starter dependencies. Runs with an embedded server (Tomcat, Jetty, Undertow). Interview Tip: In an interview, highlight that Spring Boot uses Spring under the hood, but removes boilerplate and makes it easier to go to production quickly. 3. What are the main advantages of Spring Boot? Common points interviewers expect: Very fast project setup using Spring Initializr. No need to deploy WAR to an external server, just run a JAR. Auto‑configuration and sensible defaults. Rich ecosystem of starters (web, data‑jpa, security, actuator, etc.). Production features out‑of‑the‑box: metrics, health checks, externalized configuration. 4. How do you create a simple Spring Boot application? Step#1: Create project using Spring Initializr Go to https://start.spring.io, choose Maven/Gradle, language (Java), Spring Boot version, add spring-boot-starter-web, and generate the project. Step#2: Main application class package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } @SpringBootApplication is the key annotation that boots everything (we’ll explain it next). Auto‑Configuration and @SpringBootApplication 5. What does @SpringBootApplication do? @SpringBootApplication is a convenience annotation that combines: @Configuration – marks the class as a source of bean definitions. @EnableAutoConfiguration – tells Spring Boot to configure beans based on classpath and properties. @ComponentScan – scans the current package and sub‑packages for Spring components. So when you put @SpringBootApplication on your main class, you are effectively configuring Spring, auto‑configuration, and component scanning in one line. 6. What is auto‑configuration in Spring Boot? Auto‑configuration automatically configures Spring beans based on: Libraries present on the classpath. Configuration properties in application.properties or application.yml. For example, if spring-boot-starter-web is on the classpath, Spring Boot auto‑configures DispatcherServlet, Jackson, and an embedded Tomcat server. Important: You can override auto‑configuration by defining your own beans or by using @ConditionalOnMissingBean, @ConditionalOnProperty, etc. 7. Simple diagram: How a Spring Boot app starts Here is the diagram: Starters and Dependencies 8. What are Spring Boot starters? Starters are curated dependency bundles that make it easy to add a feature. Examples: spring-boot-starter-web – Spring MVC, Jackson, embedded Tomcat. spring-boot-starter-data-jpa – Spring Data JPA, Hibernate. spring-boot-starter-security – Spring Security. spring-boot-starter-test – testing libraries (JUnit, AssertJ, MockMvc, etc.). Benefit: You don’t need to remember each individual dependency version. The starter pulls compatible versions for you. 9. How do you add Spring Boot starters in Maven? org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-jpa The parent spring-boot-starter-parent manages the versions, so you usually don’t specify them manually. Configuration, Properties, and Profiles 10. How does Spring Boot handle configuration? Spring Boot uses externalized configuration so you don’t hard‑code values in code. You typically configure your app using: application.properties or application.yml. Environment variables. Command line arguments. All of these can be mapped to fields using @Value or @ConfigurationProperties. Example: application.properties server.port=8081 spring.datasource.url=jdbc:postgresql://localhost:5432/mydb spring.datasource.username=demo spring.datasource.password=demo spring.jpa.hibernate.ddl-auto=update logging.level.org.springframework.web=INFO 12. What are Spring profiles? How do you use them? Profiles let you group configuration for different environments such as dev, test, and prod. You usually have: application-dev.properties application-prod.properties Example: # application-dev.properties spring.datasource.url=jdbc:h2:mem:devdb logging.level.root=DEBUG # application-prod.properties spring.datasource.url=jdbc:postgresql://prod-db:5432/proddb logging.level.root=INFO Activate a profile: Command line: –spring.profiles.active=dev Environment variable: SPRING_PROFILES_ACTIVE=prod You can also restrict beans to a profile using @Profile(“dev”). 13. Diagram: How configuration is resolved Later sources override earlier ones. Building REST APIs with Spring Boot 14. How do you create a REST API in Spring Boot? You use: @RestController to mark a class as a REST controller. @GetMapping, @PostMapping, @PutMapping, @DeleteMapping for endpoints. Example: simple CRUD for Book @RestController @RequestMapping("/api/books") public class BookController { private final BookService bookService; public BookController(BookService bookService) { this.bookService = bookService; } @GetMapping public List getAllBooks() { return bookService.findAll(); } @PostMapping public BookDto createBook(@RequestBody CreateBookRequest request) { return bookService.create(request); } @GetMapping("/{id}") public BookDto getBook(@PathVariable Long id) { return bookService.findById(id); } } 15. What is the difference between @Controller and @RestController? @Controller is used in MVC apps that return views (like Thymeleaf templates). @RestController is a combination of @Controller and @ResponseBody, so methods directly return JSON/XML in the response body. In modern APIs, @RestController is what you use most of the time. 16. Request flow diagram in a Spring Boot REST API Data Access with Spring Boot and JPA 17. How do you connect Spring Boot to a database? Add spring-boot-starter-data-jpa and the database driver (e.g., postgresql). Configure spring.datasource.* properties. Define JPA entities and repository interfaces. 18. Example: Entity and repository @Entity public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String author; // getters and setters } public interface BookRepository extends JpaRepository { List findByAuthor(String author); } Spring Data JPA automatically creates the implementation for BookRepository. 19. How does Spring Boot manage transactions? By default, Spring Data JPA methods are transactional. You can also add @Transactional on service methods: @Service public class BookService { private final BookRepository repository; public BookService(BookRepository repository) { this.repository = repository; } @Transactional public BookDto create(CreateBookRequest request) { Book book = new Book(); book.setTitle(request.getTitle()); book.setAuthor(request.getAuthor()); return mapToDto(repository.save(book)); } } Spring will create a proxy around this bean and open/commit/rollback the transaction around the method call. Error Handling and Validation 20. How do you handle exceptions in Spring Boot REST APIs? A common pattern is: Throw custom exceptions from services (e.g., BookNotFoundException). Use @ControllerAdvice with @ExceptionHandler methods to convert them into standard error responses. 21. Example: Global exception handler @ResponseStatus(HttpStatus.NOT_FOUND) class BookNotFoundException extends RuntimeException { public BookNotFoundException(Long id) { super("Book not found with id " + id); } } @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(BookNotFoundException.class) public ResponseEntity> handleBookNotFound(BookNotFoundException ex) { Map body = new HashMap<>(); body.put("error", ex.getMessage()); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(body); } } 22. How do you validate request bodies? You use Bean Validation (Jakarta Validation) with annotations like @NotBlank, @Size, etc., combined with @Valid in controller methods. public class CreateBookRequest { @NotBlank private String title; @NotBlank private String author; // getters and setters } @PostMapping public BookDto createBook(@Valid @RequestBody CreateBookRequest request) { return bookService.create(request); } If validation fails, Spring Boot automatically returns a 400 response. You can customize the error body using another @ExceptionHandler for MethodArgumentNotValidException. Spring Boot Actuator and Monitoring 23. What is Spring Boot Actuator? Actuator adds production‑ready features like health checks, metrics, and info endpoints to your application. Common interview points: Helps monitor the application. Exposes endpoints under /actuator such as health, info, metrics, beans. Can integrate with tools like Prometheus, Grafana, and cloud providers. 24. How do you enable Actuator? Add dependency: org.springframework.boot spring-boot-starter-actuator Configure exposure in application.properties: management.endpoints.web.exposure.include=health,info,metrics,env management.endpoint.health.show-details=always Now you can hit http://localhost:8080/actuator/health. 25. How do you secure Actuator endpoints? Best practices: Do NOT expose sensitive endpoints publicly. Use Spring Security and restrict access to roles (e.g., only ADMIN) or to internal networks. Expose only health (without details) on public endpoints, and keep full details for internal use. Spring Boot and Microservices 26. Why is Spring Boot popular for microservices? Light‑weight: each service runs as a small, stand‑alone JAR. Easy integration with Spring Cloud components (Config Server, Eureka, API Gateway). Great support for REST, security, messaging, and externalized configuration. 27. What is Spring Cloud Config? How does it work with Spring Boot? Spring Cloud Config provides a central configuration server for all microservices. High‑level flow: You run a Config Server (itself a Spring Boot app) that reads properties from Git, S3, etc. Client microservices (also Spring Boot apps) fetch configuration on startup from the config server. Optionally use /actuator/refresh or Spring Cloud Bus to refresh configs without restart. This avoids copying the same application-prod.properties into multiple services. 28. Diagram: Simple Spring Boot microservices Cloud Config setup Security in Spring Boot 29. How do you add security to a Spring Boot application? Add spring-boot-starter-security. Define a SecurityFilterChain bean to configure HTTP security (recommended in Spring Security 6+). Implement user details using in‑memory users or persistent storage. 30. Example: Basic HTTP authentication @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> auth .requestMatchers("/actuator/health").permitAll() .anyRequest().authenticated() ) .httpBasic(Customizer.withDefaults());return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withUsername("user") .password("{noop}password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } } Here we: Disabled CSRF (only for demo\ in real projects be careful). Allowed unauthenticated access to /actuator/health. Secured other endpoints with HTTP Basic. Testing Spring Boot Applications 31. What testing support does Spring Boot provide? Key pieces: spring-boot-starter-test with JUnit, AssertJ, Mockito, and Spring Test. @SpringBootTest for full integration tests. Test “slices” like @WebMvcTest, @DataJpaTest, etc., to test layers in isolation. 32. Example: Testing a controller with @WebMvcTest @WebMvcTest(BookController.class) class BookControllerTest { @Autowired private MockMvc mockMvc; @MockBean private BookService bookService; @Test void shouldReturnAllBooks() throws Exception { List books = List.of(new BookDto(1L, "Clean Code", "Robert C. Martin")); when(bookService.findAll()).thenReturn(books); mockMvc.perform(get("/api/books")) .andExpect(status().isOk()) .andExpect(jsonPath("$[0].title").value("Clean Code")); } } @WebMvcTest starts only the web layer, so tests are fast and focused. Common Tricky/Senior‑Level Questions 33. How do you diagnose slow Spring Boot startup? Typical checks interviewers look for: Too many auto‑configurations enabled – remove unused starters. Heavy database initialization (large schema/data). Classpath scanning of huge packages. Logging in debug mode for everything. Use actuator/startup or ApplicationStartup to analyze startup steps. 34. How do you reduce memory usage of a Spring Boot application? Possible answers: Remove unused dependencies and starters. Tune JVM options (-Xms, -Xmx, GC tuning). Use lazy initialization (spring.main.lazy-initialization=true). Avoid loading large objects in memory (e.g., caches) unnecessarily. Use lighter web servers (e.g., switch from Tomcat to Undertow if appropriate). 35. How would you handle configuration secrets (passwords, API keys)? Do NOT commit secrets to Git. Use environment variables, vaults (HashiCorp Vault, AWS Secrets Manager, etc.), or encrypted properties. Integrate with Spring Cloud Config + Vault wherever possible. You can also mention using spring.cloud.config.server.encrypt.enabled or custom property decryption mechanisms in enterprise setups. 36. How would you migrate a legacy Spring application to Spring Boot? High‑level strategy: Identify current modules and dependencies. Create a new Spring Boot app with similar dependencies. Move configuration from XML to Java config or properties. Move beans, services, and controllers gradually. Use profiles to keep old and new behavior side by side while migrating. Interviewers want to see that you think in small, safe steps instead of a “big bang” rewrite. Advanced Spring Boot 3.x Interview Questions (2026) 37. What are the major changes in Spring Boot 3.x compared to Spring Boot 2.x? This is the #1 Spring Boot 3.x question in every interview. Feature Spring Boot 2.x Spring Boot 3.x Minimum Java version Java 8 Java 17 (mandatory) Namespace javax.* jakarta.* Spring Framework Spring 5 Spring Framework 6 Jakarta EE EE8 EE 10 Native image Experimental First-class (GraalVM) Observability Manual setup Micrometer built-in Virtual Threads Not supported Java 21 + Project Loom HTTP client RestTemplate RestClient (new in 3.2) AOT compilation Not available AOT + build-time optimization ♥ Interview Tip: The javax.* → jakarta.* migration is a breaking change. If your team is migrating from Boot 2 to Boot 3, all imports, third-party libraries, and persistence annotations (@Entity, @Column, etc.) must use jakarta.*. 38. What is GraalVM Native Image and why does it matter in Spring Boot 3? Short Answer: GraalVM Native Image compiles your Spring Boot application ahead-of-time (AOT) into a native binary that starts in milliseconds and uses very little memory, ideal for microservices and serverless deployments. Comparison: Metric Traditional JVM JAR GraalVM Native Image Startup time ~3–5 seconds ~75ms Memory usage ~300–500 MB ~60 MB Peak throughput Higher (JIT) Slightly lower Build time Fast Slow (minutes) How to build a native image: org.graalvm.buildtools native-maven-plugin # Build native image using Docker (no GraalVM install needed) ./mvnw -Pnative -DskipTests spring-boot:build-image Important limitation: Reflection-based code, dynamic proxies, and classpath scanning have restrictions in native images. Spring Boot 3.x’s AOT engine generates hints for the GraalVM compiler to handle Spring-specific reflection automatically. 39. What is AOT (Ahead-of-Time) compilation in Spring Boot 3? In Spring Boot 3, AOT processing happens at build time instead of runtime. Traditional Spring: App starts → ApplicationContext created at runtime → Beans resolved → Ready Spring Boot 3 AOT: Build time: Analyze beans → Generate source code + config hints App starts → Skip discovery phase → Directly instantiate pre-computed beans Benefits: Faster startup (less work at runtime) Smaller memory footprint Required for GraalVM native image compilation Enable AOT processing at build time: ./mvnw spring-boot:process-aot Spring Boot generates the AOT-processed sources in target/spring-aot/. 40. What are Virtual Threads in Spring Boot and how do you enable them? Virtual Threads (from Project Loom, available since Java 21) are lightweight threads managed by the JVM, not the OS. Why it matters: Traditional platform threads: ~1 MB each, ~10,000 max per JVM. Virtual threads: ~few KB each, millions per JVM. You write simple, blocking-style code but get the scalability of reactive programming. Enable Virtual Threads in Spring Boot 3.2+ (Java 21 required) # application.properties spring.threads.virtual.enabled=true That single property switches Tomcat to use virtual threads for every incoming HTTP request. Or configure manually: @Bean public TomcatProtocolHandlerCustomizer> virtualThreadsForTomcat() { return protocolHandler -> protocolHandler.setExecutor( Executors.newVirtualThreadPerTaskExecutor()); } Interview Tip: Emphasize the difference: Virtual Threads are not reactive programming (no Mono/Flux). They give you reactive-level concurrency with familiar imperative code style. 41. What is the new RestClient in Spring Boot 3.2? How is it different from RestTemplate and WebClient? Spring Boot 3.2 introduced RestClient as a modern, fluent, synchronous HTTP client, essentially the successor to RestTemplate. // RestClient example RestClient restClient = RestClient.create(); BookDTO book = restClient.get() .uri("https://api.example.com/books/{id}", 1) .retrieve() .body(BookDTO.class); Comparison: Feature RestTemplate WebClient RestClient (new) Style Blocking, imperative Non-blocking, reactive Blocking, fluent API style Old, verbose Reactive (Mono/Flux) Modern, clean Reactive support No Yes No Complexity Low High Low Spring Boot 3.2+ Deprecated (still works) Supported Recommended Rule of thumb: Use RestClient for new synchronous services in Spring Boot 3.2+. Use WebClient only when you need reactive/non-blocking behavior. 42. What is @HttpExchange in Spring Boot 3? How does it work? @HttpExchange is a declarative HTTP client interface introduced in Spring 6 / Spring Boot 3. It works like Feign but is built into Spring — no extra dependency needed. // Declare the interface @HttpExchange("https://api.example.com") public interface BookServiceClient { @GetExchange("/books") List getAllBooks(); @GetExchange("/books/{id}") BookDTO getBookById(@PathVariable Long id); @PostExchange("/books") BookDTO createBook(@RequestBody CreateBookRequest request); } // Register as a Spring bean @Configuration public class HttpClientConfig { @Bean public BookServiceClient bookServiceClient() { RestClient restClient = RestClient.create(); HttpServiceProxyFactory factory = HttpServiceProxyFactory .builderFor(RestClientAdapter.create(restClient)) .build(); return factory.createClient(BookServiceClient.class); } } // Inject and use like any service @Service public class OrderService { private final BookServiceClient bookClient; //... } Interview Tip: This replaces Feign for many use-cases in Spring Boot 3. Mention it as a modern alternative when asked about inter-service communication. 43. What is Problem Details (RFC 7807) support in Spring Boot 3? Spring Boot 3 introduced native support for RFC 7807: Problem Details for HTTP APIs. Instead of returning a custom error JSON like: { "error": "Book not found", "code": 404 } You return a standardized ProblemDetail object: { "type": "https://api.example.com/errors/not-found", "title": "Resource Not Found", "status": 404, "detail": "Book with id 99 was not found", "instance": "/api/books/99" } How to enable: spring.mvc.problemdetails.enabled=true Custom ProblemDetail in exception handler: @ExceptionHandler(ResourceNotFoundException.class) public ProblemDetail handleNotFound(ResourceNotFoundException ex, HttpServletRequest request) { ProblemDetail pd = ProblemDetail.forStatusAndDetail( HttpStatus.NOT_FOUND, ex.getMessage()); pd.setTitle("Resource Not Found"); pd.setType(URI.create("https://yourdomain.com/errors/not-found")); return pd; } This makes your API error responses consistent and interoperable across services and consumers. 44. What is the difference between @Transactional propagation types? (Senior question) This is consistently asked at senior level. Propagation Behavior REQUIRED (default) Join existing transaction; create new if none exists REQUIRES_NEW Always create a new transaction; suspend existing NESTED Create a nested transaction (savepoint); rollback only the nested part on failure MANDATORY Must have an existing transaction; throws exception if none NEVER Must NOT have a transaction; throws exception if one exists SUPPORTS Use transaction if available; run without if not NOT_SUPPORTED Suspend existing transaction and run non-transactionally Common interview trap: @Service public class OrderService { @Transactional public void placeOrder() { saveOrder(); sendNotification(); // REQUIRES_NEW — separate transaction } @Transactional(propagation = Propagation.REQUIRES_NEW) public void sendNotification() { ... } } Note: If sendNotification() is called from within the same class, the @Transactional on sendNotification() is ignored due to Spring’s proxy mechanism. You must call it from a different bean. Final Tips for Your Spring Boot Interview Start by mastering the basics: @SpringBootApplication, auto‑configuration, starters, and REST controllers. Then move to data access, configuration/profiles, error handling, security, and actuator, because these are common real‑world scenarios. Finally, practice implementing a tiny Spring Boot REST service (with JPA, validation, and Actuator) end‑to‑end. When you can build and explain that confidently, most Spring Boot interview questions will feel natural. Related