Posted in

Spring Boot Interview Questions and Answers: A Comprehensive Guide for All Experience Levels






Spring Boot has become the go-to framework for building modern Java applications. Whether you’re a fresher stepping into the industry or an experienced developer looking to refresh your knowledge, mastering Spring Boot concepts is essential for technical interviews. This guide covers 30+ carefully curated interview questions spanning foundational to advanced topics, complete with detailed answers.

Fresher Level Questions

1. What is Spring Boot?

Spring Boot is a framework built on top of the Spring Framework that simplifies the development of production-ready Spring applications. It eliminates boilerplate configuration by providing auto-configuration, embedded servers, and starter dependencies. Spring Boot allows you to create standalone applications with minimal setup, making it ideal for rapid application development.

2. How does Spring Boot differ from the Spring Framework?

Spring Framework requires extensive XML configuration or Java-based configuration to set up an application. Spring Boot, on the other hand, provides auto-configuration, eliminating the need for manual setup. Spring Boot also includes embedded servers (like Tomcat), starter POMs for dependency management, and production-ready features out of the box, whereas Spring Framework requires external servers and manual dependency management.

3. What are the key components of Spring Boot?

Spring Boot consists of four main components:

  • Spring Boot Auto-configuration: Automatically configures dependencies based on what’s present in the classpath.
  • Spring Boot Starter POMs: Pre-configured dependency descriptors that simplify Maven configuration.
  • Spring Boot CLI (Command Line Interface): A command-line tool for quickly developing Spring applications.
  • Spring Boot Actuators: Production-ready features for monitoring and managing applications.

4. What is auto-configuration in Spring Boot?

Auto-configuration is a feature that automatically configures the Spring application based on dependencies present on the classpath. Spring Boot analyzes the dependencies and uses conditionals to determine which beans and configurations should be enabled or disabled. For example, if the H2 database is on the classpath, Spring Boot automatically configures an in-memory database. This reduces boilerplate code and allows developers to focus on business logic.

5. What does the @SpringBootApplication annotation do?

The @SpringBootApplication annotation is a convenience annotation that combines three annotations: @Configuration, @ComponentScan, and @EnableAutoConfiguration. It marks the class as the starting point of a Spring Boot application and enables automatic configuration of the Spring context.

6. What is a Spring Boot Starter POM?

A Spring Boot Starter POM is a pre-configured set of dependency descriptors that simplifies Maven configuration. Starters provide transitive dependencies for specific functionality. For example, spring-boot-starter-web includes all dependencies needed to build web applications, and spring-boot-starter-data-jpa includes JPA and database dependencies. This eliminates the need to manually define individual dependencies and their versions.

7. Can you explain how HTTP requests flow through a Spring Boot application?

A typical HTTP request flow in a Spring Boot application follows the MVC pattern: First, the client makes an HTTP request (GET, POST, PUT, DELETE) to the browser. The request reaches the Controller, where all requests are mapped and handled based on URL patterns. The Controller delegates to the Service layer, where all business logic is performed on data mapped to JPA using model classes. The Repository layer handles all CRUD operations for REST APIs. Finally, a response (typically in JSON format) is returned to the end user.

8. What is the difference between @Controller and @RestController?

@Controller returns a model object and view (HTML page), making the response human-readable. It’s used for traditional web applications that serve HTML. @RestController, on the other hand, returns the object directly, and the object data is written in the HTTP response as JSON or XML. It’s ideal for building REST APIs and microservices.

9. What is dependency injection, and how does @Autowired work?

Dependency injection is a design pattern where objects receive their dependencies from external sources rather than creating them internally. The @Autowired annotation tells Spring to automatically inject the required dependencies into a bean. When Spring creates a bean, it looks for matching beans in the context and injects them automatically. This reduces coupling and makes code more testable and maintainable.

10. What are Spring Boot Actuators?

Spring Boot Actuators provide production-ready features for monitoring and managing applications. They expose endpoints that give insights into your application’s health, metrics, and operational details. Common actuator endpoints include /actuator/health (application health status), /actuator/metrics (CPU usage, memory, thread information), and /actuator/env (environment variables and beans). Actuators are useful for load balancers to check application health and for administrators to monitor application performance.

Intermediate Level Questions

11. How do you handle exceptions in Spring Boot?

Exception handling in Spring Boot can be implemented using @ControllerAdvice and @ExceptionHandler annotations. You create a global exception handler class annotated with @ControllerAdvice. Inside this class, you define methods annotated with @ExceptionHandler that handle specific exceptions. These methods return customized responses with appropriate HTTP status codes. This approach provides centralized exception handling and full control over status codes and response formats sent to clients.

12. What is the purpose of @Configuration annotation?

