Top 30 Spring Boot Interview Questions (With Code Examples)
Hey developers, Sudip Bhaiya here!
If you’re preparing for a Java backend or microservices interview, then Spring Boot is a skill you just can’t skip. It’s the framework behind most modern Java projects—making application development faster, cleaner, and ready for production from day one.
In this post, I’ve shared the Top 30 Spring Boot Interview Questions with detailed explanations and real-world code examples. My goal is simple—to help you understand each concept practically, not just cram definitions. Whether you’re aiming for your first backend role or levelling up for senior interviews, these Spring Boot questions will help you stand out and speak with confidence.
Let’s decode Spring Boot together—one interview question at a time

1) What are the main features of Spring Boot?
Let’s start with the basics — why is everyone talking about Spring Boot?
The main reason is speed + simplicity. Spring Boot takes away all the heavy configuration that old Spring projects used to require and lets you focus directly on writing business logic.
Let’s go through the main features of Spring Boot, one by one:
a) Auto-Configuration: Spring Boot automatically configures your application based on the dependencies present in your project.
You don’t need to write long XML files or manual bean configurations.
If you add the spring-boot-starter-web dependency, Spring Boot automatically configures Tomcat, Spring MVC, and other required beans.
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
✅ No need to configure a DispatcherServlet or Tomcat manually — Spring Boot does it for you!
b) Starter Dependencies: Spring Boot provides a set of “starter” dependencies that group common libraries together.
Instead of searching and adding 10 different JARs manually, you just include a single starter dependency.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
✅ This single line brings in Spring MVC, Jackson (for JSON), and an embedded Tomcat server.
c) Embedded Servers: Spring Boot comes with embedded servers like Tomcat, Jetty, or Undertow.
So you don’t need to deploy your WAR file to an external server.
You can just run your app using:
mvn spring-boot:run
✅ Your app starts instantly like a standalone application.
d) Opinionated Defaults: Spring Boot gives you sensible default configurations for the most common setups — like database connections, logging, JSON serialisation, etc.
Of course, you can override these defaults anytime via the application.properties or application.yml file.
server.port=8085
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
✅ So, you get flexibility with convenience.
e) Easy Integration with Spring Ecosystem: Spring Boot easily integrates with:
- Spring Data JPA (for database)
- Spring Security (for authentication)
- Spring Cloud (for microservices)
- Spring Batch (for batch processing)
✅ This makes it a complete ecosystem for modern backend development.
2) What is @SpringBootApplication?
This is the point at which our Spring Boot application begins its execution. This annotation combines @Configuration, @EnableAutoConfiguration, and @ComponentScan. It marks the main class for bootstrapping your app.
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
3) What are Starter Dependencies?
Starter dependencies are pre-packaged sets of commonly used libraries that help you get started quickly without manually searching and adding dozens of dependencies.
Suppose you want to create a web application using Spring Boot.
In old Spring projects, you’d have to manually add dependencies like: spring-webmvc, jackson-databind, tomcat, validation-api and a few more…
That’s a lot to manage, right? 😅
But with Spring Boot, you can simply add one line:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
And boom 💥
You automatically get everything you need for a web project: Spring MVC, Jackson (for JSON support), an embedded Tomcat server, and Validation libraries.
Sudip Bhaiya’s Tip:
When starting a new Spring Boot project, always look for an existing starter dependency before adding any manual JARs.
It keeps your setup simple, stable, and consistent with the Spring Boot ecosystem 💪
4)Explain Spring Boot’s Auto-Configuration
Auto-Configuration means Spring Boot automatically configures your application based on the dependencies and settings it finds in your project — so you don’t have to write all the boilerplate setup yourself.
How Does It Work:
When your application starts:
--> 1st it will search for @SpringBootApplication
-->checks all the classes available in the classpath and auto-configures beans accordingly.
-->You can always override this configuration using your own @Bean definitions or properties.
Real-world example: If you add a database dependency and add info inside application.properties, Spring Boot automatically enables transaction management > creates a DataSource bean > Configures Hibernate EntityManager
5) How is Spring Boot different from Spring Framework?
Spring Boot automates setup (embedded servers, zero XML) while classic Spring requires manual configuration and external web servers.
6)How do you create a basic REST API in Spring Boot?
Creating an API with Spring Boot is super simple.
You don’t need to configure servers, XML files, or complex setups — just write your code, and Spring Boot handles the rest.
Steps to Create a REST API:
a) Create a Java Class with Controller tram (Example SudipBhaiyaController.java)
b) Annotate it with @RestController ( We are telling Spring Boot: “Hey Spring Boot Bhaiya, it is my Controller class”)
c)Write a method by which we will make API calls( Get, Put, Patch, Delete)
@RestController // Marks this class as a REST controller
public class HelloController {
@GetMapping("/hello") // Handles GET requests at /hello
public String sayHello() {
return "Hello from Sudip Bhaiya 👋 — Your first Spring Boot API!";
}
}
7) What is Dependency Injection in Spring Boot?
In programming, a dependency is just another class or object that your class needs to work with.
For example:
class Car {
Engine engine = new Engine();
}
Here, the Car depends on an Engine.
But notice — Car is creating the Engine The object itself is used new Engine().
Dependency Injection (DI) means giving an object its dependencies from outside, instead of creating them inside.( It is Loose Coupling, Easier Testing, Better Reusability, Cleaner Code).
There are three types of Dependency Injection we are using in Spring Boot: Constructor Injection, Setter Injection and Field Injection.
Sudip Bhaiya’s Tip:
Always go for Constructor Injection — it’s clean, testable, and avoids
NullPointerException.
Think of DI like this: You focus on what you need, Spring focuses on how to give it to you. 🔥
8) What is Spring Boot Actuator?
Spring Boot Actuator is a production-ready feature that provides built-in endpoints to monitor, manage, and get insights about your running Spring Boot application — without writing any extra code. It’s like adding a health check and performance dashboard directly into your backend.
9) What is the default server port number in Spring Boot?
The default server-side port number is 8080.
10) How do you customise the server port?
To customise the server port, we need to go application.properties and set the server.port.
server.port=8081
11. What is @RestController vs @Controller?
In Spring Boot, when you want to handle web requests, you use controllers.
But depending on what you return (HTML page or data), you use either @Controller or @RestController.
The main difference or use case is:
Use @Controller When building a web app with pages.
Use @RestController When building a REST API that sends/receives JSON data.
12) What is the role of application.properties?
There are very important roles or use cases available for application.properties:
a) For server config like changing port, context path etc.
b) Database Config like DataSource, JPA, Hibernate settings.
c) Logging like Control log levels for different packages.
d) Custom Properties like Store your own app settings.
e) Profiles like Different configs for dev, test, and prod environments.
13. How do you connect Spring Boot with a database using JPA?
Spring Boot makes it super simple with Spring Data JPA, so you can focus on writing business logic rather than boilerplate code.
Steps to follow to connect Spring Boot with a database using JPA:
Step 1: Add Dependencies in pom.xml
<dependencies>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Database Driver (MySQL example) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
Step 2: Configure the Database in application.properties
# Database connection
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JPA / Hibernate settings
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
Step 3: Create an Entity Class
An entity maps a Java class to a database table.
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Constructors
public User() {}
public User(String name, String email) {
this.name = name;
this.email = email;
}
// Getters & Setters
public Long getId() { return id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
Step 4: Create a Repository Interface
Spring Data JPA automatically implements CRUD methods if you extend JpaRepository
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
// You can define custom query methods if needed
}
14. How is exception handling managed in Spring Boot?
Spring Boot provides a clean, centralised way to handle these exceptions so we can maintain consistent and professional code. We can use these ways to handle exceptions:
a) Simple try-catch block
@GetMapping("/divide")
public int divide(@RequestParam int a, @RequestParam int b) {
try {
return a / b;
} catch (ArithmeticException e) {
return 0; // simple handling
}
}
b) Using @ExceptionHandler
@RestController
@RequestMapping("/api")
public class MathController {
// Handle ArithmeticException
@ExceptionHandler(ArithmeticException.class)
public String handleArithmeticException(ArithmeticException e) {
return "Error: Division by zero is not allowed!";
}
}
c) Global Exception Handling Using @ControllerAdvice
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ArithmeticException.class)
public ResponseEntity<String> handleArithmetic(ArithmeticException e) {
return new ResponseEntity<>("Division by zero is not allowed!", HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleAllExceptions(Exception e) {
return new ResponseEntity<>("Something went wrong: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
d) Custom Exception
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
15. What is Spring Boot DevTools?
When we are developing a Spring Boot application, every time we make a code change, we usually have to stop the app, rebuild it, and restart it. This is slow, boring, and interrupts your workflow. But Spring Boot DevTools solves this problem.
It’s a developer tool that helps you speed up development by enabling automatic restarts, live reload, and debugging features.
To use Spring Boot DevTools in our project, we need to add spring-boot-devtools dependency in our pom.xml.
16. How does Spring Boot manage dependencies?
In a normal Java project, managing dependencies can be painful, but Spring Boot makes this super simple by handling dependency management automatically through something called Starters and Dependency Management Plugin.
The spring-boot-starter-parent sets versions and plugins, ensuring consistent builds.
17. What is @EnableCaching and @Cacheable?
When our application fetches the same data again and again, like user details or product info, it can slow things down. That’s where caching comes in.
Caching means storing frequently accessed data temporarily (in memory)
so that the next time it’s needed, it can be fetched faster without hitting the database or an API again.
@EnableCaching is placed on your main Spring Boot application class.
It tells Spring Boot to look for caching annotations in your project and enable cache management.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@Cacheable is used on methods whose results you want to store (cache).
When the same method is called again with the same parameters, Spring Boot will return the cached result instead of executing the method again.
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
@Cacheable("products")
public String getProductById(int id) {
System.out.println("Fetching product from database..."); // just for demo
// Imagine this takes 2 seconds in real life
return "Product with ID: " + id;
}
}
18) How do you implement security in Spring Boot?
Spring Security is a Spring framework module that helps protect your application by: 🔑 Authentication – Verifying who the user is (like login) and🚦 Authorization – Checking what they can access (like admin/user roles)
It can secure REST APIs, Web applications, and Method-level access (using annotations like @PreAuthorize)
For implementing security in Spring Boot, we need to follow these steps:
a) Adding Spring Security Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
b) Default Login Credentials
When you run your app, Spring Boot auto-generates a default user and password. You can see this in your console.
Username → user
Password → shown in your console (changes every run)
Is there any way to change those? yes!
In application.property we need to add this:
spring.security.user.name=admin
spring.security.user.password=admin123
c) Customise endpoints for making public or protected
Spring Security give us control to decide which endpoint we want to make public or protected.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable() // Disable CSRF for APIs
.authorizeHttpRequests()
.requestMatchers("/public/**").permitAll() // Public URLs
.requestMatchers("/admin/**").hasRole("ADMIN") // Admin access
.anyRequest().authenticated() // All others need authentication
.and()
.httpBasic(); // Use Basic Auth (username + password)
return http.build();
}
}
d) Customer User Creation
@Configuration
public class UserConfig {
@Bean
public UserDetailsService userDetailsService() {
var user = User.withUsername("user")
.password(passwordEncoder().encode("user123"))
.roles("USER")
.build();
var admin = User.withUsername("admin")
.password(passwordEncoder().encode("admin123"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
e) JWT (JSON Web Token) for Modern APIs
In real-world applications, we use JWT authentication instead of Basic Auth.
JWT allows stateless authentication — no session, just a signed token.
Work Flow of JWT:
-->User logs in with credentials
------>Server verifies and sends a JWT token
--------->User sends token in Authorization header for each request
------------>Server validates token before processing
19. How does Spring Boot handle environments and profiles?
Before we understand how Spring Boot handles environments and profiles, let us first understand what are Environments & Profiles.
Environment = The runtime context of your app (like dev, test, prod).
Profile = A way to group and load environment-specific configurations automatically.
Basic Structure of Property Files
In your src/main/resources folder, you can have:
application.properties
application-dev.properties
application-test.properties
application-prod.properties
Now, for activating any particular profile in our application, we need to do in our application.properties:
spring.application.name=myapp
spring.profiles.active=dev
👉 This line means:
“Run the app with dev profile by default.”
We can use @Profile in any particular method, class or code for use or activate conditionally.
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
@Service
@Profile("dev")
public class DevDatabaseService implements DatabaseService {
public void connect() {
System.out.println("Connected to DEV database");
}
}
@Service
@Profile("prod")
public class ProdDatabaseService implements DatabaseService {
public void connect() {
System.out.println("Connected to PROD database");
}
}
20. What are embedded servers in Spring Boot?
In Spring Boot, we can have embedded Tomcat, Jetty, or Undertow for running apps directly (no external server installation needed).
21) How is logging performed in Spring Boot
Logging means recording information about your application’s execution — like errors, warnings, and important events — into the console or files.
Spring Boot uses SLF4J (Simple Logging Facade for Java) with Logback as the default logging framework. You don’t need to add anything — it’s included automatically when you use spring-boot-starter.
Using Logger in Your Code:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
@GetMapping("/hello")
public String hello() {
logger.info("Inside /hello endpoint");
logger.debug("Debugging some logic here...");
logger.warn("This is just a warning message");
logger.error("Error message for testing");
return "Hello, Spring Boot Logging!";
}
}
22) How to package a Spring Boot app as an executable JAR?
In Spring Boot, applications are typically packaged as executable JAR files using the built-in support provided by the Spring Boot Maven or Gradle plugin.
This means that instead of deploying a traditional WAR file on an external Tomcat server, the Spring Boot JAR already contains an embedded web server — usually Tomcat, Jetty, or Undertow — along with all required dependencies.
So, once it’s built, we can run the application just by executing:
java -jar myapp.jar
To create this executable JAR, we use:
mvn clean package
This command compiles the code, packages all dependencies, and produces a single fat JAR (also called an Uber JAR) inside the target/ directory.
The magic happens because of the Spring Boot Maven Plugin, which adds a special entry point and dependency management. For example, in pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Internally, Spring Boot packages all dependencies under BOOT-INF/lib and your compiled classes under BOOT-INF/classes.
Finally, you can simply run the JAR anywhere that has Java installed — no extra setup needed — making it portable, lightweight, and production-ready.
23) How to enable/disable auto-configuration?
By default, Spring Boot automatically configures the application based on the dependencies that are available in the classpath — this is known as auto-configuration.
For example, if we have spring-boot-starter-web in our project, Spring Boot will automatically configure: An embedded Tomcat server, DispatcherServlet, and Jackson for JSON conversion
However, sometimes we might want to disable a specific auto-configuration — for example, if we want to use our own custom configuration instead of the default one.
Spring Boot gives us multiple ways to enable or disable auto-configuration:
Enable Auto-Configuration:
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Disable Auto-Configuration (Globally)
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Disable Auto-Configuration via application.properties
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
24) How do you schedule tasks in Spring Boot?
In Spring Boot, we can schedule tasks using the Spring Scheduler — it allows us to execute methods automatically at a fixed interval, fixed delay, or based on a cron expression.
To use it, Spring Boot provides the @EnableScheduling and @Scheduled annotations, which make scheduling extremely easy to set up without needing any external libraries.
To enable Scheduling in Spring Boot, we need to add @EnableScheduling in main class.
@SpringBootApplication
@EnableScheduling
public class SchedulerApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulerApplication.class, args);
}
}
Now, create a simple service class with a scheduled method:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class MyScheduledTasks {
// Run every 5 seconds
@Scheduled(fixedRate = 5000)
public void performTask() {
System.out.println("Running task at: " + System.currentTimeMillis());
}
}
@Scheduled(fixedRate = 5000) → runs the task every 5 seconds, starting from the beginning of the last execution.
You can also use fixedDelay or cron expressions for more control.
Here is an example of a cron expression :
//cron expressions for more flexible scheduling — for example, to run a task every day at 10 AM:
@Scheduled(cron = "0 0 10 * * ?")
public void runDailyReport() {
System.out.println("Generating daily report at 10 AM");
}
In real-world projects, scheduling is used for: Sending scheduled email notifications, cleaning up expired sessions, generating daily/weekly reports, Syncing data from APIs periodically etc.
25) How do you handle file uploads in Spring Boot?
In Spring Boot, file uploads are handled easily using the MultipartFile interface provided by Spring MVC. Spring Boot automatically supports file uploads when you include the spring-boot-starter-web dependency.
Typically, we handle file uploads using a REST API endpoint that accepts files via HTTP POST requests with multipart/form-data content type.
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
byte[] bytes = file.getBytes();
Path path = Paths.get("uploads/" + file.getOriginalFilename());
Files.write(path, bytes);
return "Success!";
} catch (IOException e) {
return "Failed!";
}
}
26) What are the stereotype annotations in Spring Boot?
In Spring, stereotype annotations are special annotations that mark a class as a Spring-managed component, so that Spring automatically detects and registers it as a bean in the ApplicationContext.
@Component → generic bean
@Service → business logic
@Repository → data layer
@Controller → MVC web controller
@RestController → REST API controller
27. What’s the role of @Entity annotation?
In Spring Boot, when we use JPA (Java Persistence API) for database operations, the @Entity annotation is used to mark a Java class as a database entity.
Essentially, it tells Spring Boot (and Hibernate, the default JPA implementation) that this class should be mapped to a table in the database.
This enables automatic ORM (Object-Relational Mapping), so each object of this class corresponds to a row in the database table.
28) How to create custom error pages?
In Spring Boot, when an error occurs—like 404 Not Found or 500 Internal Server Error—Spring Boot automatically provides a default error page.
Spring Boot supports custom error pages using HTML pages, @ControllerAdvice, @RestControllerAdvice, or by overriding ErrorController.
Use HTML pages for UI apps and JSON responses for REST APIs.
29. What is Spring Initializr?
Spring Initializr is a web-based tool provided by the Spring team that helps developers quickly generate a Spring Boot project with all the necessary dependencies and configuration.
30. What is @Value annotation?
In Spring Boot, the @Value annotation is used to inject values into fields, method parameters, or constructor parameters from external sources like application.properties or application.yml, environment variables, or system properties.
Basic Usage with application.properties after declaring some value here
app.name=JavaInterviewPro
app.version=1.0.0
Now use this value inside a class
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class AppInfo {
@Value("${app.name}")
private String name;
@Value("${app.version}")
private String version;
public void printInfo() {
System.out.println("Application Name: " + name);
System.out.println("Application Version: " + version);
}
}
Always focus on building strong fundamentals. Skills you master today will open doors for opportunities tomorrow.
You can ask any doubts directly to your “Sudip Bhaiya” via Instagram
What is Spring Boot, and why is it popular?
What kind of questions are asked in a Spring Boot interview?
Most interviews cover core concepts like dependency injection, auto-configuration, REST API creation, JPA/Hibernate integration, actuator monitoring, and microservices communication patterns.
Who should prepare for Spring Boot interviews?
Anyone aiming for Java backend roles — including Full Stack Developers, Java Developers, and DevOps Engineers — should prepare. Mastering Spring Boot is essential for enterprise-level development and cloud deployments.
What are the most common Spring Boot annotations?
Some of the most frequently used annotations include:@SpringBootApplication (to bootstrap the app)@RestController and @GetMapping (for REST APIs)@Autowired (for dependency injection)@Entity and @Table (for JPA entities)@EnableAutoConfiguration (for configuration setup)
What is the difference between Spring and Spring Boot?
Spring Boot is built on top of the Spring Framework, eliminating the need for XML configuration, and includes embedded servers and starter dependencies, which enable faster development and deployment.
