20 Most Asked Spring Boot Interview Questions
Prepare for your Spring Boot interviews with our curated list of the 20 Most Asked Spring Boot Interview Questions. Designed to boost your confidence, this article provides key insights and answers to help you excel in your next interview.
Santosh Mane
December 07, 2024
18 min read
20 Most Asked Spring Boot Interview Questions
Spring Boot has become one of the most popular frameworks in the Java ecosystem for building microservices and standalone applications. If you're preparing for an interview, having a strong grasp of Spring Boot concepts is essential. Below, we’ve compiled the 20 most frequently asked Spring Boot interview questions, complete with detailed answers.
1. What is Spring Boot, and how does it differ from Spring?#
Spring Boot is a framework built on top of the Spring Framework. It streamlines the process of building and deploying Spring-based applications by addressing the complexity of configuration and setup. With Spring Boot, developers can focus more on writing business logic and less on infrastructure and configuration.
Key Features of Spring Boot#
1. Auto-Configuration
Spring Boot's auto-configuration feature automatically configures application components based on the dependencies and settings present in the application. This eliminates the need for most boilerplate code and manual configuration.
- For example, if the
spring-boot-starter-web
dependency is included, Spring Boot automatically configures:- DispatcherServlet for handling web requests.
- Default settings for a web server.
- Jackson for JSON serialization/deserialization.
2. Embedded Server Support
Spring Boot provides built-in support for embedded servers like Tomcat, Jetty, or Undertow, enabling developers to run web applications directly without requiring an external application server.
This simplifies deployment as the application can be packaged as a standalone JAR file, runnable with java -jar
:
3. Starter Dependencies
Spring Boot introduces the concept of starter dependencies, which are curated dependency sets that provide all the necessary libraries for specific functionalities. This reduces the hassle of managing individual dependencies.
- Example:
spring-boot-starter-web
includes dependencies for Spring MVC, Jackson, and an embedded Tomcat server.spring-boot-starter-data-jpa
bundles Hibernate, Spring Data JPA, and a database driver.
4. Production-Ready Features
Spring Boot includes features like:
- Health checks using Actuator.
- Metrics and monitoring.
- Pre-configured logging (Logback by default).
5. Opinionated Defaults
Spring Boot provides sensible defaults for application configurations, which can be customized as needed. This balances flexibility and ease of use.
This table shows how Spring Boot Differs from Traditional Spring#
Feature | Spring Framework | Spring Boot |
---|---|---|
Configuration | Requires extensive manual configuration in XML or Java. | Uses auto-configuration to minimize manual setup. |
Server Setup | Requires deploying to an external server like Tomcat or Jetty. | Comes with an embedded server, eliminating the need for external servers. |
Dependencies | Requires managing individual dependencies for each functionality. | Provides starter dependencies to simplify dependency management. |
Deployment | Typically packaged as a WAR file for deployment. | Packaged as a standalone JAR with everything included. |
Monitoring & Metrics | Requires additional tools or manual setup. | Built-in support via Spring Boot Actuator. |
2. What are the advantages of using Spring Boot?#
Advantages of Using Spring Boot
1. Simplified Dependency Management
Spring Boot starters provide pre-configured dependencies for common use cases, reducing the complexity of managing individual dependencies.
2. Production-Ready Features
Includes tools like Spring Boot Actuator for monitoring application health, gathering metrics, and managing your app in production.
3. Embedded Server Support
Comes with built-in support for embedded servers like Tomcat, Jetty, or Undertow, enabling applications to run as standalone JAR files without external server setup.
4. Minimal Configuration
Leverages annotations and auto-configuration to eliminate boilerplate XML or manual Java configurations.
5. Microservices-Friendly
Easily integrates with Spring Cloud, making it ideal for developing microservices with features like service discovery and load balancing.
By using Spring Boot, you focus more on business logic while the framework handles configurations and setup.
3. What is a Spring Boot Starter?#
A Spring Boot Starter is a collection of pre-configured dependencies that make it easier to set up a specific functionality in your Spring Boot application. Instead of manually adding each individual dependency, you can include a single starter that provides everything you need for a particular feature.
Examples:
- spring-boot-starter-web: Provides dependencies for building web applications, including Spring MVC, embedded Tomcat, and Jackson for JSON processing.
- spring-boot-starter-data-jpa: Includes dependencies for working with JPA (Java Persistence API) and Hibernate, simplifying database access and entity management.
These starters save time by offering a streamlined approach to dependency management, allowing you to focus more on application logic.
4. What is Spring Boot Auto Configuration?#
Spring Boot Auto Configuration is a feature that automatically configures application beans based on the classpath, existing beans, and properties set in the application. It reduces the need for manual configuration, making it easier to set up and maintain Spring applications.
For example, if you add the spring-boot-starter-web
dependency, Spring Boot will automatically configure necessary components like a DispatcherServlet for handling web requests, without needing explicit configuration in the application.
This behavior is powered by conditional configuration classes that check for the presence of specific classes in the classpath and configure relevant beans accordingly, enabling zero or minimal configuration in the application.
5. Explain the @SpringBootApplication
annotation.#
The @SpringBootApplication
annotation is a composite annotation that combines three key Spring annotations to simplify configuration in Spring Boot applications:
- @Configuration: Marks the class as a configuration class, meaning it can define beans that are used in the Spring context.
- @EnableAutoConfiguration: Enables Spring Boot's auto-configuration mechanism, which automatically configures application components based on the classpath and existing beans.
- @ComponentScan: Scans the current package (and its sub-packages) for Spring components, such as
@Component
,@Service
,@Repository
, and@Controller
, automatically registering them in the application context.
Example:#
By using @SpringBootApplication
, you don’t need to add @Configuration
, @EnableAutoConfiguration
, and @ComponentScan
separately, as it's all bundled together, making the code cleaner and more concise.
6. What is Spring Boot Actuator?#
Spring Boot Actuator is a set of production-ready features that help you monitor and manage your Spring Boot application. It exposes a variety of built-in endpoints to provide insights into the health, metrics, and other critical aspects of the application.
Common Endpoints:#
- /actuator/health: Provides the health status of the application (e.g., "UP" or "DOWN"), useful for checking if the application is running smoothly.
- /actuator/metrics: Displays various application metrics like memory usage, request counts, and more, helping monitor performance.
Customization:#
You can customize the Actuator endpoints and configure which ones are enabled or disabled using properties in the application.properties
file, allowing control over what is exposed to external systems.
Example configuration:
Spring Boot Actuator helps in monitoring the application's health and performance, providing valuable information for debugging and production monitoring.
7. What is JPA, Hibernate, Spring-data-jpa and how they are related ?#
1. Hibernate
Hibernate is an Object-Relational Mapping (ORM) framework for Java. It simplifies the process of mapping Java objects to database tables and handling data persistence. Hibernate handles the underlying database operations, reducing the need to write complex SQL queries manually.
2. JPA (Java Persistence API)
JPA is a specification that defines a standard for ORM in Java. It outlines how Java objects should be mapped to database tables but doesn’t provide an actual implementation. It provides standard annotations like @Entity, @Table, and @Id for defining entity classes.
3. Spring Data JPA
Spring Data JPA is a part of the Spring Data project, designed to simplify data access layers in Spring applications. It provides an abstraction over JPA, making it easier to work with database entities and perform CRUD (Create, Read, Update, Delete) operations. Allows you to define repository interfaces like JpaRepository, CrudRepository, etc., to manage entity objects without writing boilerplate code. Enables you to define custom queries using method names, e.g., findByUsername(String username), and Spring Data JPA generates the query automatically.
How They are related ?
JPA provides the standard API and guidelines for ORM in Java.
Hibernate is an implementation of the JPA specification and can be used as the JPA provider to manage database interactions.
Spring Data JPA simplifies working with JPA by providing repository interfaces, query generation, and additional features, making it easier to manage data access in Spring applications.
Spring Data JPA is a layer on top of JPA that simplifies working with databases in Spring applications. It uses Hibernate (or another JPA provider) behind the scenes to perform the actual database interactions.
8. What is the role of application.properties
and application.yml
?#
Both application.properties
and application.yml
are configuration files used to define application-specific properties in a Spring Boot application. They allow you to externalize configuration, making it easier to modify settings without changing the code.
Common Properties:#
- spring.datasource.url: Specifies the database URL for the data source.
- server.port: Defines the custom port number on which the application runs (default is 8080).
Differences:#
- application.properties: A flat key-value format (key=value).
- application.yml: A more structured, hierarchical format, using indentation for nested properties.
Example of application.properties
:
Example of application.yml
:
Both files serve the same purpose, but you can choose either format based on preference or project requirements.
9. What is a CommandLineRunner
in Spring Boot?#
CommandLineRunner
is a functional interface in Spring Boot that allows you to execute specific code once the Spring Boot application has started. It's commonly used for tasks like initialization, pre-loading data, or running custom logic after the application context is fully initialized.
Key Points:#
- The
run
method ofCommandLineRunner
is executed after the application starts. - It provides the
String... args
parameter, allowing you to access command-line arguments passed to the application.
Example:#
In this example, the message "Application started!" will be printed to the console when the application starts.
CommandLineRunner
is useful for running tasks that need to happen at startup, without the need for additional configuration or setup.
10. What is a Spring Boot Profile?#
A Spring Boot Profile is a way to segregate configuration for different environments, such as development (dev), testing (test), and production (prod). Profiles allow you to define environment-specific settings in your application, making it easy to switch between configurations depending on the environment the application is running in.
Key Points:#
- Profiles enable configuration segregation for different stages of the application lifecycle (e.g., dev, test, prod).
- You can define environment-specific properties in separate
application-{profile}.properties
orapplication-{profile}.yml
files.
Activating a Profile:#
You activate a profile by setting the spring.profiles.active
property in the application.properties
file or as a command-line argument.
Example:
In this example, the "dev" profile is activated, and the application will use the application-dev.properties
or application-dev.yml
file for configuration.
Benefits:#
- Easily manage multiple configurations without modifying the code.
- Helps in maintaining environment-specific values (e.g., database URLs, API keys).
11. What are @RestController and @Controller?#
@Controller: This annotation is used in traditional MVC (Model-View-Controller) applications. It defines a controller that handles HTTP requests and returns views (e.g., JSP or HTML). It is typically used in applications where you want to render HTML responses or manage a user interface.
Example:
@RestController: This is a specialized version of @Controller
. It combines @Controller
and @ResponseBody
, meaning that it handles HTTP requests and directly returns data (e.g., JSON or XML), rather than rendering a view. It is commonly used in RESTful web services or APIs.
Example:
Key Differences:#
@Controller
returns views (HTML/JSP).@RestController
returns data (JSON/XML) directly without the need for a view.
12. How does Spring Boot handle exceptions globally?#
Spring Boot handles exceptions globally using @ControllerAdvice
and @ExceptionHandler
.
- @ControllerAdvice: This annotation is used to define a global exception handler for all controllers in the application. It allows you to centralize exception handling logic.
- @ExceptionHandler: This annotation is used within
@ControllerAdvice
to define methods that handle specific exceptions. You can specify the exception type, and Spring Boot will automatically call the appropriate method when that exception is thrown.
Example:#
In this example:
- Any exception of type
Exception
(or its subclasses) will be caught by thehandleException
method. - The method returns a
ResponseEntity
with anINTERNAL_SERVER_ERROR
status and the exception message in the response body.
Benefits:#
- Centralized exception handling.
- Clean and reusable error management across controllers.
13. What is IoC and How Does IoC Work in Spring?#
Inversion of Control (IoC):
IoC is a design principle where the control of object creation and dependency management is transferred from the application to a container, such as the Spring IoC container
Working :-
- Configuration: The Spring IoC container is configured using XML, Java annotations, or Java-based configuration classes.
- Bean Creation: The container reads the configuration and creates the required beans.
- Dependency Injection: The container injects the necessary dependencies into the beans.
- Bean Management: The container manages the lifecycle of the beans, including initialization and destruction.
14. What is Hibernate and How do you integrate Spring Boot with Hibernate?#
Hibernate is an Object-Relational Mapping (ORM) framework for Java, which simplifies database interactions by mapping Java objects to database tables and vice versa. It handles CRUD operations, complex queries, and transactions, reducing the need for manual SQL queries.
Integration of Spring Boot with Hibernate:#
Spring Boot simplifies the integration of Hibernate by using Spring Data JPA, which provides an abstraction layer over Hibernate. This allows you to use Hibernate without needing to write extensive configuration code.
Steps to integrate Hibernate with Spring Boot:#
Add Dependencies:
- Add the necessary dependencies for Spring Data JPA and the database driver (e.g., for MySQL, PostgreSQL) in the
pom.xml
orbuild.gradle
.
Configure DataSource:
- Configure the
DataSource
inapplication.properties
orapplication.yml
.
Create Entity Classes:
- Define Java classes as entities and annotate them with
@Entity
,@Table
, and other relevant JPA annotations.
Create Repository Interface:
- Use Spring Data JPA’s
JpaRepository
to interact with the database.
Use in Service/Controller:
- Inject the repository and perform CRUD operations.
Benefits of Using Hibernate with Spring Boot:#
- Simplified database interaction via ORM.
- Automatic configuration of Hibernate through Spring Data JPA.
- No need to write SQL queries for common CRUD operations, as Spring Data JPA generates them automatically.
This integration allows you to manage the persistence layer efficiently with minimal setup and boilerplate code.
15. What is Spring Boot DevTools?#
Spring Boot DevTools is a set of tools that enhance the development experience by enabling features like hot swapping, live reload, and faster application restarts.
Key Features:#
- Hot Swapping: Allows developers to make changes to the code and see the results immediately without restarting the application. This speeds up development by eliminating the need for manual restarts.
- Live Reload: Automatically refreshes the browser when changes are made to the application, ensuring the UI is always up-to-date with minimal effort.
- Automatic Restart: Spring Boot DevTools monitors changes in the application and automatically restarts the application when classes or resources change, reducing manual intervention and improving development efficiency.
- Enhanced Debugging: Provides additional logging and better debugging support, making it easier to identify and resolve issues during development.
How to Use:#
Add Dependency: Add the Spring Boot DevTools dependency to your pom.xml
or build.gradle
.
Example (pom.xml):
Automatic Configuration: DevTools automatically works when the application is running in development mode. It doesn't require additional configuration to enable most features.
Benefits:#
- Speeds up the development cycle by reducing time spent on manual restarts.
- Improves developer productivity through faster feedback loops and automatic browser refreshes.
- Makes the development process more efficient and user-friendly.
Spring Boot DevTools is primarily intended for use in development environments and should not be included in production builds due to its impact on performance.
16. How do you secure a Spring Boot application?#
Securing a Spring Boot application involves several strategies to ensure authentication, authorization, and overall protection of the application from threats. Here’s how you can secure a Spring Boot application:
1. Use Spring Security:#
Spring Security is a powerful framework for securing Java applications, providing features like authentication, authorization, and protection against common security threats (CSRF, session fixation, etc.).
Add dependency:
2. Authentication and Authorization:#
Use AuthenticationManager to handle user authentication. You can configure authentication using in-memory users, JDBC authentication, or integrating with external systems (like OAuth2 or LDAP).
Example for in-memory authentication:
3. Password Encoding:#
Always store passwords in a secure, encoded format using a password encoder like BCryptPasswordEncoder.
4. Role-Based Access Control (RBAC):#
Use @PreAuthorize or @Secured annotations to restrict access to certain methods based on user roles or authorities.
Example:
5. Enable HTTPS:#
Enforce secure communication by configuring SSL in your application to support HTTPS.
Example (application.properties):
6. Cross-Site Request Forgery (CSRF) Protection:#
Spring Security provides CSRF protection by default. It should be disabled only if necessary (for stateless APIs).
Example (disabling CSRF):
7. Session Management:#
Secure session management by setting session timeouts and limiting session fixation vulnerabilities.
Example:
8. JWT Authentication (for REST APIs):#
- For stateless authentication in REST APIs, you can use JWT (JSON Web Token) to authenticate and authorize users without storing sessions on the server.
- Example: Configure filters to intercept requests and validate JWT tokens.
9. API Rate Limiting and IP Blocking:#
- Protect your APIs from abuse by implementing rate limiting or blocking suspicious IP addresses.
- You can use third-party libraries or implement custom filters for this.
10. Security Headers:#
Add additional security headers to HTTP responses to mitigate attacks like XSS and clickjacking.
Example:
11. Monitor and Audit:#
- Use tools like Spring Boot Actuator for monitoring application health, and configure logging for auditing access and security-related events.
17. What are Spring Boot Filters?#
Filters process HTTP requests and responses.
Example of a custom filter:
18. What are the main differences between JpaRepository
and CrudRepository
?#
Both JpaRepository
and CrudRepository
are interfaces provided by Spring Data JPA for performing database operations. Here's a concise comparison:
1. Inheritance and Features:#
CrudRepository
:- Provides basic CRUD operations (Create, Read, Update, Delete).
- Minimal functionality.
JpaRepository
:- Extends
CrudRepository
andPagingAndSortingRepository
. - Includes additional features like batch processing and pagination and sorting.
- Extends
2. Pagination and Sorting:#
CrudRepository
:- Does not have built-in support for pagination and sorting.
JpaRepository
:
Provides pagination and sorting methods directly using the Pageable
and Sort
interfaces.
Example:
3. Custom Query Execution:#
CrudRepository
:- Limited in providing custom query methods.
JpaRepository
:- Supports JPA-specific functionality such as
flush()
for synchronizing changes with the database andsaveAndFlush()
for immediate commit.
- Supports JPA-specific functionality such as
4. Performance:#
CrudRepository
:- Suitable for simple operations without advanced features.
JpaRepository
:- Better suited for large-scale applications requiring pagination, sorting, or advanced JPA features.
5. Batch Operations:#
CrudRepository
:- Does not support batch operations like deleting or saving in bulk.
JpaRepository
:
Provides batch operations for improved performance.
Example:
Summary Table:#
Feature | CrudRepository | JpaRepository |
---|---|---|
Basic CRUD Operations | ✅ | ✅ |
Pagination and Sorting | ❌ | ✅ |
Batch Operations | ❌ | ✅ |
JPA-Specific Methods | ❌ | ✅ |
Suitable For | Simple applications | Advanced applications |
When to use?
- Use
CrudRepository
for basic operations and when you need simplicity. - Use
JpaRepository
for applications requiring advanced features like pagination, sorting, or batch processing.
19. What is the significance of Spring Boot testing annotations?#
Spring Boot provides various testing annotations that simplify writing and managing unit and integration tests by offering powerful tools to create application contexts, mock dependencies, and test application behavior. Here's a concise explanation:
Common Testing Annotations:#
@SpringBootTest
Purpose: Loads the full application context for integration tests.
Example:
@WebMvcTest
Purpose: Loads only the web layer (controllers, filters) for testing. Useful for testing REST controllers.
Example:
@DataJpaTest
Purpose: Configures an in-memory database and focuses on testing JPA repositories.
Example:
@MockBean
Purpose: Provides mock instances of beans, replacing actual ones in the application context.
Example:
@TestConfiguration
Purpose: Defines additional configurations for tests that do not affect the main application context.
Example:
@BeforeEach
and @AfterEach
- Purpose: Run setup or teardown logic before and after each test method.
Significance of Testing Annotations:#
- Simplifies Context Setup: Automatically configures the application context based on the test requirements.
- Improves Test Isolation: Provides specific testing scopes like web layer (
@WebMvcTest
) or JPA (@DataJpaTest
). - Mimics Real Scenarios: Allows testing with actual Spring behaviors (e.g., dependency injection, application context behavior).
- Supports Mocking: Ensures external dependencies are mocked without changing the actual application logic.
20. What are the different ways to deploy a Spring Boot application?#
Spring Boot provides flexibility in deployment, allowing applications to run in various environments. Here's a concise explanation:
1. Embedded Server Deployment#
Description: Spring Boot applications include an embedded web server (e.g., Tomcat, Jetty, Undertow), enabling standalone execution.
How to Deploy:
Package the application as a JAR.
Run using the command:
Use Case: Quick and lightweight deployment without external server dependency.
2. WAR Deployment on External Servers#
- Description: Spring Boot applications can be packaged as WAR files and deployed to external servers like Tomcat or JBoss.
- How to Deploy:
Updatepom.xml
to includespring-boot-starter-tomcat
as provided scope.
ExtendSpringBootServletInitializer
in the main application class:
Package as WAR and deploy to an external server.
- Use Case: Environments with pre-configured application servers.
3. Containerized Deployment#
Description: Use Docker to package the application along with its runtime environment.
How to Deploy:
Create a Dockerfile
:
Build and run the Docker image:
Use Case: Microservices and cloud environments.
4. Cloud Deployment#
- Description: Deploy directly to cloud platforms like AWS Elastic Beanstalk, Google App Engine, or Azure App Service.
- How to Deploy:
- Package as JAR or WAR.
- Use the respective cloud CLI or dashboard to upload and deploy.
- Use Case: Scalable and managed hosting.
5. Kubernetes Deployment#
- Description: Deploy in a containerized environment orchestrated by Kubernetes.
- How to Deploy:
- Use a
Deployment
andService
YAML file. - Apply Kubernetes configurations using
kubectl
.
- Use a
Summary Table:#
Deployment Type | Description | Use Case |
---|---|---|
Embedded Server (java -jar ) | Standalone execution with built-in server. | Local and lightweight deployments. |
WAR Deployment | Deploy to external app servers. | Legacy systems or existing infrastructure. |
Docker Container | Package app with runtime using Docker. | Microservices and cloud-ready apps. |
Cloud Platforms | Directly host on managed cloud services. | Scalable, managed solutions. |
Kubernetes | Containerized deployment with orchestration. | Large-scale, distributed systems. |
Conclusion:
The choice of deployment depends on the application's requirements, scalability needs, and existing infrastructure.