Spring Boot remains a cornerstone of modern Java development, empowering developers to build production-ready applications with minimal configuration. As demand for Spring Boot expertise grows, acing technical interviews requires a deep understanding of its core concepts, annotations, and best practices. This blog compiles the most frequently asked Spring Boot interview questions, curated from industry trends. Let’s dive in!
Table of Contents
1. What is Spring Boot?
Spring Boot is a framework built on top of Spring that simplifies application development by providing auto-configuration, embedded servers (e.g., Tomcat), and starter dependencies. It reduces boilerplate code and accelerates deployment.
Key Features:
- Auto-configuration based on classpath dependencies.
- Embedded servers for standalone execution.
- Production-ready tools like Actuator for monitoring.
2. How does Spring Boot differ from Spring Framework?
Spring Framework | Spring Boot |
---|---|
Requires manual configuration (XML/Java). | Auto-configuration reduces setup. |
Less production-ready out of the box. | Built-in metrics, health checks, and security. |
Slower development cycles. | Rapid development with starters and CLI |
3. Explain the @SpringBootApplication Annotation
This annotation combines three annotations:
- @Configuration: Marks the class as a configuration source.
- @EnableAutoConfiguration: Enables auto-configuration based on dependencies.
- @ComponentScan: Scans for components in the package.
Example:
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
4. What are Spring Boot Starters?
Starters simplify dependency management by bundling common libraries. Examples include:
- spring-boot-starter-web: For web applications.
- spring-boot-starter-data-jpa: For database access.
- spring-boot-starter-security: For authentication
5. How to Change the Embedded Tomcat Port?
Add server.port
in application.properties
:
server.port=8081
6. What is Spring Boot Actuator?
Actuator provides production-ready endpoints to monitor and manage applications, such as:
/health
: Application health status./metrics
: Performance metrics./info**: Custom application details. Enable it by adding the
spring-boot-starter-actuator` dependency
7. How to Handle Exceptions Globally in Spring Boot?
Use @ControllerAdvice
and @ExceptionHandler
:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleError(UserNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
}
8. How to Secure a Spring Boot REST API?
- Add
spring-boot-starter-security
. - Extend
WebSecurityConfigurerAdapter
to configure HTTP security:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
9. Explain Spring Profiles
Profiles allow environment-specific configurations (e.g., dev
, prod
). Activate them via application-{profile}.properties
or set spring.profiles.active=dev
10. How to Connect Spring Boot to a Database Using JPA?
- Add
spring-boot-starter-data-jpa
and database driver (e.g., MySQL). - Configure
application.properties
:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
- Create a repository interface extending
JpaRepository
11. What is the Role of @RestController?
@RestController
combines @Controller
and @ResponseBody
, enabling RESTful web services that return JSON/XML instead of views.
12. How to Implement Pagination in Spring Data JPA?
Use Pageable
in repository methods:
@GetMapping("/users")
public Page<User> getUsers(Pageable pageable) {
return userRepository.findAll(pageable);
}
We have a detail post on how to implement pagination and sorting in Spring Boot.
13. What is Dependency Injection in Spring Boot?
Dependency Injection (DI) allows Spring to inject dependencies (e.g., services, repositories) into classes via @Autowired
, promoting loose coupling.
14. How to Test a Spring Boot Application?
- Use
@SpringBootTest
for integration tests. - Mock dependencies with
@MockBean
and@WebMvcTest
for controller testing.
15. What is Spring Boot DevTools?
DevTools enhances development with features like automatic restarts, live reload, and debug configurations. Add the dependency below in your pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
16. How to Deploy a Spring Boot Application to Docker?
- Create a
Dockerfile
:
FROM openjdk:17
COPY target/myapp.jar /app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]
- Build and run the image.
17. What are the Advantages of YAML over Properties Files?
YAML supports hierarchical configurations, improving readability for complex setups:
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost/mydb
18. How to Schedule Tasks in Spring Boot?
Use @EnableScheduling
and @Scheduled
:
@Scheduled(fixedRate = 5000)
public void runTask() {
System.out.println("Task executed every 5 seconds");
}
19. What is Spring Cloud?
Spring Cloud extends Spring Boot for building distributed systems (microservices), offering tools for service discovery, configuration management, and load balancing.
20. How to Enable CORS in Spring Boot?
Use @CrossOrigin
on controllers or configure globally:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://example.com");
}
};
}
21. What is the difference between @Controller and @RestController?
@Controller is used in Spring MVC to handle HTTP requests and return views (HTML pages). @RestController combines @Controller and @ResponseBody, returning data directly in JSON/XML format for RESTful APIs
22. How to disable Actuator security in Spring Boot?
Set management.security.enabled=false
in application.properties
. However, this is not recommended for production and should only be used in secured environments.
23. What is an IoC Container in Spring Boot?
The Inversion of Control (IoC) container manages object creation, dependencies, and lifecycle. It injects dependencies using @Autowired, promoting loose coupling.
24. Explain the @Transactional annotation.
@Transactional annonation ensures database operations are atomic. If an exception occurs, it rolls back changes. Commonly used in service layers for database transactions.
25. How to enable HTTP/2 in Spring Boot?
Add server.http2.enabled=true
in application.properties
. Requires an embedded server like Tomcat 9+ or Jetty.
26. What is the ELK Stack, and how does it integrate with Spring Boot?
The ELK Stack (Elasticsearch, Logstash, Kibana) aggregates and visualizes logs. Integrate it by configuring Logstash to collect logs and Elasticsearch to store them, then use Kibana for analysis.
27. How to implement JWT authentication in Spring Boot?
- Add
spring-boot-starter-security
. - Create a JWT filter to validate tokens.
- Configure
WebSecurityConfigurerAdapter
to enable JWT-based security
28. How to test a Spring Boot service using Mockito?
Use @MockBean to mock dependencies and @SpringBootTest for integration testing:
@SpringBootTest
public class UserServiceTest {
@MockBean
private UserRepository userRepository;
@Test
public void testFindUserById() {
when(userRepository.findById(1L)).thenReturn(Optional.of(new User("Radha")));
assertEquals("Radha", userService.findUserById(1L).getName());
}
}
29. What is Spring Data JPA?
Spring Data JPA simplifies database operations by providing repository interfaces (e.g., JpaRepository
) and reducing boilerplate code for CRUD operations.
30. What is Swagger, and how to integrate it with Spring Boot?
Swagger is an API documentation tool. Integrate it using springfox-boot-starter
and annotate controllers with @Api and @ApiOperation.
31. How to handle file uploads in Spring Boot?
Use MultipartFile in a controller method:
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
// Save file logic
return "File uploaded!";
}
You can read the detail example on File Upload Spring Boot.
Configure file size limits in application.properties
. You can also read how to define file upload size limit in spring boot for more detail.
32. What is Spring Boot Admin?
A community tool for monitoring Spring Boot applications. It provides a dashboard to view health, logs, and metrics via Actuator endpoints.
33. How to implement caching in Spring Boot?
- Add
spring-boot-starter-cache
. - Enable caching with @EnableCaching.
- Annotate methods with @Cacheable or @CacheEvict
34. What is the difference between JPA and Hibernate?
JPA is a specification, while Hibernate is an implementation of JPA. Spring Boot uses Hibernate by default for ORM.
35. How to use H2 Database in Spring Boot?
Add h2
dependency and configure application.properties
:
spring.datasource.url=jdbc:h2:mem:testdb
spring.h2.console.enabled=true
Access the H2 console at /h2-console
.
36. How to customize the Spring Boot banner?
Well, this question may not be asked in an interview, but it is good to know.
Add a banner.txt
file in src/main/resources
or disable it with spring.main.banner-mode=off
.
37. What are the best practices for Spring Boot logging?
- Use SLF4J with Logback.
- Configure levels in
application.properties
:
logging.level.root=INFO
logging.level.com.example=DEBUG
Conclusion
Mastering these Spring Boot interview questions will give you a competitive edge in 2025’s job market. Focus on hands-on practice, explore advanced topics like microservices and reactive programming, and stay updated with Spring Boot’s evolving ecosystem.