Top 50 SpringBoot Interview Questions and Answer
Spring Boot Interview Question With Answer
Spring Boot is an open-source framework for building standalone, production-ready Spring applications. It provides a quick
approach to creating microservices and web applications using the Spring Framework, avoiding the need for significant standard
code.
Top 20 Spring Boot Interview Questions and Answers For Beginners
1. What is Spring Boot?
Spring Boot is developed on top of the Spring framework to create stand-alone RESTful web applications with minimal
configuration. The application does not require external servers to function because it has embedded servers such as Tomcat and
Jetty.
In this Java Tutorial, I'll cover the top 50 Spring Boot interview questions and answers, separated into three categories: 20 for
beginners, 15 for intermediate developers, and 15 for experienced experts. This article will help you fully prepare for any Spring
Boot interviews you may have.
The Spring Boot framework operates independently.
It creates production-ready spring apps.
Spring Boot includes several important features. A few of them are listed below:
Auto-configuration: Spring Boot automatically configures dependencies using the @EnableAutoconfiguration annotation,
reducing boilerplate code.
2. What are the Features of Spring Boot?
2.
The key componentsof Spring Boot are given below:
Spring Boot Starters
Auto-configuration
Spring Boot Actuator
Spring Boot CLI for Embedded Servers
@SpringBootApplication represents a shortcut for three annotations: @Configuration, @EnableAutoConfiguration, and
@ComponentScan. It initializes the application context and enables auto-configuration.
Spring Boot manages dependencies with the Maven or Gradle build tools. It includes a set of default dependencies that may be
modified, allowing developers to select the most relevant versions and libraries for their applications.
Spring Boot Starters are pre-configured sets of dependencies that make it simple to include the necessary libraries for various
functionalities, including web development, security, and JPA.
Spring Boot is a framework for building standalone, production-grade Spring-based applications, offering many advantages.
Easy to use: Spring Boot reduces the amount of boilerplate code required to construct a Spring application.
Rapid Development: Spring Boot's opinionated approach and auto-configuration allow developers to create apps quickly
without the need for time-consuming setup, reducing development time.
Scalable: Spring Boot applications are designed to be scalable. This means that they may be easily scaled up or down to meet
your application's requirements.
Production-ready: Spring Boot contains capabilities such as metrics, health checks, and externalized configuration, all of which
are intended for usage in production situations.
Spring Boot Starter POM: These POMs provide pre-configured dependencies for functions such as database, security, and
Maven setup.
Spring Boot CLI (Command Line Interface): This command line tool is mostly used for managing dependencies, creating
projects, and running apps.
Actuator: The Spring Boot Actuator performs health checks, collects metrics, and monitors application endpoints. It also
facilitates troubleshooting management.
Embedded Servers: Spring Boot has embedded servers such as Tomcat and Jetty that allow applications to execute quickly.
There is no need for external servers.
Q6. Define the Key Components of Spring Boot.
Q3. Explain the concept of Spring Boot Starters.
Q7. How does Spring Boot handle dependencies?
Q5. What are the advantages of using Spring Boot?
Q4. What is the purpose of the @SpringBootApplication annotation?
Example:
<dependency>
org.springframework.boot
spring-boot-starter-web
</dependency>
3.
Feature
Web Development
Data Access
Security
Here'sa table that outlines why we prefer Spring Boot over Spring Framework.
Default Dependency
spring-boot-star ter-web
spring-boot-star ter-data-jpa
spring-boot-starter-security
Detailed steps for creating a project using Spring Boot.
Step 1: Open Spring Initializr by going to https://start.spring.io.
Step 2:Specify Project Details: To produce and download a Spring Boot project, input all the required information and click the
Produce Project button. Then, open the downloaded zip file and drag it into your favorite integrated development environment.
Step 3: After that, import the file into Eclipse.
In Eclipse, choose File -> Import -> Existing Maven Project. Navigate to or enter the location of the folder where you extracted the
zip file on the following page. After you click Finish, Maven will need some time to download all the dependencies and start the
project.
Aspect
Setup
Configuration
Development Speed
Spring Boot
Spring Boot automatically configures your project,
making setup simpler and faster.
Allows faster development with less boilerplate
code.
Spring Framework
Manual configuration is required, which might take
a long and be complex.
Development is slower because more setup is
needed.
and
Dependency
Management
Embedded Server
Manages dependencies automatically, simplifying
project setup.
It includes an embedded server that allows you to
run applications directly.
Designed for microservices, making them easy to
create and deploy.
It includes features like metrics and health checks
that are out of the box.
Has a large community with frequent updates and
extensive resources.
Dependencies need to be managed manually,
which can be complicated.
Requires an external server setup to deploy
applications.
It can be used for microservices but requires more
configuration.
Does not include these features by default; they
need to be added manually.
Also has a strong community, but it evolves more
slowly compared to Spring Boot.
Microservices
Production-Ready
Features
Community&
Ecosystem
Spring Boot includes multiple starter dependencies. The following are some of the most commonly utilized in the Spring Boot
application:
Data JPA starter
Web starter
A web application called Spring Initializr helps you establish a new Spring Boot project easily by choosing dependencies,
configuring project metadata, and producing a project structure that is ready for use.
Q9 What is Spring Initializr?
Q8 Why do we prefer Spring Boot over Spring?
Q11 What are the Spring Boot Starter Dependencies?
Q10 How do you create a Spring Boot project using Spring Initializer?
4.
Security starter
Test Starterz
Thymeleafstarter
The application context is automatically configured via auto-configuration using the dependencies found in the classpath.
As a result, less manual configuration is required, which facilitates getting started.
A Spring application is launched by invoking the main() method of the SpringApplication class, which has
@SpringBootApplication annotation.
This function accepts a SpringApplicationBuilder object as an argument and is used to configure the application.
Once the SpringApplication object is constructed, the run() function is invoked.
After initializing the application context, the run() method launches the program's embedded web server.
To disable a certain auto-configuration class in a Spring Boot application, use the @EnableAutoConfiguration annotation and the
"exclude" attribute.
the
Spring Boot Starters are a set of pre-configured Maven dependencies that make it easy to create specific types of apps. These
starters include:
Dependencies
Version Control
Certain features require configuration to function properly.
To use a Spring Boot startup dependency, simply add it to your project's pom.xml file. For example, to include the Spring Boot
starting web dependency, add the following dependent to the pom.xml file:
Q12 How does a spring application get started?
Q14 How do you disable a specific auto-configuration class?
Q13 Explain the concept of auto-configuration in Spring Boot.
Q14 What is the starter dependency of the Spring boot module?
Example
Example
Example
<dependency>
org.springframework.boot
@SpringBootApplication
public class MySpringApplication {
}
public static void main(String[] args) {
SpringApplication.run(MySpringApplication.class, args);
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
5.
spring-boot-starter-web
</dependency>
@ConfigurationProperties(prefix = "app")
publicclass AppConfig {
}
private String name;
private String description;
// getters and setters
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().permitAll();
}
Q16 How does Spring Boot handle security?
Q17 How do you create a custom banner in Spring Boot?
Q19 How does Spring Boot handle external configuration?
Q15 How do you create a Spring Boot project using boot CLI?
Spring Boot supports a variety of external configuration options.
Spring Boot interfaces with Spring Security to handle authentication and authorization.
It has default setups that can be changed with annotations and security configuration classes.
Setting up the CLI: Use SDKMAN to install the Spring Boot CLI (Command-Line Interface) directly!
Employing the CLI: Once installed, run the CLI by typing spring and pressing Enter.
Launch a New Project: Using start.spring.io and the init command, you can launch a new project without leaving the shell.
Using the Embedded Shell: Spring Boot includes command-line completion techniques for the BASH and ZSH shells.
To build a custom startup banner, place a banner.txt file in the src/main/resources directory.
Inside banner.txt, you can add any text, ASCII art, or messages you want to display when the application starts.
Run the application, and your custom Spring Boot banner will appear in the console.Q18 What is the use of
@ConfigurationProperties in Spring Boot?
@ConfigurationProperties maps properties from application.properties or application.yml to Java objects. This provides organized
access to your application's configuration properties.
Example
Example
6.
HTTPS requests passthrough a Spring Boot application.
The flow of HTTPS requests through a Spring Boot application is as follows:
The client initiates an HTTP request (GET, POST, PUT, DELETE) to the browser.
Following that, the request is routed to the controller, where it is mapped and handled along with all other requests.
The @ControllerAdvice and @ExceptionHandler annotations in Spring Boot allow exceptions to be handled globally.
This enables the logic for addressing errors throughout the program to be centralized.
Yes, we can turn off the default web server in the Spring Boot application. To accomplish this, change the server. Port property in the
application.properties file to "-1".
The default port for Spring Boot's embedded Tomcat server is 8080. We can alter the default port by modifying the server. A port
attribute in your application's application.properties file.
It supports property files (application.properties or application.yml) that can be stored in a variety of locations, including the
classpath, file system, and external directories.
Spring Boot also allows environment variables, command-line arguments, and the creation of profiles for various deployment
contexts.
The configuration values can be obtained using the @Value annotation or bound to Java objects using the
@ConfigurationProperties annotation.
Q21 What is Tomcat's default port in spring boot?
Q20 How do you handle exceptions in Spring Boot?
Q22 Can we disable the default web server in the Spring Boot application?
Q23 Explain the flow of HTTPS requests through the Spring Boot application.
Example
Top 15 Spring Boot Interview Questions and Answers For Intermediates
@ControllerAdvice
public class GlobalExceptionHandler {
}
@ExceptionHandler(Exception.class)
public ResponseEntity handleException(Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
7.
Annotation
@RequestMapping
@GetMapping
Purpose
Annotation that canbe used for handling HTTP requests of all methods, including GET and POST.
A specialized version of @RequestMapping is used to handle GET requests.
Following this, all business logic will be executed in the Service layer. It performs business logic on data that has been mapped
to JPA (Java Persistence API) via model classes.
The repository layer handles all CRUD activities for the REST APIs.
If there are no errors, the end users receive a JSP page.
Spring Boot allows you to construct RESTful web services using the @RestController and @RequestMapping annotations. The
@RestController annotation automatically serializes return objects to JSON or XML, making it simple to build REST APIs.
Spring Boot interfaces with databases via Spring Data JPA, simplifying the data access layer. The program often provides
configuration information. Property files and repositories are built by extending the JpaRepository.
The @RestController annotation is essentially a shortcut for creating RESTful services. It combines two annotations.
@Controller: Indicates that the class is a request handler in the Spring MVC framework.
@ResponseBody: This tells Spring to convert method return values (objects, data) directly into HTTP responses rather than
rendering views.
It allows us to define endpoints for multiple HTTP methods (GET, POST, PUT, and DELETE), return data in various forms (e.g., JSON,
XML), and map request parameters to method arguments.
Q27 How do you integrate Spring Boot with a database?
Q24 Explain @RestController annotation in Spring Boot.
Q25 How do you implement RESTful web services in Spring Boot?
Q26 What is the difference between @RequestMapping and @GetMapping in Spring Boot?
Example
Example
Example application.properties:
@RestController
@RequestMapping("/api")
public class MyRestController {
}
@GetMapping("/items")
public List getItems() {
return itemService.getAllItems();
}
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
8.
}
// getters andsetters
spring.datasource.password=password
@Service
public class UserService {
}
@Transactional
public void createUser(User user) {
userRepository.save(user);
}
Pageable pageable = PageRequest.of(0, 10);
Page users = userRepository.findAll(pageable);
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
@Repository
public interface UserRepository extends JpaRepository {
}
Page findAll(Pageable pageable);
Q28 What is the purpose of @Entity in Spring Boot?
The @Entity annotation defines a JPA entity, which is a lightweight, persistent domain object that represents a table in a database. It
is commonly used alongside @Id, @GeneratedValue, and other JPA annotations.
Q29 How do you implement pagination in Spring Boot?
Spring Boot pagination can be accomplished using Spring Data JPA's Pageable interface. It enables data retrieval in pieces, which
improves performance when working with huge datasets.
Q30 What is the purpose of @Transactional in Spring Boot?
The @Transactional annotation manages transactions in Spring Boot applications. Developers can create transactional boundaries
to ensure data consistency and rollback in the event of an error.
Q31 Difference between @Controller and @RestController.
Example
Example
Example
Example usage:
9.
Security
Features
Feature
Packaging
Component
Scanning
Example
Configuration
Application
Request
mapping.
handling &
To useSpring Profiles, simply define the spring.profiles.active property and select which profile to use.
Spring is a framework that includes a variety of modules for developing enterprise-level applications.
Spring Profiles are similar to different scenarios for an application based on its surroundings.
You create sets of configurations (such as database URLs) for various scenarios (development, testing, production).
Use the @Profile annotation to specify which configuration belongs where.
Activate profiles using environment variables or command-line parameters.
Features
When
Use
Entry Point
@SpringBootApplication @EnableAutoConfiguration
It is used when we want to customize
auto-configuration.
It can be used on any configuration class
or with @SpringBootApplication.
toIt is used when we want to use auto-configuration.
It is typically used on the main class of a Spring Boot application,
serving as the entry point.
It includes @ComponentScan annotation to enable componentIt does not perform component scanning
scanning. by itself.
WAR
It contains all the files needed to deploy a web application
to a web server.
It requires external configuration files (e.g., web.xml,
context.xml) to define the web application.
It can be deployed to a web server that is configured with
security features.
Embedded Containers
It is a web application server included in the same
JAR file as the application code.
It uses configuration properties or annotations
within the application code.
It can be made more secure by using security
features provided by JRE.
It is used to mark a class as a controller. It is a combination of @Controller and
@ResponseBody.
It is used for RESTful APIs.
It is used for web applications.
It is used with @RequestMapping to map HTTPIt is used to handle requests like GET, PUT,
requests to methods. POST, and DELETE.
Q35 Spring Vs. Spring Boot?
Q33 What are Profiles in Spring?
Q32 What are the differences between @SpringBootApplication and
@EnableAutoConfiguration annotation?
Q34 What are the differences between WAR and embedded containers?
@SpringBootApplication
public class MyApplication {
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Configuration
@EnableAutoConfiguration
public class MyConfiguration { }
10.
Practice
Profiles
Security
Monitoring
Performance
Optimization
Optimization Area
Database Connections
Caching
Techniques
Itis done by using connection pooling and lazy loading.
It is implemented using @Cacheable and Redis.
Description
It is used to manage different settings for development, testing, and production environments.
It involves implementing HTTPS, OAuth2, and JWT to ensure secure communication.
It is done using Actuator, Prometheus, and Grafana to monitor application health and performance
effectively.
It is achieved by fine-tuning database connections, caching strategies, and memory usage to enhance
application performance.
Spring Cloud, which includes tools for service discovery, load balancing, circuit breakers, and distributed tracing, can be used to
construct microservices. Each service has its own Spring Boot program.
Best practices include creating profiles for environment-specific setups, putting in place security measures, optimizing
performance, and establishing monitoring and logging.
Spring Boot is a framework that makes Spring development easier by offering a pre-configured environment in which
developers may focus on developing application logic.
Spring Cloud Config supports externalized configuration on both the server and the client sides of a distributed system. It enables
Spring Boot applications to retrieve configuration properties from a common store.
Performance optimization includes fine-tuning database connections, caching, shortening startup time, and reducing memory use.
To monitor performance data, employ tools such as Spring Boot Actuator and JMX.
Top 15 Spring Boot Interview Questions and Answers For Experienced.
Q36 What are the best practices for building a production-grade Spring Boot application?
Q37 How do you implement microservices using Spring Boot?
Q38 What is Spring Cloud Config, and how is it used in Spring Boot?
Q39 How do you optimize the performance of a Spring Boot application?
Example
Example Configuration
spring.cloud.config.uri=http://localhost:8888
@SpringBootApplication
public class MyMicroserviceApplication {
}
public static void main(String[] args) {
SpringApplication.run(MyMicroserviceApplication.class, args);
}
11.
Dependency
Overriding
Features
Dependency
Immutability
Startup Time
Memory Usage
ConstructorInjection
It is provided through constructor parameters.
It promotes immutability as dependencies are set at
creation.
It is harder to override dependencies with different
implementations.
It is improved by using a spring-context-indexer to reduce startup time.
It is optimized by adjusting JVM settings and bean scopes.
Versioning can be accomplished using URI versioning, request parameter versioning, or header versioning.
Setter Injection
It is set through setter methods after object creation.
It allows dependencies to be changed dynamically
after object creation.
It allows easier overriding of dependencies using
different setter values.
Spring Cloud Gateway is a simple and efficient approach to route requests to various microservices. It provides load balancing, path
rewriting, and security while also serving as an API gateway.
Dependency Injection (DI) is a design pattern that lets us create loosely linked components. In DI, an object's capacity to execute a
job is dependent on another object. There are three forms of dependence injections.
Constructor injection is the most used method of DI in Spring Boot, and constructor injection involves injecting the dependent
object into the dependent object's constructor.
Setter injection involves injecting the dependent object into the dependent object's setter method.
Field injection involves injecting the dependent object into the dependent object's field.
Q40 What is dependency injection, and what are its types?
Q43 How do you handle versioning in a Spring Boot application?
Q41 What is the difference between Constructor and Setter Injection?
Q42 What is the role of Spring Cloud Gateway in a Spring Boot microservices architecture?
Example
Example Configuration
spring:
cloud:
gateway:
routes:
- id: myService
uri: http://localhost:8081
predicates:
- Path=/service/**
@SpringBootApplication
public class GatewayApplication {
}
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
12.
Example
Example
Q46 How doyou handle transactions in Spring Boot?
Spring Boot manages transactions with the @Transactional annotation.
Q44 What differentiates Spring Data JPA and Hibernate?
Q45 How do you secure RESTful web services in Spring Boot?
Spring Security can be used to secure RESTful web services by leveraging OAuth2, JWT tokens, and role-based access control.
Hibernate, a Java Persistence API (JPA) implementation, enables Object-Relational Mapping (ORM) by allowing users to store,
retrieve, map, and change application data across Java objects and relational databases.
Hibernate converts Java data types to SQL (Structured Query Language) data types and Java classes to database tables,
allowing developers to avoid scripting data persistence in SQL applications.
Spring Data JPA, a Spring Data sub-project, provides abstraction over the DAL (Data Access Layer) by combining JPA and
Object-Relational Mapping implementations like Hibernate.
Spring Data JPA makes it easier to construct JPA repositories and aims to improve DAL implementation significantly.
@RestController
@RequestMapping("/api/v1")
public class MyController {
}
@GetMapping("/users")
public List getUsersV1() {
// Version 1 implementation
}
@RestController
@RequestMapping("/api/v2")
public class MyControllerV2 {
}
@GetMapping("/users")
public List getUsersV2() {
// Version 2 implementation
}
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/public").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login();
}
13.
This annotation ensuresthat database actions within a method are carried out within a transaction.
If an operation fails, all changes are reversed to ensure data consistency.
Advanced transaction management allows you to configure propagation behavior, isolation level, and rollback rules.
Spring Boot DevTools is a module that boosts developer productivity by enabling automatic application restart, live reloading, and
configurable property overrides. This enables developers to observe changes in real-time without manually restarting the
application, which speeds up the development process.
Spring Boot apps can be tested using a variety of approaches: Unit testing focuses on testing individual components, such as
services or repositories, utilizing frameworks such as JUnit and Mockit.
This ensures that each component of the program works independently. Integration testing determines how various
components of an application interact with one another.
Spring Boot supports the @SpringBootTest annotation, which loads the entire application context for testing.
Slice testing focuses on specific layers of the application (such as the web, service, and data layers).
Spring Boot performance optimization uses a variety of methods, including caching, connection pooling, and query optimization.
Using @Cacheable annotations, allowing connection pooling (e.g., HikariCP), and optimizing database queries with correct
indexing and pagination can all help to enhance application speed.
Spring Boot externalizes configuration via properties files, YAML files, environment variables, or command-line arguments.
Externalizing configuration increases the application's flexibility, allowing it to be quickly modified without requiring code
modifications when switching between contexts such as development, staging, and production.
Example
Example
Q50 What are the different ways to test Spring Boot applications?
Q47 How can you optimize the performance of a Spring Boot application?
Q49 How do you externalize configuration in Spring Boot, and why is it important?
Q48 What is Spring Boot's DevTools, and how does it enhance development productivity?
# application.yml
server:
port: 8080
@Service
public class AccountService {
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: user
password: pass
}
@Transactional
public void transferMoney(Long fromAccountId, Long toAccountId, BigDecimal amount) {
// Perform debit from source account
// Perform credit to destination account
}
14.
To test onlythe necessary parts of the application, use annotations such as @WebMvcTest, @DataJpaTest, and
@RestClientTest. End-to-End Testing: Ensures that the entire application works as expected, which is commonly accomplished
with automated UI testing tools such as Selenium or Cucumber.
This article includes a comprehensive list of the top 50 Spring Boot interview questions organized by experience level. It has 20
questions for beginners, 15 for intermediate developers, and 15 for seasoned pros. The questions cover key Spring Boot
concepts such as configuration, transactions, security, and performance, with actual code examples and clear explanations to
help with interview preparation. To build your career in Java, consider our Full-Stack Java Developer Certification Training Course.
Summary
View More