The @Configuration annotation marks a class as a source of bean definitions. It’s used to define custom beans programmatically using @Bean methods. When you need to configure beans that aren’t auto-configured or require custom initialization logic, you use @Configuration classes. These classes are processed by Spring to generate bean definitions, allowing you to have fine-grained control over bean creation and configuration.

13. Explain data validation in Spring Boot. Can you provide a scenario?

Scenario: You’re building a user registration REST API for a SaaS platform. You need to ensure that email addresses are in the correct format, passwords meet security requirements, and usernames are between 3 and 20 characters.

Spring Boot provides validation annotations from the Bean Validation API. You can annotate model class fields with validators like @NotNull, @Email, @Size, and @Pattern. When a request is received, Spring automatically validates the input data. If validation fails, errors are captured in a BindingResult or Errors object. You can then return these validation errors to the client with appropriate HTTP status codes (typically 400 Bad Request).

14. How do you change the embedded Tomcat server port in Spring Boot?

You can change the embedded Tomcat server port in the application.properties or application.yml file. In application.properties, add the line: server.port=8081. In application.yml, use: server: port: 8081. You can also set it programmatically or pass it as a command-line argument when running the application: java -jar app.jar --server.port=8081.

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

All these annotations mark classes as Spring beans, but they serve different purposes:

  • @Component: Generic stereotype for any Spring-managed component. Use this when the component doesn’t fit other categories.
  • @Service: Used for service layer classes containing business logic. It improves readability by indicating the role of the class.
  • @Repository: Used for data access layer classes (DAOs). It also provides exception translation from database exceptions to Spring exceptions.
  • @Controller: Used for presentation layer classes that handle HTTP requests and return views.

16. What are Spring Boot properties, and how are they used?

Spring Boot properties are configuration settings defined in application.properties or application.yml files. Examples include server.port, spring.datasource.url, and logging.level.root. You can access these properties in your code using the @Value annotation: @Value("${server.port}") private int port;. Properties allow you to externalizes configuration, making your application flexible for different environments (development, testing, production).

17. How does Spring Boot support externalized configuration?

Spring Boot supports externalized configuration through multiple sources in priority order: command-line arguments, environment variables, application.properties, application.yml, and application-{profile}.properties files. You can also use @ConfigurationProperties to bind configuration to Java classes. This allows you to change configuration without recompiling code, making it easy to deploy the same application to different environments.

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

The @Value annotation injects values from external sources (like properties files, environment variables, or hardcoded values) directly into Spring beans. For example: @Value("${app.name}") private String applicationName; injects the value of the app.name property from application.properties. It also supports SpEL (Spring Expression Language) for complex value resolution.

19. How do you create a basic REST API in Spring Boot?

To create a basic REST API:

  • Create a controller class annotated with @RestController.
  • Define methods for different endpoints using @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping.
  • Map requests to methods using URL patterns and HTTP methods.
  • Return objects that are automatically serialized to JSON.

Example:

@RestController
@RequestMapping("/api/users")
public class UserController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return new User(id, "John Doe");
    }
}

20. What is the difference between @RequestMapping and @GetMapping?

@RequestMapping is a generic annotation that handles multiple HTTP methods. To specify the method, you use the method attribute: @RequestMapping(value="/users", method=RequestMethod.GET). @GetMapping is a specialized extension of @RequestMapping specifically for GET requests. @GetMapping improves code clarity and readability. Similar specialized annotations include @PostMapping, @PutMapping, and @DeleteMapping.

21. How does Spring Boot handle dependency management?

Spring Boot manages dependencies through its parent POM (spring-boot-starter-parent) and starter dependencies. The parent POM defines default versions for commonly used libraries, preventing version conflicts. Starter POMs aggregate related dependencies into convenient bundles. For example, spring-boot-starter-web includes Spring MVC, embedded Tomcat, and Jackson for JSON processing. This approach simplifies dependency management and ensures compatibility across libraries.

22. How do you handle CORS in Spring Boot?

CORS (Cross-Origin Resource Sharing) can be configured globally or at the controller level. For global configuration, create a configuration class with a WebMvcConfigurer bean and override the addCorsMappings method. At the controller level, use the @CrossOrigin annotation on controller methods or classes. This allows your Spring Boot application to handle requests from different origins securely.

23. What are Spring Profiles, and why are they useful?

Spring Profiles allow you to define different configurations for different environments. You can create application-dev.properties, application-test.properties, and application-prod.properties files. At runtime, activate a specific profile using spring.profiles.active property or environment variables. This enables you to use environment-specific configurations (database URLs, logging levels, security settings) without changing code or recompiling.

Advanced Level Questions

24. Explain a scenario where you’d disable auto-configuration and provide custom configuration.

