Spring Boot has become the de facto standard for building modern Java applications, particularly in microservices, RESTful APIs, and cloud-native architectures. Its opinionated framework, powerful auto-configuration, and extensive ecosystem allow developers to focus more on business logic and less on boilerplate code.
Because of its widespread adoption, Spring Boot is now a core topic in technical interviews for Java and backend development roles. Interviewers frequently assess a candidate’s knowledge of core Spring Boot features, annotations, dependency management, and how well they understand the framework’s behavior in real-world scenarios.
This blog presents a comprehensive set of 50 Spring Boot interview questions and answers, carefully organized by difficulty level. Whether you are a fresher, a working developer, or preparing for a senior backend role, this guide will help you revise key concepts, understand best practices, and confidently handle both conceptual and coding rounds in interviews.
Who Should Read This Blog?
This blog is tailored for anyone preparing for technical interviews that involve Spring Boot—whether for backend development, full-stack engineering, or cloud-native application roles. With its structured approach and progressive question set, it is suitable for a broad audience:
- Java developers looking to strengthen their understanding of Spring Boot fundamentals
- Backend engineers working on microservices or REST APIs using the Spring ecosystem
- Computer science graduates or freshers preparing for entry-level Java/Spring interviews
- Experienced professionals revisiting Spring Boot for senior or lead-level technical interviews
- Career switchers or self-taught developers transitioning into backend or enterprise Java roles
Whether you are aiming for product-based companies, startups, or enterprise IT teams, this guide will help you build clarity around key concepts and explain them with confidence during interviews.
Let us now begin with the Basic-Level Spring Boot Interview Questions and Answers.
Basic-Level Spring Boot Interview Questions (1–15)
1. What is Spring Boot?
Answer:
Spring Boot is an open-source framework built on top of the Spring Framework. It simplifies the development of stand-alone, production-grade Spring applications by providing auto-configuration, embedded servers, and opinionated defaults.
2. How is Spring Boot different from the traditional Spring Framework?
Answer:
Spring Boot reduces boilerplate configuration by offering:
- Auto-configuration of beans and components
- Embedded web servers like Tomcat or Jetty
- Convention over configuration
- Minimal XML setup
Traditional Spring requires extensive manual configuration and external server deployment.
3. What is the role of the @SpringBootApplication
annotation?
Answer:@SpringBootApplication
is a meta-annotation that combines:
@Configuration
@EnableAutoConfiguration
@ComponentScan
It marks the main class and enables component scanning and auto-configuration.
4. How do you run a Spring Boot application?
Answer:
A Spring Boot application can be run using:
- The
main()
method withSpringApplication.run()
- The command
mvn spring-boot:run
orgradle bootRun
- Executing the generated
.jar
file withjava -jar
5. What is the default port of a Spring Boot application?
Answer:
By default, Spring Boot applications run on port 8080 when using an embedded server like Tomcat.
6. How do you change the default port of a Spring Boot application?
Answer:
You can change the port in application.properties
:
server.port=9090
or in application.yml
:
server:
port: 9090
7. What are Spring Boot Starters?
Answer:
Starters are dependency descriptors that simplify Maven or Gradle configurations. They bundle commonly used dependencies for specific functionalities.
Example:
spring-boot-starter-web
(for building web apps and RESTful APIs)spring-boot-starter-data-jpa
(for JPA and Hibernate integration)
8. What is auto-configuration in Spring Boot?
Answer:
Auto-configuration automatically sets up application beans based on classpath settings, property files, and annotations. It reduces the need for manual configuration.
9. How is dependency management handled in Spring Boot?
Answer:
Spring Boot uses a parent POM that provides dependency versions. You can include only the necessary dependencies without specifying version numbers, ensuring compatibility.
10. What is the difference between @Component
, @Service
, and @Repository
?
Answer:
All three are specializations of @Component
and enable component scanning:
@Component
: Generic component@Service
: Business logic layer@Repository
: Data access layer (with exception translation enabled)
11. What is the use of application.properties
or application.yml
?
Answer:
These files store external configuration settings such as port number, database URL, logging levels, and custom properties. They allow environment-specific and centralized configuration.
12. What is the use of the @RestController
annotation?
Answer:@RestController
is a combination of @Controller
and @ResponseBody
. It is used to build RESTful web services and automatically serializes return values into JSON or XML.
13. How can you create a simple REST endpoint in Spring Boot?
Answer:
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
14. What is the purpose of the @RequestMapping
annotation?
Answer:@RequestMapping
is used to map web requests to controller methods. It supports various HTTP methods through attributes like method = RequestMethod.GET
.
15. How do you handle dependency injection in Spring Boot?
Answer:
Spring Boot handles dependency injection using annotations:
@Autowired
for field or constructor injection@Component
,@Service
,@Repository
to define beans- Constructor-based injection is preferred for testability and immutability
Intermediate-Level Spring Boot Interview Questions (16–30)
16. What is the difference between @ComponentScan
and @EnableAutoConfiguration
?
Answer:
@ComponentScan
: Tells Spring where to look for annotated components (like@Service
,@Controller
) for dependency injection.@EnableAutoConfiguration
: Enables Spring Boot’s auto-configuration mechanism, allowing the framework to automatically configure beans based on classpath dependencies.
17. What is Spring Boot DevTools and why is it useful?
Answer:spring-boot-devtools
is a development-time dependency that provides features like automatic restarts, live reload, and configuration caching. It improves developer productivity by reflecting changes without restarting the application manually.
18. How do you configure a Spring Boot application to connect to a database?
Answer:
By setting properties in application.properties
or application.yml
, for example:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=pass
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
19. What is @Value
annotation used for in Spring Boot?
Answer:@Value
is used to inject property values into fields from external configuration files.
Example:@Value("${server.port}")
private int port;
20. How do you handle exceptions in Spring Boot REST APIs?
Answer:
By using @ControllerAdvice
and @ExceptionHandler
annotations:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
21. What is the use of @Entity
and @Table
in Spring Boot?
Answer:
@Entity
: Marks a class as a JPA entity to be mapped to a database table.@Table
: Optionally specifies the name of the table (if different from the class name).
22. What is Spring Data JPA and why is it used in Spring Boot?
Answer:
Spring Data JPA simplifies database access by eliminating boilerplate code for repositories. It supports CRUD operations, pagination, and custom queries with method naming conventions or @Query
.
23. What is the difference between CrudRepository
, JpaRepository
, and PagingAndSortingRepository
?
Answer:
CrudRepository
: Basic CRUD functionalityPagingAndSortingRepository
: Adds pagination and sorting capabilitiesJpaRepository
: Extends both and adds JPA-specific operations (e.g., batch inserts)
24. How do you enable CORS in a Spring Boot application?
Answer:
Using @CrossOrigin
annotation:
@CrossOrigin(origins = "http://example.com")
@GetMapping("/api/data")
public String getData() {
return "Some data";
}
25. How do you secure endpoints using Spring Security in Spring Boot?
Answer:
By adding spring-boot-starter-security
and creating a security configuration class:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and().httpBasic();
}
}
26. What is the difference between @RestController
and @Controller
?
Answer:
@RestController
: Returns data directly (e.g., JSON) without a view@Controller
: Returns a view (typically used with web templates like Thymeleaf)
27. How do you read a custom property value in Spring Boot?
Answer:
Using @ConfigurationProperties
:
@ConfigurationProperties(prefix = "myapp")
public class MyAppConfig {
private String name;
// getters and setters
}
Or using @Value("${myapp.name}")
directly.
28. What are profiles in Spring Boot and how do you use them?
Answer:
Profiles allow you to define different configurations for different environments (e.g., dev, test, prod). You can activate a profile using:
propertiesCopyEditspring.profiles.active=dev
And annotate config classes or beans using @Profile("dev")
29. How do you implement logging in Spring Boot?
Answer:
Spring Boot supports logging with Logback, Log4j2, or Java Util Logging. You can configure it via application.properties
:
logging.level.org.springframework=INFO
logging.file.name=app.log
Use Logger
in classes:
private static final Logger logger = LoggerFactory.getLogger(MyClass.class);
30. What is the difference between application.properties
and application.yml
?
Answer:
Both are used for configuration, but:
application.properties
: Flat key-value formatapplication.yml
: YAML format with hierarchical structure
Choose based on personal or team preference; both are supported natively.
Advanced-Level Spring Boot Interview Questions (31–40)
31. What is Spring Boot Actuator?
Answer:
Spring Boot Actuator provides production-ready features such as monitoring and managing applications. It exposes endpoints to retrieve application metrics, health status, environment properties, and more.
Example endpoints:
/actuator/health
/actuator/metrics
/actuator/env
You can enable specific endpoints in application.properties
:
propertiesCopyEditmanagement.endpoints.web.exposure.include=health,info
32. How do you secure actuator endpoints?
Answer:
Actuator endpoints can be secured using Spring Security. For example, restrict access using role-based authentication in your WebSecurityConfigurerAdapter
:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.requestMatchers(EndpointRequest.to("health", "info")).permitAll()
.requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN")
.and().httpBasic();
}
33. What are custom starter dependencies in Spring Boot?
Answer:
A custom starter is a reusable module that bundles pre-configured dependencies, configurations, and autoconfiguration logic. It follows the naming pattern your-module-spring-boot-starter
and simplifies inclusion of standard components across multiple projects.
34. How does Spring Boot handle external configuration priority?
Answer:
Spring Boot follows a well-defined order of configuration loading. From highest to lowest priority:
command-line arguments
application.properties
/application.yml
in current directoryapplication.properties
inside JAR (/config
folder)application.properties
inside JAR root- Default values in
@Value
or Java code
35. What is Spring AOP and how is it used in Spring Boot?
Answer:
Spring AOP (Aspect-Oriented Programming) allows separation of cross-cutting concerns such as logging, transaction management, or security.
Common annotations:
@Aspect
: Marks a class as an aspect@Before
,@After
,@Around
: Define pointcuts for method interception
Spring Boot automatically supports AOP via spring-boot-starter-aop
.
36. How do you implement custom error pages in Spring Boot?
Answer:
You can create custom HTML pages like error/404.html
or error/500.html
in the resources/templates
or resources/static
folder.
Alternatively, use @ControllerAdvice
with @ExceptionHandler
for API-based responses:
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> handle404(ResourceNotFoundException ex) {
return new ResponseEntity<>("Not found", HttpStatus.NOT_FOUND);
}
37. How can you optimize Spring Boot application startup time?
Answer:
- Use lazy initialization (
spring.main.lazy-initialization=true
) - Minimize unused auto-configurations via
spring.factories
exclusions - Reduce the number of beans scanned and initialized at startup
- Use
@Profile
to disable development-only configurations in production
38. What is the use of @Conditional
annotations in Spring Boot?
Answer:
Conditional annotations allow conditional registration of beans based on properties or environment:
@ConditionalOnProperty
@ConditionalOnClass
@ConditionalOnMissingBean
Example:
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
@Bean
public MyFeature feature() {
return new MyFeature();
}
39. How does Spring Boot support testing?
Answer:
Spring Boot provides several annotations for testing:
@SpringBootTest
: Loads the full application context@WebMvcTest
: For controller-layer testing@DataJpaTest
: For JPA repository testing@MockBean
: Replaces beans with mocks
It uses embedded databases (like H2) for in-memory testing.
40. What is the use of spring.factories
in Spring Boot?
Answer:
The spring.factories
file is used to register classes for auto-configuration and other extension points. Located in META-INF/
, it enables modular configuration discovery.
Example:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.MyAutoConfiguration
Scenario-Based Spring Boot Interview Questions (41–50)
41. How do you connect a Spring Boot application to a MySQL or PostgreSQL database?
Answer:
Update application.properties
with connection details:
propertiesCopyEditspring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=pass
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
Add the relevant JDBC driver in your pom.xml
:
xmlCopyEdit<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
42. How would you create a REST API that returns a list of employees in JSON format?
Answer:
javaCopyEdit@RestController
@RequestMapping("/employees")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@GetMapping
public List<Employee> getAllEmployees() {
return employeeService.findAll();
}
}
Ensure the Employee
class is annotated with @Entity
and returned list is serialized automatically as JSON.
43. How do you handle a custom 404 error for a missing resource in a REST API?
Answer:
Define a custom exception and handle it globally:
javaCopyEdit@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> handle404(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
44. How would you monitor a Spring Boot service using Actuator and Prometheus?
Answer:
- Add dependencies:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- Enable Prometheus metrics in
application.properties
:
management.endpoints.web.exposure.include=prometheus
management.endpoint.prometheus.enabled=true
- Prometheus can then scrape metrics from
/actuator/prometheus
.
45. How do you run a Spring Boot application as a Docker container?
Answer:
- Create a Dockerfile:
FROM openjdk:17-jdk-alpine
COPY target/app.jar app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]
- Build the JAR and Docker image:
mvn clean package
docker build -t springboot-app .
- Run the container:
bashCopyEditdocker run -p 8080:8080 springboot-app
46. How would you implement pagination in a Spring Boot REST API?
Answer:
Use Spring Data JPA’s PagingAndSortingRepository
or JpaRepository
:
@GetMapping
public Page<Employee> getEmployees(@RequestParam int page, @RequestParam int size) {
return employeeRepository.findAll(PageRequest.of(page, size));
}
47. How would you enable and use caching in Spring Boot?
Answer:
- Add caching dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
- Enable caching:
@SpringBootApplication
@EnableCaching
public class App { }
- Annotate the method:
@Cacheable("employees")
public Employee getEmployeeById(Long id) { ... }
48. How do you call an external REST API from a Spring Boot application?
Answer:
Using RestTemplate
:
@RestController
public class ApiController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/external")
public String callApi() {
return restTemplate.getForObject("https://api.example.com/data", String.class);
}
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
Or use WebClient
(preferred in reactive apps):
WebClient webClient = WebClient.create();
String response = webClient.get()
.uri("https://api.example.com/data")
.retrieve()
.bodyToMono(String.class)
.block();
49. How would you handle environment-specific configurations in Spring Boot?
Answer:
- Create multiple property files:
application-dev.properties
application-prod.properties
- Set the active profile:
spring.profiles.active=dev
Or via command line:
java -jar app.jar --spring.profiles.active=prod
50. How would you validate incoming request data in a REST API?
Answer:
Use @Valid
and validation annotations:
public class UserDTO {
@NotBlank
private String name;
@Email
private String email;
}
@PostMapping("/users")
public ResponseEntity<?> createUser(@Valid @RequestBody UserDTO user) {
// save user
return ResponseEntity.ok("User saved");
}
Handle errors using @ControllerAdvice
to return custom validation error responses.
Core Concepts to Revise Before an Interview
To succeed in a Spring Boot interview, candidates must demonstrate both conceptual clarity and the ability to apply the framework to real-world development scenarios. Below is a structured summary of the key topics to review:
1. Spring Boot Annotations
@SpringBootApplication
,@RestController
,@Autowired
@Component
,@Service
,@Repository
@RequestMapping
,@GetMapping
,@PostMapping
, etc.@Entity
,@Table
,@Id
,@GeneratedValue
2. Dependency Injection and Bean Lifecycle
- Constructor vs. field injection
- Singleton, prototype, and request scopes
@Bean
and@Configuration
usage- Lazy initialization and bean lifecycle callbacks
3. Application Configuration
application.properties
vs.application.yml
- External configuration hierarchy
- Environment-specific profiles and
@Profile
- Custom configuration using
@Value
and@ConfigurationProperties
4. REST API Development
- Building controllers with
@RestController
- JSON request/response handling with
@RequestBody
and@ResponseBody
- Request validation using
@Valid
and JSR-303 annotations - Exception handling using
@ControllerAdvice
and@ExceptionHandler
5. Spring Data JPA and Database Integration
- Defining entities and repositories (
JpaRepository
,CrudRepository
) - Query methods and
@Query
annotation - Pagination and sorting with
Pageable
- Connecting to databases using JDBC or JPA
6. Auto-Configuration and Starters
- Purpose of
spring-boot-starter-*
dependencies - How Spring Boot performs classpath-based auto-configuration
- Customizing or disabling auto-configuration using
@EnableAutoConfiguration
and exclusions
7. Spring Boot Actuator and Monitoring
- Using Actuator endpoints:
/health
,/metrics
,/env
,/info
- Securing and customizing endpoint exposure
- Integration with monitoring tools like Prometheus and Grafana
8. Security and Authentication
- Adding
spring-boot-starter-security
- Configuring basic HTTP authentication and method-level security
- Role-based access control using
@PreAuthorize
,@Secured
- Customizing login pages and authentication providers
9. Testing Spring Boot Applications
- Using
@SpringBootTest
,@WebMvcTest
,@DataJpaTest
- Mocking beans with
@MockBean
- Writing unit tests for REST controllers and services
- Testing with embedded databases
10. DevOps and Deployment
- Creating executable JAR files using Maven or Gradle
- Writing Dockerfiles and running Spring Boot in containers
- Configuring application startup parameters
- Managing configuration via environment variables and command-line arguments
By reviewing these core areas—alongside hands-on practice—you will be better equipped to answer both theoretical and scenario-based Spring Boot interview questions. Clear explanations, practical knowledge, and familiarity with real-world use cases will set you apart as a prepared candidate.
Conclusion
Spring Boot has transformed enterprise Java development by streamlining application setup, reducing boilerplate code, and offering a powerful ecosystem for building microservices, REST APIs, and cloud-native solutions. As a result, it is one of the most sought-after skills in technical interviews for backend and full-stack roles.
In this blog, we covered 50 thoughtfully organized Spring Boot interview questions and answers—ranging from core concepts and annotations to advanced topics like Actuator, profiles, AOP, and real-world integration patterns. Whether you are a fresher, an experienced developer, or transitioning into backend development, this guide is designed to enhance your understanding and improve your confidence in technical interviews.