Scenario: You’re building a financial application for a fintech company that requires a custom database connection pool with specific timeout and retry configurations that differ from Spring Boot defaults.

You can disable auto-configuration by setting @SpringBootApplication(exclude={DataSourceAutoConfiguration.class}). Then, create a @Configuration class with @Bean methods that define custom database configurations with your specific requirements. This gives you complete control over bean creation while still leveraging Spring Boot’s framework benefits.

25. How do you package a Spring Boot application for production?

Spring Boot applications can be packaged as executable JAR files (fat JARs or uber JARs) or as WAR files for traditional application servers. For JAR packaging, use Maven or Gradle to build the application, which creates a self-contained archive with embedded servers and all dependencies. You can then run it directly: java -jar application.jar. For WAR packaging, extend SpringBootServletInitializer and deploy to external servers like Tomcat. JAR packaging is preferred for microservices and cloud deployments.

26. How do you secure a Spring Boot application?

Spring Boot security involves multiple layers. Add spring-boot-starter-security dependency for authentication and authorization. Implement security configurations using WebSecurityConfigurerAdapter or SecurityFilterChain beans. Use @EnableWebSecurity annotation. Configure HTTPS with proper certificates, enable CSRF protection, implement authentication (username/password, OAuth2, JWT tokens), and define authorization rules based on user roles. For sensitive data, use encryption, secure password storage with bcrypt, and proper secret management.

27. Explain the IoC container and its role in Spring Boot. Provide a practical scenario.

Scenario: You’re developing a payment processing microservice for an e-commerce platform. Multiple payment gateway implementations exist (Stripe, PayPal, Square), and you need to switch between them based on configuration.

The IoC (Inversion of Control) container is Spring’s framework for managing object creation and their lifetimes. It automatically creates beans, manages dependencies, and injects them where needed. In your scenario, define a PaymentGateway interface with multiple implementations. The container automatically creates the appropriate implementation bean based on your configuration. Your service class receives the required implementation through dependency injection, allowing you to switch payment gateways without code changes.

28. What is a realistic use case for Spring Boot Actuator in production?

Scenario: You’re running a microservice for an online retail platform using Kubernetes for orchestration. You need to monitor application health, track performance metrics, and allow Kubernetes to automatically restart unhealthy instances.

Configure Spring Boot Actuator to expose health and metrics endpoints. Kubernetes can query the /actuator/health endpoint regularly to determine if the application is running correctly. If health checks fail, Kubernetes automatically restarts the pod. Additionally, monitoring systems can scrape /actuator/metrics endpoints to collect performance data (CPU, memory, request latency). This enables automatic healing and proactive issue detection.

29. How would you design a microservice architecture using Spring Boot? Explain inter-service communication.

Design multiple independent Spring Boot services, each handling a specific business capability. Each service has its own database, ensuring loose coupling. For inter-service communication, use REST APIs via RestTemplate or WebClient for synchronous calls, or use message queues (like RabbitMQ or Kafka) for asynchronous communication. Implement circuit breakers using Resilience4j or Spring Cloud to handle failures gracefully. Use API Gateway pattern for routing client requests to appropriate services. This architecture promotes scalability, independent deployment, and fault isolation.

30. Explain a complex scenario where you’d use conditional auto-configuration.

Scenario: You’re building a logging framework library used by multiple teams at a SaaS company. Different applications have different logging requirements. Some need file-based logging, others need cloud logging (AWS CloudWatch), and some need both.

Create separate auto-configuration classes for different logging implementations, each with @ConditionalOnClass or @ConditionalOnProperty annotations. For example, CloudWatchLoggerAutoConfiguration activates only if AWS dependencies are present and a property is enabled. Applications can include your library and automatically get the appropriate logging configuration without manual setup. This makes your library flexible and adaptable to diverse use cases.

31. How do you implement database transactions in Spring Boot? Explain with a scenario.

Scenario: You’re building a banking application where transferring money between accounts must ensure that both debit and credit operations succeed or both fail—no partial transfers.

Use the @Transactional annotation on service methods. Spring Boot manages transactions automatically, ensuring ACID properties. If any operation within a @Transactional method fails, the entire transaction is rolled back, maintaining data consistency. Configure transaction propagation behavior and isolation levels based on your requirements. For complex scenarios involving multiple databases, use distributed transaction management or eventual consistency patterns.

These 31 interview questions cover the full spectrum of Spring Boot knowledge, from foundational concepts to advanced architectural patterns. Regular practice with these questions will prepare you for technical interviews across companies of all sizes, from startups to enterprises. Focus on understanding the underlying concepts rather than memorizing answers, as interviewers often ask follow-up questions based on your responses.


Leave a Reply

Your email address will not be published. Required fields are marked *