0% found this document useful (0 votes)
35 views154 pages

Spring Boot Interview Questions

The document is a comprehensive guide containing 120 important Spring Boot interview questions and answers, aimed at beginners and covering various aspects of Spring Boot. It includes topics such as Spring Boot's features, components, configuration, testing, and security, as well as advanced concepts like microservices and distributed tracing. The content is structured in a way that facilitates understanding and preparation for interviews related to Spring Boot development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views154 pages

Spring Boot Interview Questions

The document is a comprehensive guide containing 120 important Spring Boot interview questions and answers, aimed at beginners and covering various aspects of Spring Boot. It includes topics such as Spring Boot's features, components, configuration, testing, and security, as well as advanced concepts like microservices and distributed tracing. The content is structured in a way that facilitates understanding and preparation for interviews related to Spring Boot development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 154

Copyright © 2025 by SkillForgePrep

Table of Content
120 Most Important Spring Boot Interview Questions and Answers for Beginners............. 9
1. What is Spring Boot?........................................................................................................... 9
2. Why do we need Spring Boot?............................................................................................ 9
3. What are the main advantages of using Spring Boot?........................................................ 9
4. What are the key features of Spring Boot?........................................................................10
5. What is the difference between Spring and Spring Boot?................................................. 10
6. What are Spring Boot components?.................................................................................. 11
7. What is a Spring Boot Starter?.......................................................................................... 11
8. How does auto-configuration work in Spring Boot?........................................................... 11
9. What is Spring Boot Actuator?........................................................................................... 11
10. How can you create a Spring Boot application?.............................................................. 12
11. What is Spring Boot Initializer?........................................................................................ 12
12. What is the role of @SpringBootApplication annotation?................................................ 12
13. How does Spring Boot handle dependency management?.............................................12
14. What happens when a Spring Boot application is "Run as Java Application"?............... 13
15. What is an embedded server in Spring Boot?................................................................. 13
16. How can you change the default port of the embedded server?..................................... 13
17. What is Spring Boot CLI?................................................................................................ 14
18. What are the possible sources of external configuration in Spring Boot?....................... 14
19. What is the difference between an embedded container and a WAR file?......................15
20. How do you exclude auto-configuration classes in Spring Boot?.................................... 15
21. What is Spring Boot DevTools?....................................................................................... 15
22. How do you access command-line properties in Spring Boot?....................................... 16
23. What is the Spring Boot Actuator health endpoint?......................................................... 16
24. How do you secure Spring Boot Actuator endpoints?..................................................... 17
25. What is a multi-module project in Spring Boot?...............................................................17
26. What are profiles in Spring Boot?.................................................................................... 17
27. How do you configure logging in Spring Boot?................................................................18
28. What is a condition in Spring Boot auto-configuration?................................................... 18
29. What is Spring Boot's property binding?..........................................................................19
30. How can you implement custom health indicators in Spring Boot?................................. 19
31. What is Spring Boot's relaxed binding?........................................................................... 20
32. What is Spring Data JPA in Spring Boot?........................................................................ 20
33. How do you handle exceptions in Spring Boot REST applications?................................20
34. What is the @SpringBootTest annotation used for?........................................................ 21
35. How do you test a controller in Spring Boot?...................................................................21
36. What is the CommandLineRunner interface in Spring Boot?.......................................... 22
37. What is the difference between @Controller and @RestController?...............................23

Copyright © 2025 by SkillForgePrep


38. How do you configure CORS in Spring Boot?................................................................. 23
39. What is Spring Boot's support for caching?..................................................................... 24
40. How do you implement pagination in Spring Boot REST APIs?......................................24
41. What are Spring Boot's auto-configuration report options?............................................. 25
42. How do you implement custom Banner in Spring Boot?................................................. 25
43. What is Spring Boot Admin?............................................................................................26
44. How do you connect Spring Boot to a database?............................................................26
45. What is Spring Boot's support for WebSockets?............................................................. 26
46. How do you handle file uploads in Spring Boot?............................................................. 27
47. What is Spring Boot's support for Reactive programming?............................................. 27
48. How do you implement internationalization (i18n) in Spring Boot?................................. 28
49. What is Spring Boot's Validation support?....................................................................... 29
50. How do you implement authentication and authorization in Spring Boot?.......................30
51. What is the significance of Spring Boot's application.properties file?.............................. 31
52. How do you define custom properties in Spring Boot?....................................................31
53. What is Spring Boot's handling of static resources?........................................................32
54. How do you implement scheduled tasks in Spring Boot?................................................33
55. How do you implement asynchronous processing in Spring Boot?.................................34
56. What is Spring Boot Starters POM?................................................................................ 35
57. How do you deploy a Spring Boot application?............................................................... 35
58. What is Spring Boot's support for testing?.......................................................................36
59. What is Spring Boot Actuator info endpoint?................................................................... 36
60. How do you use profiles for environment-specific configuration?....................................37
61. What is the difference between JPA and Hibernate in Spring Boot context?.................. 38
62. How do you handle database migrations in Spring Boot?............................................... 39
63. What is Spring Data REST in Spring Boot?.....................................................................39
64. How do you secure REST APIs in Spring Boot?............................................................. 40
65. What is the purpose of @RestControllerAdvice in Spring Boot?.....................................41
66. What is Spring Boot Starter Parent?................................................................................42
67. How do you implement transaction management in Spring Boot?.................................. 43
68. What is Spring Boot's support for NoSQL databases?.................................................... 44
69. How do you disable a specific auto-configuration in Spring Boot?.................................. 45
70. What is Spring Boot's support for messaging systems?..................................................45
71. How do you implement custom auto-configuration in Spring Boot?................................ 47
72. What is Spring Boot's support for WebClient?.................................................................48
73. How do you implement unit testing in Spring Boot?........................................................ 49
74. What is Spring Boot's support for caching?..................................................................... 50
75. What is the difference between @RequestParam and @PathVariable in Spring Boot?. 52
76. How do you implement aspect-oriented programming (AOP) in Spring Boot?................52
77. How do you implement custom validators in Spring Boot?..............................................54
78. What is the purpose of @ConfigurationProperties in Spring Boot?.................................55

Copyright © 2025 by SkillForgePrep


79. How do you implement API rate limiting in Spring Boot?................................................ 56
80. What is the purpose of @ResponseStatus in Spring Boot?............................................ 58
81. How do you implement WebSockets in Spring Boot?..................................................... 59
82. How do you implement Spring Boot integration testing with Docker?............................. 61
83. What is Spring Boot's support for GraphQL?...................................................................63
84. How do you implement request logging in Spring Boot?................................................. 64
85. What is the purpose of @ControllerAdvice in Spring Boot?............................................ 67
86. How do you implement HATEOAS in Spring Boot?.........................................................69
87. What is the purpose of @RequestBody and @ResponseBody annotations?................. 70
88. How do you implement conditional beans in Spring Boot?..............................................71
89. How do you handle application events in Spring Boot?...................................................73
90. What is Spring Boot's support for Kotlin?........................................................................ 75
91. What are Spring Boot's property binding rules?.............................................................. 76
92. What is the purpose of Spring Boot's @ImportAutoConfiguration?................................. 77
93. What is Spring Boot's ApplicationRunner interface?....................................................... 78
94. How do you create custom Spring Boot starter?............................................................. 79
95. How do you handle distributed tracing in Spring Boot?................................................... 82
96. How do you implement circuit breaker pattern in Spring Boot?.......................................84
97. What is Spring Boot's support for configuration groups?.................................................87
98. How do you handle JSON serialization and deserialization in Spring Boot?...................89
99. How do you implement paging and sorting in Spring Boot REST APIs?.........................91
100. How do you handle database connection pooling in Spring Boot?................................94
101. What is Spring Boot's support for content negotiation?................................................. 96
102. What is the purpose of @Conditional annotation in Spring Boot?.................................97
103. How do you implement file storage in Spring Boot applications?.................................. 99
104. What is Spring Boot's support for batch processing?.................................................. 103
101. How do you implement rate limiting in Spring Boot?................................................... 107
102. How does Spring Boot handle database migration?....................................................107
103. Explain Spring Boot’s @ConditionalOnProperty.......................................................... 107
104. How do you secure sensitive data in application.properties?...................................... 108
105. What is Spring Boot DevTools used for?..................................................................... 108
106. How do you handle cross-origin requests (CORS) in Spring Boot?............................ 108
107. What is the purpose of spring-boot-starter-parent?..................................................... 109
108. How do you expose custom metrics in Spring Boot?.................................................. 109
109. Explain Spring Boot’s @SpringBootTest...................................................................... 110
110. How do you implement OAuth2 in Spring Boot?.......................................................... 110
111. What is Spring Boot’s CommandLineRunner?............................................................. 111
112. How do you configure multiple databases in Spring Boot?.......................................... 111
113. Explain Spring Boot’s @ConfigurationProperties.........................................................112
114. How do you handle file uploads in Spring Boot?..........................................................113
115. What is Spring Boot’s HealthIndicator?........................................................................113

Copyright © 2025 by SkillForgePrep


116. How do you implement caching in Spring Boot?..........................................................114
117. How do you deploy Spring Boot to Docker?.................................................................114
118. What is Spring Boot’s @Async?...................................................................................115
119. How do you handle XML responses in Spring Boot?................................................... 115
120. Explain Spring Boot’s @RestControllerAdvice............................................................ 116
122 Intermediate and Advanced Spring Boot Interview Questions and Answers.............117
1. How does Spring Boot's auto-configuration prioritization work?...................................... 117
2. What is the Spring Boot bootstrap process in detail?...................................................... 117
3. How can you customize the Spring Boot banner?........................................................... 117
4. What is Spring Boot's condition evaluation delta report?.................................................117
5. What is a Spring Boot FailureAnalyzer and how would you implement a custom one?.. 118
6. How does Spring Boot handle circular dependencies?................................................... 118
7. What are the limitations of Spring Boot's auto-configuration?......................................... 118
8. What is the difference between @Bean and @Component annotations?.......................118
9. How does Spring Boot's property binding work with complex structures and collections?....
119
10. What is a Spring Boot BuilderCustomizer and how would you use one?...................... 119
11. How can you implement hierarchical property sources in Spring Boot?........................ 119
12. What are configuration trees in Spring Boot and how do they work?............................ 119
13. How do you create type-safe configuration properties with validation?.........................120
14. How does Spring Boot handle property encryption and sensitive data?....................... 120
15. What is the difference between @PropertySource and @ConfigurationProperties?.... 120
16. How can you implement dynamic configuration reloading in Spring Boot?................... 120
17. What are Spring Boot's configuration file hierarchies and their precedence?............... 121
18. How does Spring Boot handle YAML configuration internally?......................................121
19. What is ConfigurationCondition and how does it differ from Condition?........................121
20. How can you create environment-specific beans beyond profiles?...............................121
21. What is the difference between @WebMvcTest and @SpringBootTest?...................... 122
22. How do you test Spring Boot applications with a real database?.................................. 122
23. What is @DirtiesContext and when should you use it?................................................. 122
24. How do you test Spring Boot WebFlux applications?.................................................... 122
25. What are MockBean and SpyBean in Spring Boot tests?............................................. 123
26. How do you test Spring Boot Actuator endpoints?........................................................ 123
27. What is the role of @TestConfiguration in Spring Boot?................................................123
28. How would you test asynchronous behavior in Spring Boot?........................................123
29. What are slice tests in Spring Boot and how do they work?..........................................124
30. How can you test custom auto-configurations in Spring Boot?..................................... 124
31. How does Spring Boot's transaction management work behind the scenes?............... 124
32. What is the difference between JdbcTemplate and NamedParameterJdbcTemplate?..124
33. How can you configure multiple data sources in Spring Boot?......................................125
34. What is the Repository design pattern and how does Spring Data implement it?......... 125

Copyright © 2025 by SkillForgePrep


35. How do you handle database migrations in Spring Boot?............................................. 125
36. What is the difference between FetchType.EAGER and FetchType.LAZY in JPA?...... 125
37. How does Spring Boot handle connection pooling?...................................................... 126
38. What are projections in Spring Data and when would you use them?.......................... 126
39. How do you implement optimistic locking in Spring Boot applications?........................ 126
40. What are the benefits and drawbacks of using Spring Data's specifications and query
DSL?....................................................................................................................................126
41. How does Spring Security's filter chain work in a Spring Boot application?.................. 127
42. What is the difference between authentication and authorization in Spring Security?.. 127
43. How would you implement method-level security with custom expressions?................127
44. What is the SecurityContext and how is it managed across threads?...........................128
45. How would you implement a custom AuthenticationProvider?...................................... 128
46. What are the best practices for password storage in Spring Boot applications?...........128
47. How does Spring Security's CSRF protection work?.....................................................128
48. What are the security implications of using JWT with Spring Boot?..............................129
49. How would you implement OAuth2 resource server with JWT validation?....................129
50. How do you secure WebSocket connections in Spring Boot?....................................... 129
51. What is the role of Spring Cloud in a Spring Boot microservices architecture?.............130
52. How does service discovery work in Spring Boot microservices?................................. 130
53. What is the Circuit Breaker pattern and how is it implemented in Spring Boot?............130
54. How would you implement distributed tracing in Spring Boot microservices?...............130
55. What are the challenges of implementing transactions across microservices?.............131
56. How do you handle API versioning in Spring Boot microservices?............................... 131
57. What is the API Gateway pattern and how does Spring Cloud Gateway implement it?131
58. How do you implement centralized configuration management in Spring Boot
microservices?.....................................................................................................................132
59. How would you design event-driven microservices with Spring Boot?..........................132
60. What are the patterns for handling data consistency in microservices?........................132
61. How would you create a custom health indicator in Spring Boot Actuator?.................. 132
62. How can you expose custom metrics in Spring Boot applications?...............................133
63. What is the Spring Boot Admin project and how does it work?..................................... 134
64. How would you secure Spring Boot Actuator endpoints in a production environment? 134
65. What is the purpose of info and health contributors in Spring Boot Actuator?.............. 134
66. How can you collect and analyze metrics from Spring Boot applications?....................134
67. What is the difference between health indicators and readiness/liveness probes?.......135
68. How would you implement custom audit events in Spring Boot?.................................. 135
69. What monitoring patterns should you implement in a microservices architecture?....... 135
70. How do you implement log correlation in distributed Spring Boot applications?........... 136
71. How would you optimize the startup time of a Spring Boot application?....................... 136
72. What is the significance of bean scope selection for application performance?............136
73. How do you implement caching in Spring Boot applications?....................................... 137

Copyright © 2025 by SkillForgePrep


74. What strategies would you use to optimize database operations in Spring Boot?........ 137
75. How do you implement asynchronous operations in Spring Boot?............................... 137
76. How would you implement reactive programming in Spring Boot?............................... 137
77. How can you optimize resource utilization in a Spring Boot application?......................138
78. What are the best practices for implementing bulkhead patterns in Spring Boot?........ 138
79. How would you implement backpressure handling in Spring Boot applications?.......... 138
80. What is the role of connection pooling in Spring Boot and how would you tune it?.......139
81. What are the different ways to package and deploy Spring Boot applications?............ 139
82. How does Spring Boot support containerization and Docker deployment?...................139
83. What is the purpose of layered JARs in Spring Boot and how do they work?...............140
84. How would you implement graceful shutdown in Spring Boot applications?................. 140
85. How do you implement Zero Downtime Deployment with Spring Boot?....................... 140
86. What is the Spring Boot Buildpack support and how does it differ from Dockerfile-based
containerization?..................................................................................................................141
87. How would you implement feature flags in a Spring Boot application?......................... 141
88. How do you manage database schema migrations in a continuous deployment pipeline?.
141
89. What are the best practices for externalizing configuration in Spring Boot applications?...
141
90. How would you implement canary deployments with Spring Boot applications?.......... 142
91. How would you test Spring Boot applications with TestContainers?............................. 142
92. What is the difference between @MockBean and traditional mocking frameworks?.... 143
93. How do you implement contract testing in Spring Boot microservices?........................ 143
94. What is the role of test slices in Spring Boot and when would you use them?..............144
95. How would you test reactive components in Spring Boot?............................................144
96. What is Test-Driven Development (TDD) in the context of Spring Boot applications?.. 144
97. How would you implement load testing for Spring Boot applications?.......................... 145
98. What are the best practices for writing maintainable tests in Spring Boot?...................145
99. How would you test Spring Boot applications with multiple profiles?............................ 145
100. How do you implement security testing in Spring Boot applications?..........................145
101. What is the difference between JdbcTemplate, NamedParameterJdbcTemplate, and
SimpleJdbcInsert?............................................................................................................... 146
102. How does Spring Boot handle database initialization?................................................146
103. What is R2DBC and how does it integrate with Spring Boot?..................................... 146
104. How do you implement auditing in Spring Boot data applications?............................. 147
105. What are the performance implications of N+1 query problems and how do you solve
them?...................................................................................................................................147
106. How would you implement multi-tenancy in Spring Boot applications?.......................147
107. What is the difference between findById() and getOne() methods in Spring Data JPA?...
148
108. How do you implement database sharding with Spring Boot?.................................... 148
109. What is the Spring Boot AutoConfiguration for different databases?.......................... 148

Copyright © 2025 by SkillForgePrep


110. How do you implement read/write splitting in Spring Boot data access?.....................148
111. What is the difference between @RestController and @Controller?........................... 149
112. How does content negotiation work in Spring Boot?................................................... 149
113. What is WebClient and how does it differ from RestTemplate?................................... 149
114. How would you implement request/response logging in a Spring Boot application?...150
115. What is the difference between @RequestParam, @PathVariable, and
@RequestBody?..................................................................................................................151
116. How does Spring Boot handle CORS configuration?.................................................. 151
117. What is the concept of media types in RESTful applications and how does Spring Boot
handle them?....................................................................................................................... 152
118. How would you implement API versioning in Spring Boot?......................................... 152
119. What is Spring HATEOAS and how would you implement it?......................................152
120. How do you implement request rate limiting in Spring Boot applications?.................. 153
121. How would you implement custom authentication filters in Spring Security?.............. 153
122. How do you implement defense against common security vulnerabilities in Spring
Boot?................................................................................................................................... 154

Copyright © 2025 by SkillForgePrep


120 Most Important Spring Boot Interview Questions
and Answers for Beginners
Spring Boot has revolutionized Java application development by simplifying configuration and
deployment processes. As one of the most sought-after skills in the Java ecosystem, preparing
for Spring Boot interviews requires understanding both fundamental concepts and practical
applications. This comprehensive guide provides 200 beginner-level Spring Boot interview
questions with expert answers to help you ace your upcoming interview.

1. What is Spring Boot?


Spring Boot is a project built on top of the Spring Framework that provides an easier and faster
way to set up, configure, and run both simple and web-based applications. It eliminates the
need for defining boilerplate configurations and provides production-ready applications with
minimal setup23.

2. Why do we need Spring Boot?


Spring Boot reduces development time and increases productivity by:

●​ Providing auto-configuration of Spring components​

●​ Eliminating boilerplate code and XML configuration​

●​ Offering embedded servers for easy deployment​

●​ Including production-ready features like metrics, health checks, and monitoring​

●​ Simplifying dependency management through starter POMs235​

3. What are the main advantages of using Spring Boot?


The main advantages include:

●​ Simplified configuration with auto-configuration​

●​ Standalone applications with embedded servers​

●​ Production-ready features through Spring Boot Actuator​

Copyright © 2025 by SkillForgePrep


●​ Quick development with Spring Initializer​

●​ Reduced development time and increased productivity​

●​ No XML configuration required​

●​ Easy dependency management with starter dependencies235​

4. What are the key features of Spring Boot?


Key features include:

●​ Auto-configuration​

●​ Starter dependencies​

●​ Embedded server support (Tomcat, Jetty, Undertow)​

●​ Spring Boot Actuator for application insights​

●​ Spring Boot CLI for rapid prototyping​

●​ Externalized configuration​

●​ Spring Initializer for project setup234​

5. What is the difference between Spring and Spring


Boot?
Spring is a comprehensive framework for Java development, while Spring Boot is a module of
Spring that simplifies the process:

●​ Spring requires manual configuration while Spring Boot provides auto-configuration​

●​ Spring projects need separate server deployment, whereas Spring Boot includes
embedded servers​

●​ Spring is more complex, while Spring Boot reduces complexity​

Copyright © 2025 by SkillForgePrep


●​ Spring takes an unopinionated view, whereas Spring Boot adopts an opinionated
approach to configuration​

●​ Spring Boot aims at rapid application development25​

6. What are Spring Boot components?


Spring Boot consists of the following components:

●​ Spring Boot Starters for dependency management​

●​ Spring Boot AutoConfigurator for auto-configuration​

●​ Spring Boot Actuator for monitoring and management​

●​ Embedded HTTP servers (Tomcat, Jetty, etc.)​

●​ Spring Boot CLI3​

7. What is a Spring Boot Starter?


Spring Boot Starters are JAR files that provide a way to include related dependencies with a
single dependency entry in your build file. They simplify build configuration and provide a
cohesive set of dependencies that work well together. For example, 'spring-boot-starter-web'
includes all dependencies needed for web development23.

8. How does auto-configuration work in Spring Boot?


Auto-configuration automatically configures a Spring application based on the dependencies
present in the classpath. For example, if JDBC is in the classpath, Spring Boot automatically
configures a DataSource. It uses conditional annotations like @ConditionalOnClass and
@ConditionalOnMissingBean to determine when to apply specific configurations2.

9. What is Spring Boot Actuator?


Spring Boot Actuator provides production-ready features to help monitor and manage Spring
Boot applications. It offers several endpoints to expose operational information about the
running application, such as health, metrics, info, dump, env, etc. These are available through
HTTP or JMX35.

Copyright © 2025 by SkillForgePrep


10. How can you create a Spring Boot application?
You can create a Spring Boot application in multiple ways:

●​ Using Spring Initializer (start.spring.io)​

●​ Using Spring Boot CLI​

●​ Using an IDE with Spring Boot support like Spring Tool Suite or IntelliJ IDEA​

●​ Using Maven or Gradle directly with appropriate dependencies25​

11. What is Spring Boot Initializer?


Spring Boot Initializer is a web tool that helps bootstrap a Spring Boot application with minimal
configuration. It provides a user interface to select project metadata, dependencies, packaging
type, Java version, and other options. It generates a project structure with appropriate build files
ready to be imported into an IDE3.

12. What is the role of @SpringBootApplication


annotation?
The @SpringBootApplication annotation is a convenience annotation that combines three
annotations:

●​ @Configuration: Tags the class as a source of bean definitions​

●​ @EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath


settings​

●​ @ComponentScan: Tells Spring to look for components in the current package and its
sub-packages​

This single annotation simplifies the setup process by replacing multiple annotations2.

13. How does Spring Boot handle dependency


management?
Spring Boot handles dependency management through:

Copyright © 2025 by SkillForgePrep


●​ Starter dependencies that group related dependencies​

●​ Built-in dependency version management (inherited from the spring-boot-starter-parent)​

●​ Transitive dependency resolution that automatically includes required dependencies​

●​ The ability to override default versions when needed23​

14. What happens when a Spring Boot application is "Run


as Java Application"?
When a Spring Boot application is run as a Java application, the following happens:

1.​ The main method is executed, which calls SpringApplication.run()​

2.​ Spring Boot auto-configuration mechanism detects dependencies​

3.​ The embedded server is started (Tomcat by default)​

4.​ Spring beans are initialized​

5.​ Any CommandLineRunner beans are executed​

6.​ The application becomes ready to serve requests2​

15. What is an embedded server in Spring Boot?


An embedded server in Spring Boot is a server (like Tomcat, Jetty, or Undertow) that is
packaged within the application JAR file. This eliminates the need to deploy the application to
an external server, making it self-contained. By default, Spring Boot uses Tomcat as its
embedded server23.

16. How can you change the default port of the embedded
server?
You can change the default port (8080) of the embedded server by:

●​ Setting the server.port property in application.properties or application.yml​

Copyright © 2025 by SkillForgePrep


●​ Using a command-line argument: --server.port=8081​

●​ Programmatically by setting the property with System properties​

●​ Using the ServerProperties class in your configuration​

Example in application.properties:

text
server.port=9090

17. What is Spring Boot CLI?


Spring Boot CLI (Command-Line Interface) is a tool that allows you to quickly prototype Spring
applications using Groovy scripts. It provides features like auto-configuration, dependency
resolution, and Spring Boot capabilities without requiring a full project setup. It simplifies the
development process for small applications and proofs of concept3.

18. What are the possible sources of external


configuration in Spring Boot?
Spring Boot allows configuration from various sources (in order of precedence):

●​ Command-line arguments​

●​ JNDI attributes​

●​ Java System properties​

●​ OS environment variables​

●​ Profile-specific properties (application-{profile}.properties)​

●​ Application properties (application.properties or application.yml)​

●​ @PropertySource annotations​

●​ Default properties2​

Copyright © 2025 by SkillForgePrep


19. What is the difference between an embedded
container and a WAR file?
An embedded container packages the server runtime within the application, allowing it to run as
a standalone JAR file. A WAR (Web Application Archive) file is a traditional deployment format
that requires an external application server. Spring Boot supports both approaches, but the
embedded container approach is simpler and aligns with microservice architecture principles.

20. How do you exclude auto-configuration classes in


Spring Boot?
You can exclude auto-configuration classes using:

●​ The exclude attribute of @EnableAutoConfiguration annotation:​



java

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

●​
●​ Or using the excludeName attribute for string class names:​

java

@EnableAutoConfiguration(excludeName={"org.springframework.boot.autoco
nfigure.jdbc.DataSourceAutoConfiguration"})

●​
●​ Or in application.properties:​

text

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jd
bc.DataSourceAutoConfiguration

●​

21. What is Spring Boot DevTools?


Spring Boot DevTools is a set of tools that improves the developer experience. Features
include:

Copyright © 2025 by SkillForgePrep


●​ Automatic application restart when files change​

●​ LiveReload support to automatically refresh the browser​

●​ Remote debugging support​

●​ Property defaults oriented towards development​

●​ Conditional disabling of certain features in production​

DevTools is automatically disabled when running a packaged application.

22. How do you access command-line properties in


Spring Boot?
Command-line properties can be accessed in several ways:

●​ Using the @Value annotation to inject specific properties​

●​ Using the Environment object to look up properties​

●​ Using @ConfigurationProperties to bind properties to a POJO​

●​ Using CommandLinePropertySource for direct access​

Example:

java
@Component
public class MyBean {
@Value("${name}")
private String name;
}

23. What is the Spring Boot Actuator health endpoint?


The health endpoint (/actuator/health) provides basic health information about the application. It
shows the status of the application (UP, DOWN, OUT_OF_SERVICE, UNKNOWN) and can

Copyright © 2025 by SkillForgePrep


include details about specific components like database connections, disk space, etc. It's useful
for monitoring and health check systems to determine if the application is functioning properly3.

24. How do you secure Spring Boot Actuator endpoints?


You can secure Actuator endpoints by:

●​ Including the Spring Security starter dependency​

●​ Configuring authentication and authorization rules​

●​ Using properties to control endpoint exposure:​



text

management.endpoints.web.exposure.include=health,info
management.endpoints.web.exposure.exclude=env,beans

●​
●​ Implementing custom security configurations for specific endpoints​

●​ Changing the base path for actuator endpoints with


management.endpoints.web.base-path​

25. What is a multi-module project in Spring Boot?


A multi-module project in Spring Boot divides a large application into smaller, modular
components (Maven/Gradle modules) that can be developed, tested, and maintained
independently. Each module has its own build file and can depend on other modules. This
approach promotes separation of concerns, code reuse, and better organization of complex
applications.

26. What are profiles in Spring Boot?


Profiles in Spring Boot provide a way to segregate parts of application configuration and make it
available only in certain environments. Profiles allow you to have environment-specific
properties and beans. You can activate profiles using:

●​ The spring.profiles.active property​

Copyright © 2025 by SkillForgePrep


●​ JVM system properties​

●​ Environment variables​

●​ Programmatically through the SpringApplication API​

27. How do you configure logging in Spring Boot?


Spring Boot uses Commons Logging for internal logging and delegates to implementation
libraries like Logback by default. You can configure logging using:

●​ application.properties/application.yml for simple configuration:​



text

logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
logging.file.name=myapp.log

●​
●​ A logback-spring.xml file for more complex configurations​

●​ Custom LoggingSystem implementation for advanced scenarios​

28. What is a condition in Spring Boot


auto-configuration?
Conditions in Spring Boot auto-configuration determine when a specific configuration should be
applied. Spring Boot provides several condition annotations:

●​ @ConditionalOnClass: Applies when specified classes are on the classpath​

●​ @ConditionalOnMissingClass: Applies when specified classes are not on the classpath​

●​ @ConditionalOnBean: Applies when specified beans exist​

●​ @ConditionalOnMissingBean: Applies when specified beans don't exist​

●​ @ConditionalOnProperty: Applies when a specific property has a specified value​

Copyright © 2025 by SkillForgePrep


●​ @ConditionalOnResource: Applies when a specific resource is available​

●​ @ConditionalOnWebApplication: Applies when it's a web application​

29. What is Spring Boot's property binding?


Spring Boot property binding is the mechanism to map externalized properties (from sources
like application.properties) to Java beans. The @ConfigurationProperties annotation enables
this binding:

java
@Configuration
@ConfigurationProperties(prefix = "mail")
public class MailProperties {
private String host;
private int port;
// getters and setters
}

This binds properties like mail.host and mail.port to the corresponding fields.

30. How can you implement custom health indicators in


Spring Boot?
You can create custom health indicators by implementing the HealthIndicator interface or
extending AbstractHealthIndicator:

java
@Component
public class CustomHealthIndicator extends AbstractHealthIndicator {
@Override
protected void doHealthCheck(Health.Builder builder) throws
Exception {
// Perform health check logic
if (/* everything is healthy */) {
builder.up().withDetail("details", "Everything is working
fine");
} else {

Copyright © 2025 by SkillForgePrep


builder.down().withDetail("details", "Something went
wrong");
}
}
}

This will be automatically integrated into the health endpoint.

31. What is Spring Boot's relaxed binding?


Relaxed binding allows various formats of property names to be mapped to the same field. For
example, with @ConfigurationProperties, the following property names all map to the
emailAddress field:

●​ mail.email-address (kebab case, recommended for .properties files)​

●​ mail.emailAddress (camel case)​

●​ mail.email_address (underscore notation)​

●​ MAIL_EMAIL_ADDRESS (upper case, recommended for environment variables)​

This provides flexibility when configuring an application from different sources.

32. What is Spring Data JPA in Spring Boot?


Spring Data JPA is a part of the Spring Data family that makes it easy to implement JPA-based
repositories. With Spring Boot, you can quickly set up Spring Data JPA with minimal
configuration using the spring-boot-starter-data-jpa dependency. It provides repository interfaces
that simplify database operations and reduce boilerplate code.

33. How do you handle exceptions in Spring Boot REST


applications?
In Spring Boot REST applications, you can handle exceptions using:

●​ @ExceptionHandler annotation at the controller level​

●​ @ControllerAdvice or @RestControllerAdvice for global exception handling​

Copyright © 2025 by SkillForgePrep


●​ ResponseEntityExceptionHandler for common HTTP exceptions​

●​ Custom error responses with appropriate HTTP status codes​

Example:

java
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse>
handleResourceNotFound(ResourceNotFoundException ex) {
ErrorResponse error = new ErrorResponse("NOT_FOUND",
ex.getMessage());
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
}

34. What is the @SpringBootTest annotation used for?


The @SpringBootTest annotation is used for integration testing in Spring Boot applications. It
creates an ApplicationContext containing all the beans in your application, simulating the
complete runtime environment. You can configure it to use a specific configuration, web
environment, or server port:

java
@SpringBootTest(webEnvironment =
SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyIntegrationTest {
// test methods
}

35. How do you test a controller in Spring Boot?


You can test a controller in Spring Boot using:

Copyright © 2025 by SkillForgePrep


●​ MockMvc for testing the MVC layer without starting a server:​

java

@WebMvcTest(MyController.class)
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;

@Test
public void testEndpoint() throws Exception {
mockMvc.perform(get("/api/items"))
.andExpect(status().isOk())

.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
}

●​
●​ TestRestTemplate or WebTestClient for full integration tests with a running server​

36. What is the CommandLineRunner interface in Spring


Boot?
CommandLineRunner is an interface used to run specific code when a Spring Boot application
starts. It's often used for initializing data or executing startup tasks. You implement the run()
method which is called after the application context has been loaded:

java
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// Code to run on startup
System.out.println("Application started with arguments: " +
Arrays.toString(args));
}
}

Copyright © 2025 by SkillForgePrep


37. What is the difference between @Controller and
@RestController?
●​ @Controller is a specialization of @Component used to define a controller in Spring
MVC. Methods return view names by default, which are resolved to view templates.​

●​ @RestController combines @Controller and @ResponseBody, indicating that the return


values of methods should be directly serialized to the HTTP response body (typically as
JSON). It's designed for building RESTful web services.​

38. How do you configure CORS in Spring Boot?


You can configure Cross-Origin Resource Sharing (CORS) in Spring Boot in several ways:

●​ Controller-level with @CrossOrigin annotation:​



java

@CrossOrigin(origins = "http://example.com")
@RestController
public class MyController { }

●​
●​ Global configuration with WebMvcConfigurer:​

java

@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://example.com")
.allowedMethods("GET", "POST");
}
}

●​

Copyright © 2025 by SkillForgePrep


●​ Using properties in application.properties:​

text

spring.web.cors.allowed-origins=http://example.com
spring.web.cors.allowed-methods=GET,POST

●​

39. What is Spring Boot's support for caching?


Spring Boot provides auto-configuration for various cache providers through the
spring-boot-starter-cache dependency. It simplifies caching configuration for:

●​ JCache (JSR-107)​

●​ EhCache​

●​ Hazelcast​

●​ Infinispan​

●​ Couchbase​

●​ Redis​

●​ Caffeine​

You can enable caching with @EnableCaching and use annotations like @Cacheable,
@CachePut, and @CacheEvict on methods.

40. How do you implement pagination in Spring Boot


REST APIs?
Spring Boot makes pagination easy with Spring Data repositories:

java
@GetMapping("/users")
public Page<User> getUsers(Pageable pageable) {
return userRepository.findAll(pageable);
}

Copyright © 2025 by SkillForgePrep


Clients can request specific pages with parameters like:

text
/users?page=0&size=10&sort=lastName,desc

For REST APIs, you can also return a PagedResources/PagedModel object using Spring
HATEOAS to include navigation links.

41. What are Spring Boot's auto-configuration report


options?
Spring Boot can provide auto-configuration reports showing which auto-configurations were
applied or not applied to your application. You can enable this by:

●​ Setting debug=true in application.properties​

●​ Using --debug when running the application from the command line​

●​ Using the DEBUG log level for org.springframework.boot.autoconfigure​

The report shows positive matches (configurations that were applied) and negative matches
(configurations that were not applied, with reasons).

42. How do you implement custom Banner in Spring


Boot?
You can implement a custom startup banner by:

●​ Creating a banner.txt file in the resources directory with your ASCII art​

●​ Setting a different file with spring.banner.location property​

●​ Using an image with spring.banner.image.location​

●​ Programmatically using the SpringApplication.setBanner() method​

●​ Disabling the banner with spring.main.banner-mode=off​

Copyright © 2025 by SkillForgePrep


43. What is Spring Boot Admin?
Spring Boot Admin is a web application that manages and monitors Spring Boot applications. It
provides a UI for Spring Boot Actuator endpoints, showing health status, metrics, environment
details, logging configuration, threads, and more. It consists of:

●​ Admin Server: A central application that collects and displays information​

●​ Client applications: Register with the admin server using Spring Boot Admin Client​

44. How do you connect Spring Boot to a database?


To connect Spring Boot to a database:

1.​ Include the appropriate starter dependency (e.g., spring-boot-starter-data-jpa)​

2.​ Add the database driver dependency (e.g., mysql-connector-java)​

3.​ Configure database connection properties in application.properties:​

text
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update

Spring Boot will auto-configure a DataSource, EntityManagerFactory, and TransactionManager.

45. What is Spring Boot's support for WebSockets?


Spring Boot provides support for WebSockets through the spring-boot-starter-websocket
dependency. It auto-configures Spring's WebSocket support when detected on the classpath.
You can:

●​ Create WebSocket handlers​

●​ Configure WebSocket endpoints with @ServerEndpoint​

●​ Use STOMP messaging with @MessageMapping​

Copyright © 2025 by SkillForgePrep


●​ Implement WebSocket security​

●​ Build interactive web applications with real-time communication​

46. How do you handle file uploads in Spring Boot?


To handle file uploads in Spring Boot:

1.​ Ensure MultipartResolver is configured (auto-configured by default)​

2.​ Set properties for upload limits:​

text
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

3.​ Create a controller method:​

java
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile
file) {
try {
// Store or process the file
String originalFilename = file.getOriginalFilename();
byte[] bytes = file.getBytes();
// Save the file to disk, database, or cloud storage
return "File uploaded successfully: " + originalFilename;
} catch (Exception e) {
return "Failed to upload file: " + e.getMessage();
}
}

47. What is Spring Boot's support for Reactive


programming?
Copyright © 2025 by SkillForgePrep
Spring Boot provides support for reactive programming through the spring-boot-starter-webflux
dependency. This enables:

●​ Non-blocking, reactive web applications with Spring WebFlux​

●​ Working with reactive streams using Project Reactor (Flux and Mono types)​

●​ Reactive data access with Spring Data R2DBC or reactive MongoDB​

●​ Integration with reactive systems like RSocket​

●​ Server-sent events and WebSocket support in a reactive style​

48. How do you implement internationalization (i18n) in


Spring Boot?
To implement internationalization in Spring Boot:

1.​ Configure a MessageSource in your application:​

java
@Configuration
public class I18nConfig {
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new
ResourceBundleMessageSource();
messageSource.setBasenames("messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
}

2.​ Create properties files for each locale:​

○​ messages.properties (default)​

○​ messages_fr.properties (French)​

Copyright © 2025 by SkillForgePrep


○​ messages_es.properties (Spanish)​

3.​ Access messages in code or templates:​

java
@Autowired
private MessageSource messageSource;

public String getWelcomeMessage(Locale locale) {


return messageSource.getMessage("welcome.message", null, locale);
}

49. What is Spring Boot's Validation support?


Spring Boot provides validation support through the spring-boot-starter-validation dependency,
which includes Hibernate Validator (the reference implementation of Bean Validation). You can:

●​ Validate request bodies with @Valid:​

java
@PostMapping("/users")
public ResponseEntity<User> createUser(@Valid @RequestBody User user)
{
// user is validated based on annotations like @NotNull, @Size, etc.
return ResponseEntity.ok(userService.save(user));
}

●​ Add validation annotations to model classes:​

java
public class User {
@NotBlank(message = "Name is required")
private String name;

@Email(message = "Email should be valid")


private String email;

Copyright © 2025 by SkillForgePrep


// other fields, getters, setters
}

●​ Create custom validators for complex validations​

50. How do you implement authentication and


authorization in Spring Boot?
To implement authentication and authorization:

1.​ Add the spring-boot-starter-security dependency​

2.​ Configure security rules:​

java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/public/**").permitAll()
.antMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws
Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")

Copyright © 2025 by SkillForgePrep


.and()
.withUser("admin").password("{noop}admin").roles("USER",
"ADMIN");
}
}

3.​ Use @PreAuthorize and other security annotations for method-level security​

51. What is the significance of Spring Boot's


application.properties file?
The application.properties file is a key configuration file in Spring Boot that allows you to
externalize configuration settings. It enables you to:

●​ Configure application behavior without code changes​

●​ Override defaults provided by auto-configuration​

●​ Define environment-specific settings​

●​ Configure built-in features like logging, server settings, database connections​

●​ Define custom application properties that can be injected into beans​

52. How do you define custom properties in Spring Boot?


To define and use custom properties:

1.​ Define properties in application.properties:​

text
app.name=My Application
app.description=A Spring Boot application
app.max-connections=100

2.​ Create a configuration class to bind these properties:​

Copyright © 2025 by SkillForgePrep


java
@Configuration
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private String description;
private int maxConnections;

// getters and setters


}

3.​ Use the properties in your code:​

java
@Service
public class MyService {
private final AppProperties appProperties;

public MyService(AppProperties appProperties) {


this.appProperties = appProperties;
}

public void doSomething() {


System.out.println("Using " + appProperties.getName());
}
}

53. What is Spring Boot's handling of static resources?


Spring Boot automatically serves static resources from specific locations in the classpath:

●​ /static​

●​ /public​

●​ /resources​

Copyright © 2025 by SkillForgePrep


●​ /META-INF/resources​

For example, a file at src/main/resources/static/css/style.css would be served at


http://server:port/css/style.css. You can customize this behavior with properties:

text
spring.web.resources.static-locations=classpath:/custom/,classpath:/st
atic/
spring.mvc.static-path-pattern=/resources/**

54. How do you implement scheduled tasks in Spring


Boot?
To implement scheduled tasks:

1.​ Enable scheduling with @EnableScheduling on a configuration class​

2.​ Create methods with @Scheduled annotation:​

java
@Component
public class ScheduledTasks {

@Scheduled(fixedRate = 5000) // Run every 5 seconds


public void reportCurrentTime() {
System.out.println("Current time: " + new Date());
}

@Scheduled(cron = "0 0 12 * * ?") // Run at 12 PM every day


public void noonTask() {
System.out.println("Noon task executed");
}
}

You can schedule tasks with fixed rates, fixed delays, or using cron expressions.

Copyright © 2025 by SkillForgePrep


55. How do you implement asynchronous processing in
Spring Boot?
To implement asynchronous processing:

1.​ Enable asynchronous processing with @EnableAsync on a configuration class​

2.​ Create methods with @Async annotation:​

java
@Service
public class AsyncService {

@Async
public CompletableFuture<String> asyncMethod() {
// Simulating long processing
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return CompletableFuture.completedFuture("Async result");
}
}

3.​ Optionally configure a custom task executor:​

java
@Configuration
@EnableAsync
public class AsyncConfig {

@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new
ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);

Copyright © 2025 by SkillForgePrep


executor.setMaxPoolSize(10);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("Async-");
executor.initialize();
return executor;
}
}

56. What is Spring Boot Starters POM?


Spring Boot Starters POM (Project Object Model) is a set of convenient dependency descriptors
that you can include in your application. Each starter contains a collection of dependencies that
are required for a specific functionality, reducing the need to search for and configure individual
dependencies. Examples include:

●​ spring-boot-starter-web: For building web applications including RESTful applications​

●​ spring-boot-starter-data-jpa: For using Spring Data JPA with Hibernate​

●​ spring-boot-starter-security: For Spring Security​

●​ spring-boot-starter-test: For testing Spring Boot applications2​

57. How do you deploy a Spring Boot application?


You can deploy a Spring Boot application in several ways:

●​ As a standalone JAR with embedded server:​



text

java -jar myapplication.jar

●​
●​ As a traditional WAR file in an external application server:​

java

public class ServletInitializer extends SpringBootServletInitializer {


@Override

Copyright © 2025 by SkillForgePrep


protected SpringApplicationBuilder
configure(SpringApplicationBuilder application) {
return application.sources(MyApplication.class);
}
}

●​
●​ Using Docker containerization​

●​ Using cloud platforms like AWS, Azure, Google Cloud Platform, or Heroku​

●​ Using Kubernetes for container orchestration​

58. What is Spring Boot's support for testing?


Spring Boot provides extensive testing support with the spring-boot-starter-test dependency,
which includes:

●​ JUnit (testing framework)​

●​ Spring Test & Spring Boot Test (utilities and integration support)​

●​ AssertJ (assertions library)​

●​ Hamcrest (matcher objects)​

●​ Mockito (mocking framework)​

●​ JSONassert (JSON assertions)​

●​ JsonPath (XPath for JSON)​

You can use annotations like @SpringBootTest for full integration tests and @WebMvcTest,
@DataJpaTest for more focused tests.

59. What is Spring Boot Actuator info endpoint?


The info endpoint (/actuator/info) provides custom information about the Spring Boot application.
By default, it's empty, but you can add information through:

Copyright © 2025 by SkillForgePrep


●​ application.properties/application.yml:​

text

info.app.name=My App
info.app.description=My Spring Boot Application
info.app.version=1.0.0

●​
●​ InfoContributor beans:​

java

@Component
public class CustomInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("database", Map.of(
"type", "mysql",
"status", "connected"
));
}
}

●​

The info endpoint is useful for displaying application metadata3.

60. How do you use profiles for environment-specific


configuration?
You can use profiles for environment-specific configuration by:

1.​ Creating profile-specific properties files:​

○​ application-dev.properties​

○​ application-prod.properties​

○​ application-test.properties​

Copyright © 2025 by SkillForgePrep


2.​ Setting active profiles:​

○​ In application.properties: spring.profiles.active=dev​

○​ As a command-line argument: --spring.profiles.active=dev​

○​ As an environment variable: SPRING_PROFILES_ACTIVE=dev​

3.​ Using profile-specific beans:​



java

@Configuration
@Profile("dev")
public class DevConfig {
// dev-specific beans
}

@Configuration
@Profile("prod")
public class ProdConfig {
// prod-specific beans
}

4.​

61. What is the difference between JPA and Hibernate in


Spring Boot context?
In the Spring Boot context:

●​ JPA (Java Persistence API) is a specification that defines a set of interfaces for ORM in
Java applications.​

●​ Hibernate is an implementation of the JPA specification.​

Spring Boot uses Hibernate as the default JPA implementation when you include
spring-boot-starter-data-jpa. You work with JPA interfaces like EntityManager and Repository,
but behind the scenes, Hibernate handles the actual database operations2.

Copyright © 2025 by SkillForgePrep


62. How do you handle database migrations in Spring
Boot?
Spring Boot supports database migration tools:

1.​ Flyway:​

○​ Add the dependency: spring-boot-starter-flyway​

○​ Create migration scripts in src/main/resources/db/migration with naming


convention V1__init.sql, V2__add_columns.sql, etc.​

○​ Flyway automatically applies migrations on startup​

2.​ Liquibase:​

○​ Add the dependency: spring-boot-starter-liquibase​

○​ Create changelog files in src/main/resources/db/changelog​

○​ Configure in application.properties:​

text

spring.liquibase.change-log=classpath:db/changelog/db.changelog-master
.xml

○​

These tools help version control database changes and ensure consistent schema across
environments.

63. What is Spring Data REST in Spring Boot?


Spring Data REST is part of the Spring Data project that automatically exports Spring Data
repositories as RESTful endpoints. With Spring Boot:

1.​ Add the dependency: spring-boot-starter-data-rest​

2.​ Create JPA repositories:​



java

Copyright © 2025 by SkillForgePrep


public interface UserRepository extends JpaRepository<User, Long> {
}

3.​
4.​ Spring Data REST automatically creates endpoints for CRUD operations:​

○​ GET /users - List all users​

○​ GET /users/{id} - Get a specific user​

○​ POST /users - Create a new user​

○​ PUT /users/{id} - Update a user​

○​ DELETE /users/{id} - Delete a user​

You can customize the behavior with annotations like @RepositoryRestResource,


@RestResource, etc.

64. How do you secure REST APIs in Spring Boot?


To secure REST APIs in Spring Boot:

1.​ Add the dependency: spring-boot-starter-security​

2.​ Configure security for REST endpoints:​



java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // Often disabled for REST APIs
.authorizeRequests()
.antMatchers("/api/public/**").permitAll()
.antMatchers("/api/**").authenticated()
.and()

Copyright © 2025 by SkillForgePrep


.httpBasic() // Basic authentication
.and()
.sessionManagement()

.sessionCreationPolicy(SessionCreationPolicy.STATELESS); // RESTful
APIs are typically stateless
}
}

3.​
4.​ For token-based authentication, integrate JWT or OAuth2:​

○​ Add appropriate dependencies​

○​ Configure token generation, validation, and storage​

○​ Create security filters​

65. What is the purpose of @RestControllerAdvice in


Spring Boot?
@RestControllerAdvice is a specialized version of @ControllerAdvice combined with
@ResponseBody. It's used for global exception handling in Spring MVC applications,
particularly for REST APIs. It allows you to:

●​ Handle exceptions across all @RestController classes​

●​ Return custom error responses​

●​ Apply consistent exception handling logic throughout the application​

Example:

java
@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)

Copyright © 2025 by SkillForgePrep


public ErrorResponse
handleResourceNotFound(ResourceNotFoundException ex) {
return new ErrorResponse("NOT_FOUND", ex.getMessage());
}

@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse handleGenericException(Exception ex) {
return new ErrorResponse("SERVER_ERROR", "An unexpected error
occurred");
}
}

66. What is Spring Boot Starter Parent?


Spring Boot Starter Parent is a special starter that provides default configurations for Spring
Boot applications. It:

●​ Defines the default Java version​

●​ Sets the default encoding (UTF-8)​

●​ Provides dependency management for Spring Boot dependencies​

●​ Configures Maven plugins with sensible defaults​

●​ Establishes a standard project structure​

By inheriting from spring-boot-starter-parent in your pom.xml, you inherit these defaults:

xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/>
</parent>

Copyright © 2025 by SkillForgePrep


67. How do you implement transaction management in
Spring Boot?
Transaction management in Spring Boot is simplified through:

1.​ Auto-configuration: When you include spring-boot-starter-data-jpa, transaction


management is auto-configured​

2.​ @Transactional annotation:​



java

@Service
public class UserService {
private final UserRepository userRepository;

public UserService(UserRepository userRepository) {


this.userRepository = userRepository;
}

@Transactional
public User createUser(User user) {
// Perform operations within a transaction
return userRepository.save(user);
}
}

3.​
4.​ Configuring transaction attributes:​

java

@Transactional(readOnly = true)
public List<User> getAllUsers() {
return userRepository.findAll();
}

@Transactional(propagation = Propagation.REQUIRED, isolation =


Isolation.READ_COMMITTED)
public void complexOperation() {

Copyright © 2025 by SkillForgePrep


// Transaction with specific attributes
}

5.​

68. What is Spring Boot's support for NoSQL databases?


Spring Boot provides support for various NoSQL databases through starters and
auto-configuration:

●​ MongoDB: spring-boot-starter-data-mongodb​

●​ Redis: spring-boot-starter-data-redis​

●​ Cassandra: spring-boot-starter-data-cassandra​

●​ Elasticsearch: spring-boot-starter-data-elasticsearch​

●​ Neo4j: spring-boot-starter-data-neo4j​

For each, Spring Boot auto-configures the necessary components and provides repository
support through Spring Data. Example for MongoDB:

java
@Document
public class Product {
@Id
private String id;
private String name;
private double price;
// getters and setters
}

public interface ProductRepository extends MongoRepository<Product,


String> {
List<Product> findByPriceGreaterThan(double price);
}

Copyright © 2025 by SkillForgePrep


69. How do you disable a specific auto-configuration in
Spring Boot?
You can disable specific auto-configurations in several ways:

1.​ Using the @EnableAutoConfiguration annotation with the exclude attribute:​



java

@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

2.​
3.​ Using the excludeName attribute for string class names:​

java

@SpringBootApplication(excludeName={"org.springframework.boot.autoconf
igure.jdbc.DataSourceAutoConfiguration"})
public class Application {
// ...
}

4.​
5.​ Using configuration properties:​

text

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jd
bc.DataSourceAutoConfiguration

6.​

70. What is Spring Boot's support for messaging


systems?

Copyright © 2025 by SkillForgePrep


Spring Boot provides support for various messaging systems:

1.​ JMS (Java Message Service):​

○​ Dependency: spring-boot-starter-activemq (ActiveMQ) or


spring-boot-starter-artemis (Artemis)​

○​ Auto-configures JmsTemplate and ConnectionFactory​

2.​ java

@Service
public class MessageService {
private final JmsTemplate jmsTemplate;

public MessageService(JmsTemplate jmsTemplate) {


this.jmsTemplate = jmsTemplate;
}

public void sendMessage(String message) {


jmsTemplate.convertAndSend("myQueue", message);
}
}

3.​
4.​ AMQP (Advanced Message Queuing Protocol):​

○​ Dependency: spring-boot-starter-amqp (RabbitMQ)​

○​ Auto-configures RabbitTemplate and ConnectionFactory​

5.​ Kafka:​

○​ Dependency: spring-boot-starter-kafka​

○​ Auto-configures KafkaTemplate and Kafka listeners​

Each integrates with Spring's messaging abstractions for sending and receiving messages.

Copyright © 2025 by SkillForgePrep


71. How do you implement custom auto-configuration in
Spring Boot?
To create custom auto-configuration:

1.​ Create a configuration class:​



java

@Configuration
@ConditionalOnClass(MyService.class)
@ConditionalOnMissingBean(MyService.class)
public class MyAutoConfiguration {

@Bean
@ConditionalOnProperty(prefix = "my.service", name = "enabled",
havingValue = "true", matchIfMissing = true)
public MyService myService() {
return new MyServiceImpl();
}
}

2.​
3.​ Create a file named META-INF/spring.factories in your resources:​

text

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.MyAutoConfiguration

4.​
5.​ Apply conditions to control when your configuration is applied​

6.​ Document your configuration properties:​



java

@ConfigurationProperties(prefix = "my.service")
public class MyServiceProperties {
private boolean enabled = true;
// getters and setters

Copyright © 2025 by SkillForgePrep


}

7.​

72. What is Spring Boot's support for WebClient?


WebClient is a non-blocking, reactive HTTP client introduced in Spring 5, and Spring Boot
provides auto-configuration for it:

1.​ Add the dependency: spring-boot-starter-webflux​

2.​ Use WebClient in your code:​



java

@Service
public class ApiService {
private final WebClient webClient;

public ApiService(WebClient.Builder webClientBuilder) {


this.webClient = webClientBuilder
.baseUrl("https://api.example.com")
.defaultHeader(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON_VALUE)
.build();
}

public Mono<User> getUser(String userId) {


return webClient.get()
.uri("/users/{id}", userId)
.retrieve()
.bodyToMono(User.class);
}
}

3.​
4.​ Customize WebClient with a bean:​

java

@Bean

Copyright © 2025 by SkillForgePrep


public WebClient.Builder webClientBuilder() {
return WebClient.builder()
.filter(logRequest());
}

5.​

73. How do you implement unit testing in Spring Boot?


Unit testing in Spring Boot typically focuses on testing components in isolation:

1.​ Use the starter: spring-boot-starter-test​

2.​ Create unit tests for services, controllers, etc.:​



java

@ExtendWith(MockitoExtension.class)
public class UserServiceTest {

@Mock
private UserRepository userRepository;

@InjectMocks
private UserService userService;

@Test
public void shouldReturnUserWhenFound() {
// Arrange
User expectedUser = new User("1", "John");

when(userRepository.findById("1")).thenReturn(Optional.of(expectedUser
));

// Act
User actualUser = userService.getUserById("1");

// Assert
assertEquals(expectedUser, actualUser);
verify(userRepository).findById("1");

Copyright © 2025 by SkillForgePrep


}
}

3.​
4.​ For controller unit tests, use MockMvc with @WebMvcTest:​

java

@WebMvcTest(UserController.class)
public class UserControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private UserService userService;

@Test
public void shouldReturnUser() throws Exception {
// Arrange
User user = new User("1", "John");
when(userService.getUserById("1")).thenReturn(user);

// Act & Assert


mockMvc.perform(get("/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value("1"))
.andExpect(jsonPath("$.name").value("John"));
}
}

5.​

74. What is Spring Boot's support for caching?


Spring Boot simplifies caching configuration:

1.​ Add the dependency: spring-boot-starter-cache​

Copyright © 2025 by SkillForgePrep


2.​ Enable caching with @EnableCaching:​

java

@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

3.​
4.​ Use caching annotations on methods:​

java

@Service
public class UserService {

@Cacheable("users")
public User getUserById(String id) {
// Method will only be called if result not in cache
return fetchUserFromDatabase(id);
}

@CacheEvict("users")
public void updateUser(User user) {
// Update user in database and evict from cache
saveUserToDatabase(user);
}

@CachePut(value = "users", key = "#user.id")


public User createUser(User user) {
// Always execute method and update cache with result
return saveUserToDatabase(user);
}
}

5.​

Copyright © 2025 by SkillForgePrep


6.​ Configure cache providers (EhCache, Redis, etc.) as needed​

75. What is the difference between @RequestParam and


@PathVariable in Spring Boot?
Both annotations are used to extract values from the URL, but they serve different purposes:

●​ @RequestParam extracts values from the query string parameters:​



java

// URL: /users?name=John&age=25
@GetMapping("/users")
public List<User> getUsers(@RequestParam String name, @RequestParam
int age) {
// Access name and age values
}

●​
●​ @PathVariable extracts values from the path segments in the URL:​

java

// URL: /users/123/orders/456
@GetMapping("/users/{userId}/orders/{orderId}")
public Order getOrder(@PathVariable Long userId, @PathVariable Long
orderId) {
// Access userId and orderId values
}

●​

76. How do you implement aspect-oriented programming


(AOP) in Spring Boot?
To implement AOP in Spring Boot:

1.​ Add the dependency: spring-boot-starter-aop​

Copyright © 2025 by SkillForgePrep


2.​ Create aspects with @Aspect annotation:​

java

@Aspect
@Component
public class LoggingAspect {

private static final Logger logger =


LoggerFactory.getLogger(LoggingAspect.class);

@Before("execution(* com.example.service.*.*(..))")
public void logBeforeMethodExecution(JoinPoint joinPoint) {
logger.info("Executing: " +
joinPoint.getSignature().getName());
}

@AfterReturning(pointcut = "execution(*
com.example.service.*.*(..))", returning = "result")
public void logAfterMethodExecution(JoinPoint joinPoint, Object
result) {
logger.info("Completed: " + joinPoint.getSignature().getName()
+ " with result: " + result);
}

@Around("@annotation(com.example.annotation.Timed)")
public Object timeMethod(ProceedingJoinPoint joinPoint) throws
Throwable {
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
long elapsedTime = System.currentTimeMillis() - start;
logger.info(joinPoint.getSignature().getName() + " executed in
" + elapsedTime + "ms");
return result;
}
}

3.​

Copyright © 2025 by SkillForgePrep


4.​ Define custom annotations for pointcuts if needed:​

java

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Timed {
}

5.​

77. How do you implement custom validators in Spring


Boot?
To implement custom validators in Spring Boot:

1.​ Create a custom constraint annotation:​



java

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PhoneNumberValidator.class)
public @interface ValidPhoneNumber {
String message() default "Invalid phone number";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

2.​
3.​ Implement the validator:​

java

public class PhoneNumberValidator implements


ConstraintValidator<ValidPhoneNumber, String> {

@Override
public void initialize(ValidPhoneNumber constraintAnnotation) {
}

Copyright © 2025 by SkillForgePrep


@Override
public boolean isValid(String phoneNumber,
ConstraintValidatorContext context) {
if (phoneNumber == null) {
return true; // Let @NotNull handle null values
}
// Simple validation for example purposes
return phoneNumber.matches("\\d{10}|\\d{3}-\\d{3}-\\d{4}");
}
}

4.​
5.​ Use the custom validator in your model:​

java

public class User {


@NotBlank
private String name;

@ValidPhoneNumber
private String phoneNumber;

// getters and setters


}

6.​

78. What is the purpose of @ConfigurationProperties in


Spring Boot?
@ConfigurationProperties binds external configuration properties to a Java bean, allowing
strongly-typed access to configuration values:

java
@Configuration
@ConfigurationProperties(prefix = "mail")
public class MailProperties {
private String host;
private int port = 25; // default value

Copyright © 2025 by SkillForgePrep


private String username;
private String password;
private Map<String, String> headers = new HashMap<>();

// getters and setters


}

With the above configuration, properties like these in application.properties:

text
mail.host=smtp.example.com
mail.port=587
mail.username=user
mail.password=secret
[email protected]

Will be automatically bound to the fields in the MailProperties class, with type conversion and
validation.

79. How do you implement API rate limiting in Spring


Boot?
There are several ways to implement rate limiting:

1.​ Using Spring Cloud Gateway (for gateway applications):​



java

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("user_service", r -> r
.path("/users/**")
.filters(f -> f
.requestRateLimiter(c -> c
.setRateLimiter(redisRateLimiter())
.setKeyResolver(userKeyResolver()))
)

Copyright © 2025 by SkillForgePrep


.uri("lb://user-service"))
.build();
}

2.​
3.​ Using Bucket4j with Spring Boot:​

java

@Component
public class RateLimitingInterceptor implements HandlerInterceptor {
private final Map<String, Bucket> buckets = new
ConcurrentHashMap<>();

@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) {
String ipAddress = request.getRemoteAddr();
Bucket bucket = buckets.computeIfAbsent(ipAddress,
k -> Bucket4j.builder()
.addLimit(Bandwidth.simple(10, Duration.ofMinutes(1)))
.build());

boolean allowRequest = bucket.tryConsume(1);


if (!allowRequest) {
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.setContentType("application/json");
response.getWriter().write("{\"error\":\"Rate limit
exceeded\"}");
}
return allowRequest;
}
}

4.​
5.​ Using custom annotations and AOP:​

java

@Target(ElementType.METHOD)

Copyright © 2025 by SkillForgePrep


@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimit {
int limit() default 10;
int duration() default 60; // seconds
}

@Aspect
@Component
public class RateLimitingAspect {
private final Map<String, RateLimiter> rateLimiters = new
ConcurrentHashMap<>();

@Around("@annotation(rateLimit)")
public Object enforceRateLimit(ProceedingJoinPoint joinPoint,
RateLimit rateLimit) throws Throwable {
String methodKey = joinPoint.getSignature().toLongString();
RateLimiter rateLimiter =
rateLimiters.computeIfAbsent(methodKey,
k -> RateLimiter.create(rateLimit.limit() / (double)
rateLimit.duration()));

if (!rateLimiter.tryAcquire()) {
throw new TooManyRequestsException("Rate limit exceeded");
}

return joinPoint.proceed();
}
}

6.​

80. What is the purpose of @ResponseStatus in Spring


Boot?
@ResponseStatus is an annotation that marks a method or exception class with a specific
HTTP status code that should be returned. It can be used in two ways:

Copyright © 2025 by SkillForgePrep


1.​ On controller methods:​

java

@GetMapping("/not-found")
@ResponseStatus(HttpStatus.NOT_FOUND)
public void notFound() {
// Method implementation
}

2.​
3.​ On exception classes for exception handling:​

java

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}

4.​
5.​ When this exception is thrown from a controller method, the response status will
automatically be set to 404 Not Found.​

81. How do you implement WebSockets in Spring Boot?


To implement WebSockets in Spring Boot:

1.​ Add the dependency: spring-boot-starter-websocket​

2.​ Configure WebSocket support:​



java

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements
WebSocketMessageBrokerConfigurer {

Copyright © 2025 by SkillForgePrep


@Override
public void configureMessageBroker(MessageBrokerRegistry registry)
{
registry.enableSimpleBroker("/topic"); // Destination prefixes
for messages to clients
registry.setApplicationDestinationPrefixes("/app"); // Prefix
for client-to-server messages
}

@Override
public void registerStompEndpoints(StompEndpointRegistry registry)
{
registry.addEndpoint("/websocket")
.setAllowedOrigins("*")
.withSockJS(); // Fallback options if WebSocket isn't
available
}
}

3.​
4.​ Create a controller for handling WebSocket messages:​

java

@Controller
public class ChatController {

@MessageMapping("/chat.send")
@SendTo("/topic/messages")
public ChatMessage send(ChatMessage message) {
return message;
}

@MessageMapping("/chat.join")
@SendTo("/topic/users")
public UserEvent join(UserEvent event) {
return new UserEvent(event.getUsername(), "joined");
}
}

Copyright © 2025 by SkillForgePrep


5.​
6.​ Implement client-side JavaScript to connect to WebSocket​

82. How do you implement Spring Boot integration


testing with Docker?
To implement integration testing with Docker in Spring Boot:

1.​ Use Testcontainers library:​



xml

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>1.17.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.17.2</version>
<scope>test</scope>
</dependency>

2.​
3.​ Create integration tests:​

java

@SpringBootTest
@Testcontainers
public class UserServiceIntegrationTest {

@Container
static PostgreSQLContainer<?> postgres = new
PostgreSQLContainer<>("postgres:14")
.withDatabaseName("testdb")
.withUsername("test")

Copyright © 2025 by SkillForgePrep


.withPassword("test");

@DynamicPropertySource
static void postgresProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username",
postgres::getUsername);
registry.add("spring.datasource.password",
postgres::getPassword);
}

@Autowired
private UserRepository userRepository;

@Autowired
private UserService userService;

@Test
void shouldSaveUser() {
// Arrange
User user = new User(null, "John");

// Act
User savedUser = userService.createUser(user);

// Assert
assertNotNull(savedUser.getId());
assertEquals("John", savedUser.getName());

// Verify in database
Optional<User> foundUser =
userRepository.findById(savedUser.getId());
assertTrue(foundUser.isPresent());
assertEquals("John", foundUser.get().getName());
}
}

4.​

Copyright © 2025 by SkillForgePrep


83. What is Spring Boot's support for GraphQL?
Spring Boot provides support for GraphQL through the Spring for GraphQL project:

1.​ Add dependencies:​



xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-graphql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.​
3.​ Define a GraphQL schema in src/main/resources/graphql/schema.graphqls:​

graphql

type Query {
bookById(id: ID!): Book
allBooks: [Book]
}

type Book {
id: ID!
title: String!
author: Author!
pages: Int
}

type Author {
id: ID!
name: String!
books: [Book]
}

4.​
Copyright © 2025 by SkillForgePrep
5.​ Create a controller:​

java

@Controller
public class BookController {

private final BookRepository bookRepository;

public BookController(BookRepository bookRepository) {


this.bookRepository = bookRepository;
}

@QueryMapping
public Book bookById(@Argument ID id) {
return bookRepository.findById(id).orElse(null);
}

@QueryMapping
public List<Book> allBooks() {
return bookRepository.findAll();
}

@SchemaMapping
public Author author(Book book) {
return book.getAuthor();
}
}

6.​
7.​ Access the GraphQL endpoint at /graphql​

84. How do you implement request logging in Spring


Boot?
There are several ways to implement request logging in Spring Boot:

Copyright © 2025 by SkillForgePrep


1.​ Using a servlet filter:​

java

@Component
public class RequestLoggingFilter implements Filter {

private static final Logger logger =


LoggerFactory.getLogger(RequestLoggingFilter.class);

@Override
public void doFilter(ServletRequest request, ServletResponse
response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse)
response;

long startTime = System.currentTimeMillis();


logger.info("Starting request {} {}", httpRequest.getMethod(),
httpRequest.getRequestURI());

chain.doFilter(request, response);

long duration = System.currentTimeMillis() - startTime;


logger.info("Completed request {} {} with status {} in {}ms",
httpRequest.getMethod(),
httpRequest.getRequestURI(),
httpResponse.getStatus(),
duration);
}
}

2.​
3.​ Using Spring's built-in request logger:​

text

# application.properties

Copyright © 2025 by SkillForgePrep


logging.level.org.springframework.web.filter.CommonsRequestLoggingFilt
er=DEBUG

4.​
5.​ java

@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
CommonsRequestLoggingFilter loggingFilter = new
CommonsRequestLoggingFilter();
loggingFilter.setIncludeClientInfo(true);
loggingFilter.setIncludeQueryString(true);
loggingFilter.setIncludePayload(true);
loggingFilter.setMaxPayloadLength(10000);
loggingFilter.setIncludeHeaders(true);
return loggingFilter;
}

6.​
7.​ Using Spring AOP:​

java

@Aspect
@Component
public class RequestLoggingAspect {

private static final Logger logger =


LoggerFactory.getLogger(RequestLoggingAspect.class);

@Around("@annotation(org.springframework.web.bind.annotation.RequestMa
pping) || " +

"@annotation(org.springframework.web.bind.annotation.GetMapping) || "
+

"@annotation(org.springframework.web.bind.annotation.PostMapping)")
public Object logRequest(ProceedingJoinPoint joinPoint) throws
Throwable {

Copyright © 2025 by SkillForgePrep


HttpServletRequest request = ((ServletRequestAttributes)
RequestContextHolder.currentRequestAttributes()).getRequest();

logger.info("Request: {} {}", request.getMethod(),


request.getRequestURI());

long startTime = System.currentTimeMillis();


Object result = joinPoint.proceed();
long duration = System.currentTimeMillis() - startTime;

logger.info("Response: {} {} completed in {}ms",


request.getMethod(), request.getRequestURI(), duration);

return result;
}
}

8.​

85. What is the purpose of @ControllerAdvice in Spring


Boot?
@ControllerAdvice is a specialization of @Component that allows you to handle exceptions
across multiple controllers. It's used for:

1.​ Global exception handling:​



java

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(ResourceNotFoundException.class)
public ModelAndView
handleResourceNotFound(ResourceNotFoundException ex) {
ModelAndView modelAndView = new
ModelAndView("error/not-found");
modelAndView.addObject("message", ex.getMessage());
return modelAndView;

Copyright © 2025 by SkillForgePrep


}

@ExceptionHandler(Exception.class)
public ModelAndView handleGenericException(Exception ex) {
ModelAndView modelAndView = new ModelAndView("error/generic");
modelAndView.addObject("message", "An unexpected error
occurred");
return modelAndView;
}
}

2.​
3.​ Global model attributes:​

java

@ControllerAdvice
public class GlobalModelAttributes {

@ModelAttribute("categories")
public List<String> getCategories() {
return Arrays.asList("Electronics", "Books", "Clothing");
}
}

4.​
5.​ Global data binding:​

java

@ControllerAdvice
public class GlobalDataBinder {

@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new
CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}
}

6.​
Copyright © 2025 by SkillForgePrep
86. How do you implement HATEOAS in Spring Boot?
HATEOAS (Hypermedia as the Engine of Application State) can be implemented in Spring Boot
using Spring HATEOAS:

1.​ Add the dependency: spring-boot-starter-hateoas​

2.​ Create entity models with links:​



java

@RestController
@RequestMapping("/users")
public class UserController {

private final UserService userService;

public UserController(UserService userService) {


this.userService = userService;
}

@GetMapping("/{id}")
public EntityModel<User> getUser(@PathVariable Long id) {
User user = userService.getUserById(id);

return EntityModel.of(user,

linkTo(methodOn(UserController.class).getUser(id)).withSelfRel(),

linkTo(methodOn(UserController.class).getAllUsers()).withRel("all-user
s"),

linkTo(methodOn(OrderController.class).getOrdersByUserId(id)).withRel(
"orders")
);
}

@GetMapping
public CollectionModel<EntityModel<User>> getAllUsers() {
List<User> users = userService.getAllUsers();

Copyright © 2025 by SkillForgePrep


List<EntityModel<User>> userModels = users.stream()
.map(user -> EntityModel.of(user,

linkTo(methodOn(UserController.class).getUser(user.getId())).withSelfR
el(),

linkTo(methodOn(OrderController.class).getOrdersByUserId(user.getId())
).withRel("orders")
))
.collect(Collectors.toList());

return CollectionModel.of(userModels,

linkTo(methodOn(UserController.class).getAllUsers()).withSelfRel());
}
}

3.​
4.​ The JSON response will include links to related resources​

87. What is the purpose of @RequestBody and


@ResponseBody annotations?
@RequestBody and @ResponseBody are annotations used in Spring MVC and Spring Boot to
handle HTTP request and response payloads:

●​ @RequestBody: Indicates that a method parameter should be bound to the body of the
HTTP request. Spring automatically deserializes the HTTP request body into the Java
object.​

java

@PostMapping("/users")
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}

●​

Copyright © 2025 by SkillForgePrep


●​ @ResponseBody: Indicates that the method return value should be bound to the HTTP
response body. Spring automatically serializes the returned object to the response.​

java

@GetMapping("/users/{id}")
@ResponseBody
public User getUser(@PathVariable Long id) {
return userService.getUserById(id);
}

●​

Note: When using @RestController, @ResponseBody is implied for all methods and doesn't
need to be explicitly added.

88. How do you implement conditional beans in Spring


Boot?
Conditional beans can be implemented using Spring's condition annotations:

java
@Configuration
public class AppConfig {

@Bean
@ConditionalOnProperty(name = "feature.legacy", havingValue =
"true")
public LegacyService legacyService() {
return new LegacyServiceImpl();
}

@Bean
@ConditionalOnClass(name = "com.example.ExternalClass")
public ExternalService externalService() {
return new ExternalServiceImpl();
}

@Bean
@ConditionalOnMissingBean

Copyright © 2025 by SkillForgePrep


public DefaultService defaultService() {
return new DefaultServiceImpl();
}

@Bean
@ConditionalOnExpression("${app.enable-feature} and
'${app.feature-mode}'=='advanced'")
public AdvancedFeatureService advancedFeatureService() {
return new AdvancedFeatureServiceImpl();
}

@Bean
@ConditionalOnWebApplication
public WebHelperService webHelperService() {
return new WebHelperServiceImpl();
}

@Bean
@Profile("dev")
public DevToolsService devToolsService() {
return new DevToolsServiceImpl();
}
}

You can also create custom conditions by implementing the Condition interface:

java
public class OnCustomCondition implements Condition {
@Override
public boolean matches(ConditionContext context,
AnnotatedTypeMetadata metadata) {
Environment env = context.getEnvironment();
return env.containsProperty("custom.property") &&
"enabled".equals(env.getProperty("custom.property"));
}
}

@Conditional(OnCustomCondition.class)

Copyright © 2025 by SkillForgePrep


@Bean
public CustomService customService() {
return new CustomServiceImpl();
}

89. How do you handle application events in Spring


Boot?
Spring Boot provides an event framework for publishing and listening to application events:

1.​ Define a custom event:​



java

public class UserCreatedEvent extends ApplicationEvent {


private final User user;

public UserCreatedEvent(Object source, User user) {


super(source);
this.user = user;
}

public User getUser() {


return user;
}
}

2.​
3.​ Publish the event:​

java

@Service
public class UserService {
private final UserRepository userRepository;
private final ApplicationEventPublisher eventPublisher;

public UserService(UserRepository userRepository,


ApplicationEventPublisher eventPublisher) {

Copyright © 2025 by SkillForgePrep


this.userRepository = userRepository;
this.eventPublisher = eventPublisher;
}

public User createUser(User user) {


User savedUser = userRepository.save(user);
eventPublisher.publishEvent(new UserCreatedEvent(this,
savedUser));
return savedUser;
}
}

4.​
5.​ Listen for events:​

java

@Component
public class UserEventListener {

private static final Logger logger =


LoggerFactory.getLogger(UserEventListener.class);

@EventListener
public void handleUserCreatedEvent(UserCreatedEvent event) {
logger.info("User created: {}", event.getUser().getId());
// Send welcome email, etc.
}

@EventListener
@Async
public void handleUserCreatedEventAsync(UserCreatedEvent event) {
// Async processing
}

@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void handleUserCreatedEventTransactional(UserCreatedEvent
event) {
// Only process after transaction commits

Copyright © 2025 by SkillForgePrep


}
}

6.​

90. What is Spring Boot's support for Kotlin?


Spring Boot provides first-class support for Kotlin:

1.​ Built-in support for Kotlin in Spring Boot starters​

2.​ Kotlin extensions for Spring Framework, including:​

○​ Extension functions for Spring API​

○​ Bean registration DSL​

○​ WebFlux DSL​

○​ Coroutines support​

3.​ Kotlin-specific auto-configuration​

4.​ Null-safety support with Spring's null-safety annotations​

Example of a Spring Boot application in Kotlin:

kotlin
@SpringBootApplication
class MyApplication

fun main(args: Array<String>) {


runApplication<MyApplication>(*args)
}

@RestController
class UserController(private val userService: UserService) {

@GetMapping("/users/{id}")
fun getUser(@PathVariable id: Long): User {
return userService.getUserById(id)

Copyright © 2025 by SkillForgePrep


}

@GetMapping("/users")
fun getUsers(): List<User> {
return userService.getAllUsers()
}
}

@Service
class UserService(private val userRepository: UserRepository) {

fun getUserById(id: Long): User {


return userRepository.findById(id).orElseThrow {
UserNotFoundException(id) }
}

fun getAllUsers(): List<User> {


return userRepository.findAll()
}
}

91. What are Spring Boot's property binding rules?


Spring Boot's property binding follows these rules:

1.​ Kebab case in properties files: spring.http.log-request-details=true​

2.​ Camel case in Java properties: springHttpLogRequestDetails=true​

3.​ Properties can be grouped with prefixes:​



text

app.service.enabled=true
app.service.timeout=30

4.​

Copyright © 2025 by SkillForgePrep


5.​ List properties can be bound using indexed notation:​

text

app.my-list[0]=value1
app.my-list[1]=value2

6.​
7.​ or using comma separation:​

text

app.my-list=value1,value2

8.​
9.​ Map properties:​

text

app.my-map.key1=value1
app.my-map.key2=value2

10.​
11.​Duration properties (converted automatically):​

text

app.timeout=30s
app.connection-timeout=PT10S

12.​
13.​Size properties:​

text

app.max-file-size=10MB

14.​

92. What is the purpose of Spring Boot's


@ImportAutoConfiguration?

Copyright © 2025 by SkillForgePrep


@ImportAutoConfiguration is an annotation used to selectively import and apply
auto-configuration classes. It's particularly useful in testing scenarios when you want to include
specific auto-configurations without loading all of them:

java
@ImportAutoConfiguration(DataSourceAutoConfiguration.class)
@SpringBootTest
public class DatabaseTest {

@Autowired
private DataSource dataSource;

@Test
public void testDataSource() {
assertNotNull(dataSource);
// More tests
}
}

This allows you to precisely control which auto-configurations are applied without relying on the
full auto-configuration mechanism.

93. What is Spring Boot's ApplicationRunner interface?


ApplicationRunner is an interface that lets you execute code after the Spring Boot application
has started. It's similar to CommandLineRunner but receives the command line arguments
wrapped in ApplicationArguments:

java
@Component
public class MyApplicationRunner implements ApplicationRunner {

private static final Logger logger =


LoggerFactory.getLogger(MyApplicationRunner.class);

@Override
public void run(ApplicationArguments args) throws Exception {
logger.info("Application started with the following
options:");

Copyright © 2025 by SkillForgePrep


if (args.containsOption("debug")) {
logger.info("Debug mode activated");
}

List<String> fileOptions = args.getOptionValues("file");


if (fileOptions != null) {
logger.info("File options: {}", fileOptions);
}

logger.info("Non-option arguments: {}",


args.getNonOptionArgs());
}
}

ApplicationRunner beans are automatically called by Spring Boot after the application is fully
started.

94. How do you create custom Spring Boot starter?


To create a custom Spring Boot starter:

1.​ Create a starter project:​



text

my-spring-boot-starter/
├── pom.xml
└── src/
└── main/
├── java/
│ └── com/example/starter/
│ ├── MyAutoConfiguration.java
│ ├── MyService.java
│ └── MyServiceProperties.java
└── resources/
└── META-INF/
├── spring.factories
└── additional-spring-configuration-metadata.json

Copyright © 2025 by SkillForgePrep


2.​
3.​ Configure pom.xml:​

xml

<groupId>com.example</groupId>
<artifactId>my-spring-boot-starter</artifactId>
<version>1.0.0</version>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>

4.​
5.​ Create configuration properties:​

java

@ConfigurationProperties(prefix = "my.service")
public class MyServiceProperties {
private boolean enabled = true;
private String prefix = "Default";

// getters and setters


}

6.​

Copyright © 2025 by SkillForgePrep


7.​ Create the service:​

java

public class MyService {


private final String prefix;

public MyService(String prefix) {


this.prefix = prefix;
}

public String getMessage(String message) {


return prefix + ": " + message;
}
}

8.​
9.​ Create auto-configuration:​

java

@Configuration
@ConditionalOnClass(MyService.class)
@EnableConfigurationProperties(MyServiceProperties.class)
public class MyAutoConfiguration {

@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "my.service", name = "enabled",
havingValue = "true", matchIfMissing = true)
public MyService myService(MyServiceProperties properties) {
return new MyService(properties.getPrefix());
}
}

10.​
11.​Create spring.factories file:​

text

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\

Copyright © 2025 by SkillForgePrep


com.example.starter.MyAutoConfiguration

12.​
13.​Create additional-spring-configuration-metadata.json:​

json

{
"properties": [
{
"name": "my.service.enabled",
"type": "java.lang.Boolean",
"description": "Enable my service.",
"defaultValue": true
},
{
"name": "my.service.prefix",
"type": "java.lang.String",
"description": "Message prefix for my service.",
"defaultValue": "Default"
}
]
}

14.​

95. How do you handle distributed tracing in Spring


Boot?
Spring Boot provides support for distributed tracing through Spring Cloud Sleuth and integration
with OpenTelemetry:

1.​ Add dependencies:​



xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Copyright © 2025 by SkillForgePrep


<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth-zipkin</artifactId>
</dependency>

2.​
3.​ Configure tracing in application.properties:​

text

spring.application.name=my-service
spring.sleuth.sampler.probability=1.0
spring.zipkin.base-url=http://localhost:9411

4.​
5.​ Tracing is automatically added to:​

○​ HTTP requests​

○​ RestTemplate calls​

○​ Async operations​

○​ Messaging (Kafka, RabbitMQ)​

6.​ Custom spans can be created:​



java

@Service
public class OrderService {

private final Tracer tracer;

public OrderService(Tracer tracer) {


this.tracer = tracer;
}

Copyright © 2025 by SkillForgePrep


public Order processOrder(Order order) {
Span span = tracer.nextSpan().name("process-order").start();
try (SpanInScope ws = tracer.withSpan(span)) {
// Process order
validateOrder(order);
calculateTotals(order);
saveOrder(order);
return order;
} finally {
span.end();
}
}

private void validateOrder(Order order) {


Span span = tracer.nextSpan().name("validate-order").start();
try (SpanInScope ws = tracer.withSpan(span)) {
// Validation logic
} finally {
span.end();
}
}
}

7.​

96. How do you implement circuit breaker pattern in


Spring Boot?
The circuit breaker pattern can be implemented in Spring Boot using Resilience4j or Spring
Cloud Circuit Breaker:

1.​ Add dependencies:​



xml

<dependency>
<groupId>org.springframework.cloud</groupId>

Copyright © 2025 by SkillForgePrep


<artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifact
Id>
</dependency>

2.​
3.​ Configure circuit breakers:​

java

@Configuration
public class CircuitBreakerConfig {

@Bean
public Customizer<Resilience4JCircuitBreakerFactory>
defaultCustomizer() {
return factory -> factory.configureDefault(id -> new
Resilience4JConfigBuilder(id)

.timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration
.ofSeconds(4)).build())
.circuitBreakerConfig(CircuitBreakerConfig.custom()
.failureRateThreshold(50)
.waitDurationInOpenState(Duration.ofMillis(1000))
.slidingWindowSize(10)
.permittedNumberOfCallsInHalfOpenState(3)
.build())
.build());
}
}

4.​
5.​ Use circuit breaker in service:​

java

@Service
public class UserService {

private final RestTemplate restTemplate;

Copyright © 2025 by SkillForgePrep


private final CircuitBreakerFactory circuitBreakerFactory;

public UserService(RestTemplate restTemplate,


CircuitBreakerFactory circuitBreakerFactory) {
this.restTemplate = restTemplate;
this.circuitBreakerFactory = circuitBreakerFactory;
}

public User getUserById(Long id) {


CircuitBreaker circuitBreaker =
circuitBreakerFactory.create("userService");
return circuitBreaker.run(
() -> restTemplate.getForObject("/users/{id}", User.class,
id),
throwable -> getFallbackUser(id, throwable)
);
}

private User getFallbackUser(Long id, Throwable throwable) {


// Return a fallback user or cached data
return new User(id, "Fallback User");
}
}

6.​
7.​ Alternatively, use the annotation-based approach:​

java

@Service
public class UserService {

private final RestTemplate restTemplate;

public UserService(RestTemplate restTemplate) {


this.restTemplate = restTemplate;
}

Copyright © 2025 by SkillForgePrep


@CircuitBreaker(name = "userService", fallbackMethod =
"getFallbackUser")
public User getUserById(Long id) {
return restTemplate.getForObject("/users/{id}", User.class,
id);
}

private User getFallbackUser(Long id, Exception ex) {


return new User(id, "Fallback User");
}
}

8.​

97. What is Spring Boot's support for configuration


groups?
Spring Boot's configuration properties binding supports grouping related properties:

1.​ Define a configuration group:​



java

@ConfigurationProperties(prefix = "app")
public class AppProperties {

private final Server server = new Server();


private final Client client = new Client();

public Server getServer() {


return server;
}

public Client getClient() {


return client;
}

public static class Server {


private String host;

Copyright © 2025 by SkillForgePrep


private int port = 8080;
private boolean secure = false;

// getters and setters


}

public static class Client {


private int timeout = 30;
private int retryCount = 3;

// getters and setters


}
}

2.​
3.​ Configure in application.properties:​

text

app.server.host=example.com
app.server.port=9090
app.server.secure=true

app.client.timeout=60
app.client.retry-count=5

4.​
5.​ Use the configuration:​

java

@Service
public class AppService {

private final AppProperties appProperties;

public AppService(AppProperties appProperties) {


this.appProperties = appProperties;
}

Copyright © 2025 by SkillForgePrep


public void connect() {
String serverHost = appProperties.getServer().getHost();
int serverPort = appProperties.getServer().getPort();
boolean secure = appProperties.getServer().isSecure();

// Use the configuration


}
}

6.​

98. How do you handle JSON serialization and


deserialization in Spring Boot?
Spring Boot handles JSON serialization and deserialization using Jackson by default:

1.​ Auto-configuration: Spring Boot automatically configures Jackson when


jackson-databind is on the classpath.​

2.​ Customizing ObjectMapper:​



java

@Configuration
public class JacksonConfig {

@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
mapper.registerModule(new JavaTimeModule());
return mapper;
}
}

3.​

Copyright © 2025 by SkillForgePrep


4.​ Using properties for common customizations:​

text

spring.jackson.serialization.indent_output=true
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.default-property-inclusion=non_null
spring.jackson.deserialization.fail-on-unknown-properties=false

5.​
6.​ Customizing serialization for specific classes:​

java

public class User {


private Long id;

@JsonProperty("full_name") // Custom property name


private String name;

@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate birthDate;

@JsonIgnore // Exclude from serialization


private String password;

// getters and setters


}

7.​
8.​ Creating custom serializers and deserializers:​

java

public class CustomDateSerializer extends JsonSerializer<LocalDate> {


@Override
public void serialize(LocalDate value, JsonGenerator gen,
SerializerProvider provider) throws IOException {

gen.writeString(value.format(DateTimeFormatter.ISO_LOCAL_DATE));
}

Copyright © 2025 by SkillForgePrep


}

// Register with:
SimpleModule module = new SimpleModule();
module.addSerializer(LocalDate.class, new CustomDateSerializer());
objectMapper.registerModule(module);

9.​

99. How do you implement paging and sorting in Spring


Boot REST APIs?
Spring Boot makes paging and sorting straightforward using Spring Data:

1.​ Create a repository that extends PagingAndSortingRepository:​



java

public interface ProductRepository extends


PagingAndSortingRepository<Product, Long> {
Page<Product> findByCategory(String category, Pageable pageable);
}

2.​
3.​ Implement the controller:​

java

@RestController
@RequestMapping("/products")
public class ProductController {

private final ProductRepository productRepository;

public ProductController(ProductRepository productRepository) {


this.productRepository = productRepository;
}

@GetMapping
public Page<Product> getProducts(

Copyright © 2025 by SkillForgePrep


@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(defaultValue = "id,asc") String[] sort) {

Sort.Direction direction = sort[1].equalsIgnoreCase("asc") ?


Sort.Direction.ASC : Sort.Direction.DESC;
Sort sortObj = Sort.by(direction, sort[0]);
Pageable pageable = PageRequest.of(page, size, sortObj);

return productRepository.findAll(pageable);
}

@GetMapping("/by-category")
public Page<Product> getProductsByCategory(
@RequestParam String category,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {

Pageable pageable = PageRequest.of(page, size);


return productRepository.findByCategory(category, pageable);
}
}

4.​
5.​ Clients can request pages with:​

text

/products?page=0&size=10&sort=price,desc

6.​
7.​ Add HATEOAS support for pagination:​

java

@RestController
@RequestMapping("/products")
public class ProductController {

private final ProductRepository productRepository;

Copyright © 2025 by SkillForgePrep


public ProductController(ProductRepository productRepository) {
this.productRepository = productRepository;
}

@GetMapping
public ResponseEntity<PagedModel<EntityModel<Product>>>
getProducts(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(defaultValue = "id,asc") String[] sort,
PagedResourcesAssembler<Product> assembler) {

Sort.Direction direction = sort[1].equalsIgnoreCase("asc") ?


Sort.Direction.ASC : Sort.Direction.DESC;
Sort sortObj = Sort.by(direction, sort[0]);
Pageable pageable = PageRequest.of(page, size, sortObj);

Page<Product> productPage =
productRepository.findAll(pageable);

return ResponseEntity.ok(
assembler.toModel(productPage,
product -> EntityModel.of(product,

linkTo(methodOn(ProductController.class).getProduct(product.getId())).
withSelfRel())
)
);
}

@GetMapping("/{id}")
public EntityModel<Product> getProduct(@PathVariable Long id) {
Product product = productRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Product
not found"));

return EntityModel.of(product,

Copyright © 2025 by SkillForgePrep


linkTo(methodOn(ProductController.class).getProduct(id)).withSelfRel()
,
linkTo(methodOn(ProductController.class).getProducts(0,
10, new String[]{"id", "asc"}, null)).withRel("products")
);
}
}

8.​

100. How do you handle database connection pooling in


Spring Boot?
Spring Boot handles database connection pooling automatically:

1.​ Default behavior: Spring Boot uses HikariCP as the default connection pool when
available on the classpath.​

2.​ Basic configuration in application.properties:​



text

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password

# HikariCP specific settings


spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.max-lifetime=1800000

3.​
4.​ Using a different connection pool:​

○​ Add the dependency for the desired pool (e.g., Tomcat JDBC or Apache DBCP2)​

○​ Remove HikariCP dependency if needed​

Copyright © 2025 by SkillForgePrep


○​ Spring Boot will auto-configure the available pool​

5.​ Manual configuration:​



java

@Configuration
public class DataSourceConfig {

@Bean
@ConfigurationProperties("spring.datasource.hikari")
public HikariConfig hikariConfig() {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
config.setUsername("root");
config.setPassword("password");
config.setMaximumPoolSize(10);
return config;
}

@Bean
public DataSource dataSource() {
return new HikariDataSource(hikariConfig());
}
}

6.​
7.​ Monitoring connection pool:​

○​ Spring Boot Actuator exposes connection pool metrics​

○​ Enable with:​

text

management.endpoints.web.exposure.include=health,info,metrics
management.metrics.enable.jdbc=true

○​
○​ Access at: /actuator/metrics/hikaricp.connections.active​

Copyright © 2025 by SkillForgePrep


101. What is Spring Boot's support for content
negotiation?
Spring Boot provides content negotiation through Spring MVC, allowing the same endpoint to
serve different formats based on request headers or URL parameters:

1.​ Configuration in application.properties:​



text

spring.mvc.contentnegotiation.favor-parameter=true
spring.mvc.contentnegotiation.parameter-name=format
spring.mvc.contentnegotiation.media-types.json=application/json
spring.mvc.contentnegotiation.media-types.xml=application/xml

2.​
3.​ Implementation in controllers:​

java

@RestController
@RequestMapping("/users")
public class UserController {

private final UserService userService;

public UserController(UserService userService) {


this.userService = userService;
}

@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return userService.getUserById(id);
}
}

4.​
5.​ With this setup, clients can request different formats:​

Copyright © 2025 by SkillForgePrep


○​ Using Accept header: Accept: application/xml or Accept:
application/json​

○​ Using URL parameter: /users/1?format=xml or /users/1?format=json​

6.​ Custom content negotiation configuration:​



java

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Override
public void
configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.favorParameter(true)
.parameterName("format")
.ignoreAcceptHeader(false)
.useRegisteredExtensionsOnly(false)
.defaultContentType(MediaType.APPLICATION_JSON)
.mediaType("json", MediaType.APPLICATION_JSON)
.mediaType("xml", MediaType.APPLICATION_XML)
.mediaType("pdf", MediaType.APPLICATION_PDF);
}
}

7.​

102. What is the purpose of @Conditional annotation in


Spring Boot?
@Conditional is a core Spring Framework annotation that Spring Boot uses extensively for its
auto-configuration. It allows beans to be conditionally registered based on conditions:

1.​ Basic usage:​



java

@Configuration

Copyright © 2025 by SkillForgePrep


public class MyConfig {

@Bean
@Conditional(MyCondition.class)
public MyService myService() {
return new MyServiceImpl();
}
}

public class MyCondition implements Condition {


@Override
public boolean matches(ConditionContext context,
AnnotatedTypeMetadata metadata) {
Environment env = context.getEnvironment();
return env.containsProperty("my.service.enabled") &&
env.getProperty("my.service.enabled", Boolean.class,
false);
}
}

2.​
3.​ Spring Boot provides specialized conditional annotations:​

○​ @ConditionalOnClass: Register bean when a class is present​

○​ @ConditionalOnMissingClass: Register bean when a class is not present​

○​ @ConditionalOnBean: Register bean when another bean exists​

○​ @ConditionalOnMissingBean: Register bean when another bean doesn't exist​

○​ @ConditionalOnProperty: Register bean based on property values​

○​ @ConditionalOnResource: Register bean when a resource is available​

○​ @ConditionalOnWebApplication: Register bean when it's a web application​

○​ @ConditionalOnNotWebApplication: Register bean when it's not a web


application​

Copyright © 2025 by SkillForgePrep


○​ @ConditionalOnExpression: Register bean based on SpEL expression​

○​ @ConditionalOnJava: Register bean based on Java version​

○​ @ConditionalOnJndi: Register bean when JNDI is available​

○​ @ConditionalOnCloudPlatform: Register bean on specific cloud platform​

4.​ These are crucial for Spring Boot's auto-configuration mechanism, which applies
configuration only when needed.​

103. How do you implement file storage in Spring Boot


applications?
File storage can be implemented in Spring Boot in several ways:

1.​ Local file system storage:​



java

@Service
public class FileStorageService {

private final Path storageLocation;

public FileStorageService(@Value("${file.storage.location}")
String storageLocation) {
this.storageLocation =
Paths.get(storageLocation).toAbsolutePath().normalize();

try {
Files.createDirectories(this.storageLocation);
} catch (IOException e) {
throw new RuntimeException("Could not create storage
directory", e);
}
}

public String store(MultipartFile file) {

Copyright © 2025 by SkillForgePrep


try {
String filename =
StringUtils.cleanPath(file.getOriginalFilename());
String uniqueFilename = UUID.randomUUID().toString() + "_"
+ filename;
Path targetLocation =
this.storageLocation.resolve(uniqueFilename);
Files.copy(file.getInputStream(), targetLocation,
StandardCopyOption.REPLACE_EXISTING);
return uniqueFilename;
} catch (IOException e) {
throw new RuntimeException("Failed to store file", e);
}
}

public Resource loadAsResource(String filename) {


try {
Path filePath =
this.storageLocation.resolve(filename).normalize();
Resource resource = new UrlResource(filePath.toUri());

if (resource.exists() || resource.isReadable()) {
return resource;
} else {
throw new RuntimeException("Could not read file: " +
filename);
}
} catch (Exception e) {
throw new RuntimeException("Could not read file: " +
filename, e);
}
}
}

2.​
3.​ Cloud storage (AWS S3 example):​

java

Copyright © 2025 by SkillForgePrep


@Service
public class S3FileStorageService {

private final AmazonS3 s3Client;


private final String bucketName;

public S3FileStorageService(
AmazonS3 s3Client,
@Value("${aws.s3.bucket}") String bucketName) {
this.s3Client = s3Client;
this.bucketName = bucketName;
}

public String store(MultipartFile file) {


try {
String filename = UUID.randomUUID().toString() + "_" +
file.getOriginalFilename();
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(file.getSize());
metadata.setContentType(file.getContentType());

s3Client.putObject(new PutObjectRequest(
bucketName, filename, file.getInputStream(), metadata
).withCannedAcl(CannedAccessControlList.PublicRead));

return s3Client.getUrl(bucketName, filename).toString();


} catch (IOException e) {
throw new RuntimeException("Failed to store file", e);
}
}

public S3Object getFile(String filename) {


return s3Client.getObject(bucketName, filename);
}

public void deleteFile(String filename) {


s3Client.deleteObject(bucketName, filename);
}

Copyright © 2025 by SkillForgePrep


}

4.​
5.​ Database storage (for small files):​

java

@Entity
public class FileEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String filename;


private String contentType;

@Lob
private byte[] data;

// getters and setters


}

public interface FileRepository extends JpaRepository<FileEntity,


Long> {
}

@Service
public class DatabaseFileStorageService {

private final FileRepository fileRepository;

public DatabaseFileStorageService(FileRepository fileRepository) {


this.fileRepository = fileRepository;
}

public Long store(MultipartFile file) throws IOException {


FileEntity fileEntity = new FileEntity();
fileEntity.setFilename(file.getOriginalFilename());
fileEntity.setContentType(file.getContentType());

Copyright © 2025 by SkillForgePrep


fileEntity.setData(file.getBytes());

FileEntity savedFile = fileRepository.save(fileEntity);


return savedFile.getId();
}

public FileEntity getFile(Long id) {


return fileRepository.findById(id)
.orElseThrow(() -> new EntityNotFoundException("File not
found"));
}
}

6.​

104. What is Spring Boot's support for batch processing?


Spring Boot provides integration with Spring Batch for batch processing:

1.​ Add the dependency: spring-boot-starter-batch​

2.​ Configure a job:​



java

@Configuration
@EnableBatchProcessing
public class BatchConfig {

private final JobBuilderFactory jobBuilderFactory;


private final StepBuilderFactory stepBuilderFactory;

public BatchConfig(JobBuilderFactory jobBuilderFactory,


StepBuilderFactory stepBuilderFactory) {
this.jobBuilderFactory = jobBuilderFactory;
this.stepBuilderFactory = stepBuilderFactory;
}

@Bean
public ItemReader<Transaction> reader() {

Copyright © 2025 by SkillForgePrep


FlatFileItemReader<Transaction> reader = new
FlatFileItemReader<>();
reader.setResource(new ClassPathResource("transactions.csv"));
reader.setLineMapper(lineMapper());
return reader;
}

@Bean
public LineMapper<Transaction> lineMapper() {
DefaultLineMapper<Transaction> lineMapper = new
DefaultLineMapper<>();

DelimitedLineTokenizer tokenizer = new


DelimitedLineTokenizer();
tokenizer.setDelimiter(",");
tokenizer.setNames("id", "amount", "timestamp",
"description");

BeanWrapperFieldSetMapper<Transaction> fieldSetMapper = new


BeanWrapperFieldSetMapper<>();
fieldSetMapper.setTargetType(Transaction.class);

lineMapper.setLineTokenizer(tokenizer);
lineMapper.setFieldSetMapper(fieldSetMapper);

return lineMapper;
}

@Bean
public ItemProcessor<Transaction, Transaction> processor() {
return transaction -> {
// Process transaction (e.g., convert currency, validate)

transaction.setDescription(transaction.getDescription().toUpperCase())
;
return transaction;
};
}

Copyright © 2025 by SkillForgePrep


@Bean
public ItemWriter<Transaction> writer() {
JdbcBatchItemWriter<Transaction> writer = new
JdbcBatchItemWriter<>();
writer.setDataSource(dataSource);
writer.setSql("INSERT INTO transactions (id, amount,
timestamp, description) VALUES (:id, :amount, :timestamp,
:description)");
writer.setItemSqlParameterSourceProvider(new
BeanPropertyItemSqlParameterSourceProvider<>());
return writer;
}

@Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.<Transaction, Transaction>chunk(10)
.reader(reader())
.processor(processor())
.writer(writer())
.build();
}

@Bean
public Job importTransactionsJob(JobCompletionNotificationListener
listener) {
return jobBuilderFactory.get("importTransactionsJob")
.incrementer(new RunIdIncrementer())
.listener(listener)
.flow(step1())
.end()
.build();
}
}

3.​

Copyright © 2025 by SkillForgePrep


4.​ Create a job completion listener:​

java

@Component
public class JobCompletionNotificationListener extends
JobExecutionListenerSupport {

private static final Logger logger =


LoggerFactory.getLogger(JobCompletionNotificationListener.class);

@Override
public void afterJob(JobExecution jobExecution) {
if(jobExecution.getStatus() == BatchStatus.COMPLETED) {
logger.info("Job finished!

Copyright © 2025 by SkillForgePrep


101. How do you implement rate limiting in Spring Boot?

Rate limiting controls the number of requests a client can make to an API within a specific
timeframe. Use Spring Cloud Gateway or Bucket4j with Spring Boot:

java

@Bean

public RateLimiter<SimpleRateLimiter> rateLimiter() {

return new SimpleRateLimiter(100, Duration.ofMinutes(1));

Configure endpoints in application.properties:

text

spring.cloud.gateway.routes[0].filters[0]=RequestRateLimiter=10, 1,
SECONDS

102. How does Spring Boot handle database migration?

Spring Boot integrates with Flyway or Liquibase for database version control. Add
spring-boot-starter-flyway and place SQL scripts in
src/main/resources/db/migration. On startup, Flyway applies pending migrations6.

103. Explain Spring Boot’s @ConditionalOnProperty.

This annotation conditionally creates beans based on property values:

java

Copyright © 2025 by SkillForgePrep


@Bean

@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")

public FeatureService featureService() {

return new FeatureServiceImpl();

104. How do you secure sensitive data in


application.properties?

Use Spring Cloud Config Server with encryption or Jasypt for property encryption:

text

spring.datasource.password=ENC(encryptedPassword)

Add jasypt-spring-boot-starter and enable encryption with


jasypt.encryptor.password8.

105. What is Spring Boot DevTools used for?

DevTools provides auto-restart, LiveReload, and development-specific configurations. It


disables caching in templates and enables debug settings automatically6.

106. How do you handle cross-origin requests (CORS) in


Spring Boot?

Configure globally via WebMvcConfigurer:

Copyright © 2025 by SkillForgePrep


java

@Override

public void addCorsMappings(CorsRegistry registry) {

registry.addMapping("/api/**")

.allowedOrigins("https://example.com")

.allowedMethods("GET", "POST");

107. What is the purpose of


spring-boot-starter-parent?

It provides default Maven configurations, dependency management, and plugin settings. Child
POMs inherit versions for Spring Boot dependencies, reducing conflicts6.

108. How do you expose custom metrics in Spring Boot?

Use Micrometer with Actuator:

java

@Bean

public MeterRegistryCustomizer<MeterRegistry> metrics() {

return registry -> registry.config().commonTags("region",


"us-east");

Copyright © 2025 by SkillForgePrep


Access metrics via /actuator/metrics3.

109. Explain Spring Boot’s @SpringBootTest.

This annotation loads the full application context for integration testing:

java

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)

public class IntegrationTest {

@Autowired

private TestRestTemplate restTemplate;

110. How do you implement OAuth2 in Spring Boot?

Add spring-boot-starter-oauth2-client and configure providers in


application.yml:

text

spring:

security:

oauth2:

client:

registration:

Copyright © 2025 by SkillForgePrep


google:

client-id: your-client-id

client-secret: your-secret

111. What is Spring Boot’s CommandLineRunner?

It executes code on application startup:

java

@Component

public class StartupRunner implements CommandLineRunner {

@Override

public void run(String... args) {

// Initialization logic

112. How do you configure multiple databases in Spring


Boot?

Define multiple DataSource beans with @Primary:

java

Copyright © 2025 by SkillForgePrep


@Primary

@Bean

@ConfigurationProperties("app.datasource.primary")

public DataSource primaryDataSource() {

return DataSourceBuilder.create().build();

@Bean

@ConfigurationProperties("app.datasource.secondary")

public DataSource secondaryDataSource() {

return DataSourceBuilder.create().build();

113. Explain Spring Boot’s @ConfigurationProperties.

It binds external properties to a Java object:

java

@ConfigurationProperties(prefix = "mail")

public class MailProperties {

private String host;

private int port;

Copyright © 2025 by SkillForgePrep


}

Use in application.properties as mail.host=smtp.example.com6.

114. How do you handle file uploads in Spring Boot?

Use MultipartFile:

java

@PostMapping("/upload")

public String uploadFile(@RequestParam("file") MultipartFile file) {

file.transferTo(new File("/path/" + file.getOriginalFilename()));

Configure size limits in application.properties:

text

spring.servlet.multipart.max-file-size=10MB

115. What is Spring Boot’s HealthIndicator?

Custom health checks extend HealthIndicator:

java

@Component

Copyright © 2025 by SkillForgePrep


public class CustomHealth implements HealthIndicator {

@Override

public Health health() {

return Health.up().withDetail("service", "active").build();

116. How do you implement caching in Spring Boot?

Enable caching with @EnableCaching and use @Cacheable:

java

@Cacheable("products")

public Product getProduct(Long id) {

return productRepository.findById(id);

Configure cache providers like Redis or Ehcache6.

117. How do you deploy Spring Boot to Docker?

Create a Dockerfile:

text

FROM openjdk:17-jdk-slim
Copyright © 2025 by SkillForgePrep
COPY target/app.jar app.jar

ENTRYPOINT ["java","-jar","/app.jar"]

Build with docker build -t spring-app . and run with docker run -p 8080:8080
spring-app8.

118. What is Spring Boot’s @Async?

It executes methods asynchronously:

java

@Async

public CompletableFuture<User> fetchUser(Long id) {

// Async logic

Enable with @EnableAsync and configure a ThreadPoolTaskExecutor6.

119. How do you handle XML responses in Spring Boot?

Add jackson-dataformat-xml and use @RestController:

java

@GetMapping(value = "/user", produces =


MediaType.APPLICATION_XML_VALUE)

public User getUser() {

Copyright © 2025 by SkillForgePrep


return userService.getUser();

120. Explain Spring Boot’s @RestControllerAdvice.

It handles exceptions globally for REST controllers:

java

@RestControllerAdvice

public class GlobalExceptionHandler {

@ExceptionHandler(ResourceNotFoundException.class)

public ResponseEntity<Error>
handleNotFound(ResourceNotFoundException ex) {

return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new
Error(ex.getMessage()));

Copyright © 2025 by SkillForgePrep


122 Intermediate and Advanced Spring Boot
Interview Questions and Answers
This comprehensive guide provides 122 intermediate and advanced Spring Boot interview
questions with expert answers to help you prepare for technical interviews. These questions
build on fundamental knowledge and explore more complex aspects of Spring Boot
development.

1. How does Spring Boot's auto-configuration


prioritization work?
Auto-configuration classes in Spring Boot follow a specific order of precedence. They use
@AutoConfigureOrder and @AutoConfigureBefore/@AutoConfigureAfter annotations to
establish relationships between configurations. The framework first processes user-defined
beans (from @Configuration classes), then applies auto-configuration beans only when needed.
This ensures that explicit configurations always take precedence over automatic ones, while
maintaining dependency relationships between various auto-configurations.

2. What is the Spring Boot bootstrap process in detail?


The Spring Boot bootstrap process follows these steps: First, the SpringApplication class is
instantiated, which sets up the bootstrapping process. It then creates the appropriate
ApplicationContext based on the application type (servlet, reactive, or standard). Next, it loads
ApplicationContextInitializers from META-INF/spring.factories. The application then prepares the
environment, including property sources and profiles. After this, the ApplicationContext is
refreshed, triggering the auto-configuration process. Finally, any CommandLineRunner or
ApplicationRunner beans are executed before the application becomes ready.

3. How can you customize the Spring Boot banner?


You can customize the Spring Boot banner by creating a banner.txt file in the
src/main/resources directory. Alternatively, you can set the spring.banner.location property to
point to a custom banner file, or use spring.banner.image.location for image banners. For
programmatic customization, you can set a Banner implementation on the SpringApplication
instance or disable the banner entirely with setShowBanner(false) or
spring.main.banner-mode=off in properties.

4. What is Spring Boot's condition evaluation delta


report?
Copyright © 2025 by SkillForgePrep
The condition evaluation delta report is a diagnostic tool that shows why auto-configuration
conditions were matched or not matched. It helps troubleshoot configuration issues by
displaying which auto-configuration classes were included or excluded and why. You can enable
it by setting the logging level for org.springframework.boot.autoconfigure.condition to DEBUG or
by adding --debug as a command-line argument when starting the application.

5. What is a Spring Boot FailureAnalyzer and how would


you implement a custom one?
A FailureAnalyzer is a component that intercepts exceptions during application startup and
converts them into human-readable messages. To create a custom FailureAnalyzer, implement
the FailureAnalyzer interface, analyze specific exceptions, and return a FailureAnalysis object
with a description, cause, and action. Then register it in META-INF/spring.factories under the
org.springframework.boot.diagnostics.FailureAnalyzer key. This helps provide more meaningful
error messages for specific application failure scenarios.

6. How does Spring Boot handle circular dependencies?


Spring Boot, like Spring Framework, detects circular dependencies during context initialization.
For constructor injection, circular dependencies result in a BeanCurrentlyInCreationException
because beans cannot be partially initialized. For setter injection, Spring resolves circular
dependencies by creating proxies. You can set spring.main.allow-circular-references=true to
force Spring to resolve circular dependencies using proxies, but this is generally discouraged as
circular dependencies often indicate design issues.

7. What are the limitations of Spring Boot's


auto-configuration?
Auto-configuration has several limitations: it may create unnecessary beans in complex
applications; debugging can be challenging as configurations are applied implicitly; it may not
cover all edge cases for third-party integrations; there might be configuration conflicts when
multiple auto-configurations try to configure the same component; and some configurations
might be opinionated, requiring explicit overrides for custom behavior.

8. What is the difference between @Bean and


@Component annotations?
While both create Spring-managed beans, @Component is a class-level annotation that
automatically registers a class as a bean through component scanning. @Bean is a
method-level annotation used in @Configuration classes to explicitly declare a bean. @Bean

Copyright © 2025 by SkillForgePrep


gives more control over bean creation and configuration, allows returning different instances
based on conditions, and is often used for third-party classes that you don't own. @Component
is simpler but offers less control and can only be used on your own classes.

9. How does Spring Boot's property binding work with


complex structures and collections?
Spring Boot can bind properties to complex structures including nested objects, maps, lists, and
sets. For nested properties, use dot notation (e.g., person.address.city=Boston). For lists, use
indexed notation (e.g., my.list=value) or comma-separated values. For maps, use bracketed or
dot notation (my.map[key]=value or my.map.key=value). When combined with
@ConfigurationProperties, Spring Boot automatically converts property values to appropriate
types and creates the necessary structure.

10. What is a Spring Boot BuilderCustomizer and how


would you use one?
A BuilderCustomizer is an interface used to customize various builder components in Spring
Boot. For example, a SpringApplicationBuilderCustomizer allows customization of the
SpringApplicationBuilder before the application is built. You implement the customize method to
modify the builder's behavior. This pattern is used internally in Spring Boot and is also available
for extensions. For instance, you might use a TomcatServletWebServerFactoryCustomizer to
customize Tomcat server settings programmatically.

11. How can you implement hierarchical property sources


in Spring Boot?
Hierarchical property sources can be implemented by creating custom PropertySourceLocators
and registering them with the ConfigurationPropertiesBindingPostProcessor. Alternatively, you
can use Spring Cloud Config for a robust solution. You can also programmatically add
PropertySources to the Environment with different precedence levels using
environment.getPropertySources().addFirst() or addLast() methods. This allows organizing
configurations in parent-child relationships with appropriate override capabilities.

12. What are configuration trees in Spring Boot and how


do they work?
Configuration trees in Spring Boot allow binding hierarchical configurations to Java objects. You
can use the @NestedConfigurationProperty annotation or the @ConfigurationProperties
annotation with a prefix to create nested structures. The properties are organized in a tree-like
Copyright © 2025 by SkillForgePrep
structure, where properties can override their parent values based on specificity. This is
particularly useful for organizing related configurations logically while maintaining separation of
concerns.

13. How do you create type-safe configuration properties


with validation?
To create type-safe configuration properties with validation, create a POJO annotated with
@ConfigurationProperties(prefix="myapp") and @Validated. Then add validation constraints
using Bean Validation annotations like @NotNull, @Min, or @Pattern. Register the configuration
class with @EnableConfigurationProperties or by annotating it with @Component. Spring Boot
will automatically bind properties with the specified prefix to this class and validate them during
binding.

14. How does Spring Boot handle property encryption


and sensitive data?
Spring Boot doesn't provide built-in property encryption, but you can implement it using the
Jasypt library with spring-boot-jasypt or Spring Cloud Config with encryption/decryption
capabilities. For sensitive data, you can use environment variables, external credential stores,
or vault solutions like HashiCorp Vault or AWS Secrets Manager. Spring Boot 2.4+ also supports
config data encryption providers that can decrypt properties during the environment preparation
phase.

15. What is the difference between @PropertySource and


@ConfigurationProperties?
@PropertySource loads properties from a specific file into Spring's Environment but doesn't
bind them directly to beans. It's typically used with @Value annotations.
@ConfigurationProperties binds entire groups of properties to structured objects with relaxed
binding and type conversion. @PropertySource is more suitable for simple property injection,
while @ConfigurationProperties offers better organization, validation, and type safety for
complex configuration structures.

16. How can you implement dynamic configuration


reloading in Spring Boot?
Dynamic configuration reloading can be implemented using Spring Cloud Config with the
@RefreshScope annotation and the /actuator/refresh endpoint. Alternatively, you can create a
custom solution using file watchers (like WatchService) to monitor configuration changes, and
Copyright © 2025 by SkillForgePrep
implement ApplicationListeners to update beans when configurations change. For
database-stored configurations, you can use scheduled tasks to periodically check for updates
and refresh affected components.

17. What are Spring Boot's configuration file hierarchies


and their precedence?
Spring Boot loads configuration in this order (from highest to lowest precedence):
Command-line arguments, JNDI attributes, Java System properties, OS environment variables,
random values, application-{profile}.properties/yml outside of the packaged application,
application-{profile}.properties/yml packaged inside the application, application.properties/yml
outside the packaged application, application.properties/yml packaged inside the application,
and @PropertySource annotations on @Configuration classes. Additionally, profile-specific files
take precedence over non-profile files.

18. How does Spring Boot handle YAML configuration


internally?
Spring Boot uses SnakeYAML library to parse YAML files. The YamlPropertySourceLoader
converts YAML documents into PropertySource objects. Multi-document YAML files are
processed sequentially, with later documents overriding earlier ones. YAML's hierarchical
structure is flattened into key-value pairs using dot notation. Spring Boot also supports lists,
maps, and type conversion from YAML syntax to Java types. YAML files can include profiles
using the spring.profiles key for conditional configuration activation.

19. What is ConfigurationCondition and how does it differ


from Condition?
ConfigurationCondition extends the basic Condition interface by adding a ConfigurationPhase
that specifies when the condition should be evaluated. The two phases are
PARSE_CONFIGURATION (during @Configuration class parsing, before bean definitions are
created) and REGISTER_BEAN (when beans are being registered). This allows more precise
control over when conditions are checked, which is crucial for conditions that depend on bean
registry state or need to influence the parsing process itself.

20. How can you create environment-specific beans


beyond profiles?
Beyond profiles, you can create environment-specific beans using conditional annotations:
@ConditionalOnProperty to check specific property values, @ConditionalOnExpression to use
Copyright © 2025 by SkillForgePrep
SpEL expressions for complex conditions, @ConditionalOnJava to check Java versions, or
@ConditionalOnResource to check for resource availability. You can also implement custom
Condition classes for sophisticated logic, or use factory methods that programmatically decide
which implementation to instantiate based on the Environment.

21. What is the difference between @WebMvcTest and


@SpringBootTest?
@WebMvcTest loads only the web layer components (controllers, filters, etc.) and provides a
MockMvc instance for testing HTTP requests without starting a server. It's focused on testing
MVC components in isolation. @SpringBootTest loads the full application context (or a slice with
specific configuration), can start an actual server with @AutoConfigureMockMvc or
TestRestTemplate for integration testing. @WebMvcTest is faster and more focused, while
@SpringBootTest provides more comprehensive integration testing.

22. How do you test Spring Boot applications with a real


database?
To test with a real database, you can use @SpringBootTest with a test-specific
application.properties file pointing to a test database. Alternatively, use @TestPropertySource to
override datasource properties, or @AutoConfigureTestDatabase to configure a replacement.
For integration testing, you might use Testcontainers to spin up a real database instance in a
Docker container. Combine with @Sql for test data setup and @Transactional to rollback
changes between tests.

23. What is @DirtiesContext and when should you use it?


@DirtiesContext signals that the test modifies the ApplicationContext and it should be closed
and rebuilt for subsequent tests. Use it when tests change bean definitions, modify bean
behavior in ways that affect other tests, or alter static state. It can target the class level (all
methods), specific methods, or specific class modes (BEFORE_CLASS, AFTER_CLASS,
BEFORE_EACH_TEST_METHOD, AFTER_EACH_TEST_METHOD). However, it's costly for
performance, so use it judiciously and consider designing tests to avoid context pollution
instead.

24. How do you test Spring Boot WebFlux applications?


To test Spring Boot WebFlux applications, use @WebFluxTest for controller tests with
WebTestClient. For end-to-end testing, use @SpringBootTest with WebTestClient. Test reactive
repositories with @DataMongoTest or @DataR2dbcTest. Use StepVerifier from reactor-test to
verify reactive sequences step-by-step. For testing with backpressure and virtual time, use

Copyright © 2025 by SkillForgePrep


TestPublisher and VirtualTimeScheduler. Always ensure proper handling of subscriptions and
test both success and error flows.

25. What are MockBean and SpyBean in Spring Boot


tests?
@MockBean creates a Mockito mock of a bean and replaces any existing bean of the same
type in the ApplicationContext. It's useful for isolating components by mocking their
dependencies. @SpyBean creates a Mockito spy, wrapping an existing bean while allowing you
to override specific methods. Both support Mockito's when/then stubbing and verify methods.
Use @MockBean when you need complete control over dependency behavior and @SpyBean
when you want to keep the original behavior but monitor or override specific methods.

26. How do you test Spring Boot Actuator endpoints?


To test Spring Boot Actuator endpoints, you can use @WebMvcTest or @WebFluxTest with
@Import(EndpointConfiguration.class) for specific endpoints. For testing custom endpoints,
include your endpoint class in the test. Use MockMvc or WebTestClient to make requests to
/actuator/{endpoint}. For security-enabled endpoints, use @WithMockUser or configure test
security. You can also use @SpringBootTest with TestRestTemplate or WebTestClient for full
integration testing of actuator endpoints.

27. What is the role of @TestConfiguration in Spring


Boot?
@TestConfiguration is used to define additional beans or override existing ones specifically for
tests without affecting the main application configuration. Unlike regular @Configuration
classes, @TestConfiguration-annotated inner classes are not picked up by component scanning
automatically. They must be explicitly imported using @Import or registered with
@ContextConfiguration. This allows you to provide test-specific beans, mock dependencies, or
configuration properties that should only apply in the testing environment.

28. How would you test asynchronous behavior in Spring


Boot?
To test asynchronous behavior, use @EnableAsync in test configuration and leverage the
Spring test framework's support for awaitility. You can use awaits().until() methods to wait for
asynchronous operations to complete. For more control, inject AsyncTaskExecutor and use
countDownLatch patterns. For @Scheduled methods, you might need to trigger them manually

Copyright © 2025 by SkillForgePrep


in tests. For CompletableFuture results, use join() or get() with appropriate timeouts. Always
include assertions to verify the expected state after async operations complete.

29. What are slice tests in Spring Boot and how do they
work?
Slice tests in Spring Boot load only a specific "slice" of the application context to test a particular
layer in isolation. Examples include @WebMvcTest (web layer), @DataJpaTest (persistence
layer), @JsonTest (JSON serialization), and @RestClientTest (REST clients). Each slice
auto-configures the minimum required components for testing that slice while mocking or
disabling other components. This approach speeds up tests by loading only what's necessary
and allows focused testing of individual architectural layers.

30. How can you test custom auto-configurations in


Spring Boot?
To test custom auto-configurations, use @ImportAutoConfiguration to explicitly import your
auto-configuration class. Create test scenarios that verify the conditions under which your
auto-configuration should be applied or skipped. Use ApplicationContextRunner or
WebApplicationContextRunner to programmatically set up different application contexts and
assert the presence or absence of expected beans. Test both the positive case (configuration
applies) and negative cases (configuration is skipped due to conditions) to ensure proper
behavior.

31. How does Spring Boot's transaction management


work behind the scenes?
Spring Boot's transaction management is built on Spring's declarative transaction support.
When @EnableTransactionManagement is detected (auto-configured by
spring-boot-starter-data-*), Spring creates a TransactionInterceptor that intercepts methods
marked with @Transactional. This interceptor creates, commits, or rolls back transactions using
a PlatformTransactionManager (automatically configured based on your datasource).
Proxy-based AOP is used to wrap @Transactional beans, which is why self-invocation doesn't
trigger transaction management.

32. What is the difference between JdbcTemplate and


NamedParameterJdbcTemplate?
JdbcTemplate is Spring's core JDBC abstraction that uses indexed parameters (?) in SQL
queries, while NamedParameterJdbcTemplate extends this functionality to support named
Copyright © 2025 by SkillForgePrep
parameters (:paramName) in SQL statements. NamedParameterJdbcTemplate provides better
readability and maintainability for complex queries, eliminates parameter position errors, and
accepts Maps or SqlParameterSource objects for parameter values. Under the hood, it
transforms named parameters back to the standard JDBC positional parameters.

33. How can you configure multiple data sources in


Spring Boot?
To configure multiple data sources, define separate @Bean methods for each DataSource,
EntityManagerFactory (for JPA), and TransactionManager with appropriate qualifiers. Use
@Primary for the default source. Configure each datasource with its own properties
(spring.datasource.primary.* and spring.datasource.secondary.*). For JPA, use
@EnableJpaRepositories with basePackages and entityManagerFactoryRef attributes to
associate repositories with the correct EntityManagerFactory. Create separate @Configuration
classes for clean separation of concerns.

34. What is the Repository design pattern and how does


Spring Data implement it?
The Repository pattern mediates between the domain and data mapping layers, acting like an
in-memory collection of domain objects. Spring Data implements this through a hierarchy of
interfaces (Repository, CrudRepository, PagingAndSortingRepository, etc.) where you define
method signatures following a naming convention. Spring Data generates the implementation at
runtime using proxies. It translates method names into queries, handles transactions, converts
between domain and database representations, and provides consistent exception translation
across different data stores.

35. How do you handle database migrations in Spring


Boot?
Database migrations in Spring Boot are typically handled using Flyway or Liquibase, both of
which have Spring Boot auto-configurations. With Flyway, place SQL migration scripts in
resources/db/migration named V1__init.sql, V2__add_columns.sql, etc. For Liquibase, create a
changelog in resources/db/changelog using XML, YAML, or JSON. Configure the migration tool
via spring.flyway.* or spring.liquibase.* properties. Migrations run automatically at startup,
ensuring database schema consistency across all environments.

36. What is the difference between FetchType.EAGER and


FetchType.LAZY in JPA?

Copyright © 2025 by SkillForgePrep


FetchType.EAGER loads associated entities immediately when the parent entity is loaded,
ensuring data is available but potentially retrieving unnecessary data and causing performance
issues with large object graphs. FetchType.LAZY loads associated entities only when explicitly
accessed (on-demand), improving initial query performance but potentially causing
LazyInitializationException if accessed outside a transaction. Spring Boot configures appropriate
transaction management and entity managers to support both strategies, but LAZY is generally
recommended as the default approach.

37. How does Spring Boot handle connection pooling?


Spring Boot automatically configures a connection pool when a pooling library is detected on the
classpath. By default, it uses HikariCP (the fastest and most reliable option), falling back to
Tomcat pooling or Apache DBCP2 if HikariCP is not available. The pool is configured with
sensible defaults, but can be customized through spring.datasource.hikari.* properties (or
equivalent for other providers). The pool manages connections efficiently, improving
performance by reusing connections rather than repeatedly establishing new ones.

38. What are projections in Spring Data and when would


you use them?
Projections in Spring Data allow retrieving partial entities or custom data structures instead of
complete entities. Interface-based projections define methods matching property names, while
class-based projections use constructors. Closed projections (concrete property methods) are
more performant as Spring can optimize the query. Open projections (with @Value expressions)
offer more flexibility. Projections are useful when you need only specific fields from entities,
reducing network traffic and improving performance, especially in complex domain models.

39. How do you implement optimistic locking in Spring


Boot applications?
Implement optimistic locking by adding a version field to your entity annotated with @Version.
Spring Data JPA automatically increments this version on each update and checks it during
transactions, throwing an OptimisticLockingFailureException if the version has changed since
the entity was read. To handle conflicts, you can either catch the exception and implement a
retry mechanism or use Spring Retry with @Retryable annotation. This prevents concurrent
updates from overwriting each other without the overhead of pessimistic locking.

40. What are the benefits and drawbacks of using Spring


Data's specifications and query DSL?

Copyright © 2025 by SkillForgePrep


Benefits of specifications and query DSL include type-safe queries that catch errors at compile
time, improved readability compared to string-based JPQL, composable criteria for complex
queries, and abstraction over the underlying data store. Drawbacks include a steeper learning
curve, potential performance overhead for very simple queries, generation of less optimized
SQL in some complex scenarios, and additional dependencies. They shine in applications with
complex dynamic querying requirements but might be overkill for simple CRUD operations.

41. How does Spring Security's filter chain work in a


Spring Boot application?
Spring Security in Spring Boot works by inserting a chain of servlet filters into the application's
filter chain. The DelegatingFilterProxy delegates to a FilterChainProxy, which contains multiple
SecurityFilterChain instances. Each chain has filters for authentication, authorization, exception
handling, etc., applied in a specific order. When a request arrives, filters process it sequentially:
authentication filters verify the user's identity, authorization filters check permissions, and other
filters handle CSRF protection, session management, and more.

42. What is the difference between authentication and


authorization in Spring Security?
Authentication verifies who the user is by validating credentials against a store (database,
LDAP, OAuth provider, etc.) and creates an Authentication object in the SecurityContext.
Authorization determines what the authenticated user can do by checking permissions against
security rules defined with annotations like @PreAuthorize or HttpSecurity configuration.
Authentication happens first, establishing identity, while authorization follows, controlling access
based on that identity. Spring Security separates these concerns with distinct components:
AuthenticationManager and AccessDecisionManager.

43. How would you implement method-level security with


custom expressions?
To implement method-level security with custom expressions, first enable it with
@EnableGlobalMethodSecurity(prePostEnabled=true). Then create a bean that extends
SecurityExpressionRoot and implements MethodSecurityExpressionOperations to define
custom expressions. Register this bean with a MethodSecurityExpressionHandler
implementation. Finally, use your custom expressions in @PreAuthorize or @PostAuthorize
annotations: @PreAuthorize("@mySecurityBean.canAccessResource(authentication, #id)").
This allows highly specific, context-aware security rules that consider both user identity and
method parameters.

Copyright © 2025 by SkillForgePrep


44. What is the SecurityContext and how is it managed
across threads?
SecurityContext holds the Authentication object representing the current user. By default, it's
stored in a ThreadLocal variable managed by SecurityContextHolder. This makes it available
throughout the current thread but not to child threads. For applications using async processing
or thread pools, use the SecurityContextHolder.MODE_INHERITABLETHREADLOCAL strategy
or explicitly copy the context to new threads. In web applications,
SecurityContextPersistenceFilter saves/loads the context between requests, with session-based
persistence as the default strategy.

45. How would you implement a custom


AuthenticationProvider?
To implement a custom AuthenticationProvider, create a class that implements the
AuthenticationProvider interface with two key methods: authenticate() (performs authentication
logic and returns a populated Authentication object if successful) and supports() (determines if
this provider can handle the Authentication type). Register your provider with the
AuthenticationManagerBuilder either through a WebSecurityConfigurerAdapter or by exposing it
as a @Bean. This approach allows custom authentication mechanisms like API key
authentication, one-time passwords, or integration with proprietary identity systems.

46. What are the best practices for password storage in


Spring Boot applications?
Best practices for password storage include using Spring Security's PasswordEncoder interface,
with modern implementations like BCryptPasswordEncoder, Pbkdf2PasswordEncoder, or
SCryptPasswordEncoder. Never store passwords in plain text or use simple hashing algorithms
(MD5/SHA). Use password encoders with adaptive hashing that incorporate salt automatically
and support work factors that can be increased over time. Consider using
DelegatingPasswordEncoder to support multiple encoding algorithms simultaneously, which
helps with migrations and evolving security standards.

47. How does Spring Security's CSRF protection work?


Spring Security's CSRF protection works by generating a unique token per session and
requiring this token in all state-changing requests (POST, PUT, DELETE). The token is typically
included as a hidden form field or custom HTTP header. CsrfFilter validates that incoming
requests contain a token matching the one stored in the session, rejecting requests with missing
or invalid tokens. This prevents attackers from tricking users into submitting unwanted requests.

Copyright © 2025 by SkillForgePrep


For RESTful APIs with non-browser clients, CSRF protection is often disabled as it's
unnecessary.

48. What are the security implications of using JWT with


Spring Boot?
JWT usage in Spring Boot has several security implications: tokens can't be invalidated before
expiration unless you implement a blacklist mechanism; sensitive information in tokens (even
when encrypted) may be exposed; token size increases with claims, affecting network
performance; signature validation is crucial to prevent tampering; and proper expiration times
balance security and user experience. Use jjwt or nimbus-jose-jwt libraries, store only necessary
claims, implement token refresh mechanisms, and consider token rotation for sensitive
operations.

49. How would you implement OAuth2 resource server


with JWT validation?
To implement an OAuth2 resource server with JWT validation in Spring Boot, add the
spring-security-oauth2-resource-server dependency and configure the JWT issuer URI and JWK
Set URI in application.properties. Then configure security to use OAuth2 resource server with
JWT: .oauth2ResourceServer().jwt(). For custom validation, implement a
JwtAuthenticationConverter to extract authorities from claims. Use @EnableResourceServer in
older versions or just standard Spring Security configuration in newer ones. This validates
tokens against the authorization server's public keys.

50. How do you secure WebSocket connections in Spring


Boot?
Secure WebSocket connections by configuring Spring Security for your SockJS and STOMP
endpoints. Override configureMessageBroker() in a class extending
AbstractSecurityWebSocketMessageBrokerConfigurer to secure message destinations. Use
interceptors like ChannelInterceptor to authenticate STOMP headers or messages. Apply
@PreAuthorize on controller methods that handle socket subscriptions. Implement custom
authentication with AuthorizationManager for message channels and subscriptions. Always use
HTTPS for the underlying HTTP connection to prevent man-in-the-middle attacks on the initial
WebSocket handshake.

Copyright © 2025 by SkillForgePrep


51. What is the role of Spring Cloud in a Spring Boot
microservices architecture?
Spring Cloud provides tools for common microservice patterns in Spring Boot applications. It
offers service discovery (Eureka, Consul), client-side load balancing (Ribbon, Spring Cloud
LoadBalancer), API gateway (Spring Cloud Gateway, Zuul), distributed configuration (Config
Server), circuit breakers (Resilience4j, Hystrix), and distributed tracing (Sleuth, Zipkin). Spring
Cloud abstracts the complexities of building distributed systems, allowing developers to focus
on business logic while providing resilient communication between services, centralized
configuration management, and observability across the entire system.

52. How does service discovery work in Spring Boot


microservices?
Service discovery in Spring Boot microservices typically uses Netflix Eureka or Consul. Services
register themselves with the discovery server on startup, providing their host, port, and service
ID. Clients query the discovery server to locate services by ID rather than using hardcoded
URLs. With @EnableDiscoveryClient annotation and spring-cloud-starter-netflix-eureka-client
dependency, services automatically register and can locate others using load-balanced
RestTemplate or WebClient with @LoadBalanced annotation or directly through
DiscoveryClient. This enables dynamic scaling and prevents configuration changes when
service instances change.

53. What is the Circuit Breaker pattern and how is it


implemented in Spring Boot?
The Circuit Breaker pattern prevents cascading failures by wrapping remote service calls in a
circuit breaker object that monitors failures. When failures exceed a threshold, the circuit
"opens," failing fast without attempting the call. After a timeout, the circuit "half-opens" to test if
the service has recovered. In Spring Boot, this is implemented using Resilience4j or Hystrix
(legacy). With Spring Cloud Circuit Breaker, you can annotate methods with @CircuitBreaker or
use a CircuitBreakerFactory for programmatic usage. This improves system resilience by
isolating failures and providing fallbacks.

54. How would you implement distributed tracing in


Spring Boot microservices?
Implement distributed tracing in Spring Boot microservices using Spring Cloud Sleuth and
Zipkin. Add spring-cloud-starter-sleuth and spring-cloud-sleuth-zipkin dependencies to each
microservice. Sleuth automatically adds trace and span IDs to request headers and logs.

Copyright © 2025 by SkillForgePrep


Configure spring.zipkin.baseUrl to point to your Zipkin server. For manual instrumentation, use
the Tracer bean to create custom spans. Additional sampling configuration can control how
many traces are collected. This creates a complete picture of request flow across multiple
services, making it easier to diagnose performance issues and failures.

55. What are the challenges of implementing transactions


across microservices?
Implementing transactions across microservices is challenging because traditional ACID
transactions don't scale in distributed systems. Challenges include: maintaining data
consistency without distributed transactions; handling partial failures; ensuring eventual
consistency; dealing with different databases in different services; and managing compensating
transactions for rollbacks. Solutions include using the Saga pattern (choreography or
orchestration-based), event-driven architectures with idempotent operations, the outbox pattern
for reliable event publishing, and implementing eventual consistency with appropriate business
logic to handle temporary inconsistencies.

56. How do you handle API versioning in Spring Boot


microservices?
API versioning in Spring Boot microservices can be implemented through: URL path versioning
(/api/v1/resource), request parameter versioning (?version=1), custom header versioning
(X-API-Version: 1), content negotiation (Accept: application/vnd.company.app-v1+json), or a
combination of these approaches. With Spring MVC, use @RequestMapping to route to
different controller implementations or methods. For evolutionary changes, consider using API
expansion techniques like optional fields rather than creating entirely new versions. Document
all versions clearly with tools like SpringDoc OpenAPI or Swagger.

57. What is the API Gateway pattern and how does Spring
Cloud Gateway implement it?
The API Gateway pattern provides a single entry point for all client requests to a microservices
system, handling cross-cutting concerns like routing, filtering, security, and monitoring. Spring
Cloud Gateway implements this using a reactive, non-blocking architecture built on Spring
WebFlux. It routes requests based on predicates (conditions about the request) and applies
filters (to modify requests/responses). Gateway features include path-based routing, load
balancing, circuit breaking via Resilience4j, rate limiting, path rewriting, and request/response
modification. This centralizes common functionality and shields clients from internal service
composition.

Copyright © 2025 by SkillForgePrep


58. How do you implement centralized configuration
management in Spring Boot microservices?
Centralized configuration management is implemented with Spring Cloud Config. Create a
Config Server application with @EnableConfigServer and point it to a Git repository containing
configuration files. Microservices include the config client dependency and bootstrap from the
server on startup. Use spring.application.name to identify which configuration to load. For
dynamic reconfiguration, implement @RefreshScope on beans and trigger refresh via
/actuator/refresh endpoint or Spring Cloud Bus for coordinated refreshes across instances. This
ensures consistent configuration across services and environments with version control
benefits.

59. How would you design event-driven microservices


with Spring Boot?
Design event-driven microservices with Spring Boot using Spring Cloud Stream or Spring for
Apache Kafka. Define service interfaces using functional programming models with producer
and consumer methods. Use message brokers like RabbitMQ or Kafka as the communication
backbone. Implement idempotent consumers to handle duplicate events. Consider the outbox
pattern for reliable event publishing. Use event sourcing where appropriate to maintain history.
Leverage Spring Integration for complex routing scenarios. This approach decouples services,
improves scalability, and enables asynchronous processing while maintaining system resilience
through temporal decoupling.

60. What are the patterns for handling data consistency in


microservices?
Data consistency patterns in microservices include: Saga pattern for coordinating transactions
across services through events or orchestration; Event Sourcing to capture all state changes as
events; CQRS to separate read and write operations; the Outbox pattern for reliable event
publishing; Database-per-service to maintain clear boundaries; and Materialized Views for read
optimization. Each service should own its data exclusively, with other services accessing it only
through APIs. For queries spanning multiple services, consider API composition, CQRS with
denormalized views, or domain events to maintain eventually consistent projections.

61. How would you create a custom health indicator in


Spring Boot Actuator?
To create a custom health indicator, implement the HealthIndicator interface or extend
AbstractHealthIndicator class. Override the health() or doHealthCheck() method to perform your

Copyright © 2025 by SkillForgePrep


health check logic and return a Health object with status and details. Register the
implementation as a Spring bean, and it will automatically be included in the health endpoint
results. For example, a database connection health check or a third-party service dependency
check can be implemented this way. The status will aggregate up to the overall application
health status.

java
@Component
public class ExternalServiceHealthIndicator extends
AbstractHealthIndicator {
@Override
protected void doHealthCheck(Health.Builder builder) throws
Exception {
try {
// Check external service health
if (isExternalServiceUp()) {
builder.up().withDetail("service", "External Service
is responding normally");
} else {
builder.down().withDetail("service", "External Service
is not responding");
}
} catch (Exception e) {
builder.down().withDetail("error", e.getMessage());
}
}
}

62. How can you expose custom metrics in Spring Boot


applications?
Custom metrics can be exposed using Micrometer API, which Spring Boot Actuator uses as its
metrics facade. Inject a MeterRegistry bean and register various metric types: Counter for
incrementing values, Gauge for current values, Timer for latencies, DistributionSummary for
distributions with min/max/percentiles, or LongTaskTimer for long-running tasks. Tag metrics
with dimensions for better categorization. These metrics are automatically exposed via the
/actuator/prometheus endpoint in Prometheus format or can be viewed via
/actuator/metrics/{metric.name}. Micrometer abstracts the underlying monitoring system,
supporting Prometheus, Datadog, New Relic, etc.

Copyright © 2025 by SkillForgePrep


63. What is the Spring Boot Admin project and how does
it work?
Spring Boot Admin is a web application that provides a UI to manage and monitor Spring Boot
applications. It works with a server-client architecture: the server component is a Spring Boot
application with @EnableAdminServer annotation, while clients are regular Spring Boot
applications with spring-boot-admin-starter-client dependency. Clients register with the server
via HTTP, sending their actuator endpoints. The server polls these endpoints to collect metrics,
health statuses, and other information, displaying them in a dashboard. It offers features like
environment modification, JVM metrics visualization, log level adjustments, and notifications for
status changes.

64. How would you secure Spring Boot Actuator


endpoints in a production environment?
In production, secure Actuator endpoints by first restricting which endpoints are exposed with
management.endpoints.web.exposure.include/exclude properties. Change the
management.server.port to separate application and management traffic. Implement Spring
Security with role-based access control for endpoints-typically requiring ACTUATOR or ADMIN
roles. Use HTTPS for all communications. Consider placing actuator endpoints behind a
separate load balancer with restricted access. For sensitive endpoints like /env, /heapdump, and
/shutdown, either disable them completely or implement strict security policies with specific IP
allowlisting and multi-factor authentication.

65. What is the purpose of info and health contributors in


Spring Boot Actuator?
Info and health contributors in Spring Boot Actuator provide extensible mechanisms for
exposing application information and health status. InfoContributor implementations supply data
for the /actuator/info endpoint, offering details like application version, git commit information,
build details, or custom business information. HealthContributor implementations feed into the
/actuator/health endpoint, representing individual components' health status. Spring Boot
provides built-in contributors (e.g., DiskSpaceHealthIndicator), but you can add custom ones to
expose business-specific health indicators or informational metadata that help with monitoring
and troubleshooting.

66. How can you collect and analyze metrics from Spring
Boot applications?

Copyright © 2025 by SkillForgePrep


Collect and analyze metrics by leveraging Spring Boot Actuator with Micrometer, which exposes
metrics in various formats. Configure Prometheus endpoint (/actuator/prometheus) and set up
Prometheus server to scrape these metrics. Visualize data using Grafana dashboards. For
distributed systems, implement distributed tracing with Spring Cloud Sleuth and Zipkin. Use ELK
stack (Elasticsearch, Logstash, Kibana) for log aggregation and analysis. For advanced APM,
integrate commercial solutions like Dynatrace or New Relic using their Micrometer registries.
Set up alerts on key metrics like response times, error rates, and resource utilization.

67. What is the difference between health indicators and


readiness/liveness probes?
Health indicators in Spring Boot Actuator provide application health status through the
/actuator/health endpoint, covering various subsystems like databases, disk space, and custom
components. Readiness and liveness probes are Kubernetes concepts: liveness probes
determine if an application should be restarted (is it alive?), while readiness probes determine if
an application should receive traffic (is it ready to serve?). Spring Boot 2.3+ bridged these
concepts with dedicated /actuator/health/liveness and /actuator/health/readiness endpoints,
allowing different health indicator groups to contribute to each probe type for more precise
container orchestration.

68. How would you implement custom audit events in


Spring Boot?
Implement custom audit events by using Spring Boot's built-in audit mechanism. Create custom
AuditEvent classes by extending Spring Security's AuditEvent. Publish events using the
ApplicationEventPublisher or the AuditEventRepository directly. To persist events, implement a
custom AuditEventRepository that stores events in your preferred data store (database, log
system, etc.). You can listen to these events using @EventListener annotations on methods.
This approach provides a standardized way to track security-related or business-important
actions in your application for compliance, security analysis, or operational insights.

69. What monitoring patterns should you implement in a


microservices architecture?
In a microservices architecture, implement these monitoring patterns: centralized logging with
log correlation IDs (using ELK stack or Graylog); distributed tracing (with Sleuth and Zipkin) to
track requests across services; health checking with Spring Boot Actuator; metrics collection
with Prometheus and visualization with Grafana; centralized monitoring dashboards showing
system-wide state; automated alerting based on thresholds; service dependency mapping to
understand impact chains; and chaos engineering practices to verify monitoring effectiveness.

Copyright © 2025 by SkillForgePrep


Additionally, implement circuit breaker metrics monitoring to track system resilience and request
rate/error dashboards to identify problematic services.

70. How do you implement log correlation in distributed


Spring Boot applications?
Implement log correlation by adding Spring Cloud Sleuth to your services. It automatically adds
trace and span IDs to each request and annotates log messages with these IDs. Configure a
consistent logging format across all services that includes these IDs. Use a centralized logging
system like ELK stack or Graylog to aggregate logs. Configure your logging appenders to
include the trace ID in every log message using the %X{traceId} and %X{spanId} MDC variables
in your log pattern. This allows reconstructing the complete request flow across multiple
services by filtering logs with the same trace ID.

71. How would you optimize the startup time of a Spring


Boot application?
To optimize Spring Boot startup time: use lazy initialization with
spring.main.lazy-initialization=true; limit component scanning with specific package paths; use
Spring Boot 2.3+ functional bean registration instead of @ComponentScan; enable background
initialization with spring.main.background-preinitializer=true; apply the hint-based AOT engine
(Spring Boot 3.x); consider native compilation with GraalVM native-image; disable JMX with
spring.jmx.enabled=false; and avoid classpath scanning in JARs with
spring.main.cloud-platform=none when cloud platforms aren't used. Additionally, use
spring.main.banner-mode=off to disable the startup banner and minimize dependencies to
essential ones.

72. What is the significance of bean scope selection for


application performance?
Bean scope selection significantly impacts performance. Singleton-scoped beans (default) are
instantiated once per container, optimizing memory usage and startup time, with negligible
retrieval costs. Prototype-scoped beans create new instances on each retrieval, increasing
memory usage and garbage collection pressure. Request/session scopes in web applications
create instances per HTTP request/session, potentially causing high object churn. Choose
singleton scope whenever possible, especially for stateless services. Use prototypes only when
necessary for mutable state, and consider thread-safety mechanisms like ThreadLocal or
proxies when thread-safe behavior is required with non-singleton scopes.

Copyright © 2025 by SkillForgePrep


73. How do you implement caching in Spring Boot
applications?
Implement caching in Spring Boot by adding spring-boot-starter-cache and a cache provider like
Caffeine, Ehcache, or Redis. Enable caching with @EnableCaching on a configuration class.
Apply @Cacheable to methods whose results should be cached, @CacheEvict to methods that
invalidate caches, and @CachePut to update cache entries. Configure caches in
application.properties or create a CacheManager bean. For distributed applications, use Redis
or Hazelcast. Implement a composite caching strategy with a local in-memory cache backed by
a distributed cache for better performance. Always consider cache eviction policies and
time-to-live settings to prevent stale data.

74. What strategies would you use to optimize database


operations in Spring Boot?
Optimize database operations by: using JPA batch processing with
spring.jpa.properties.hibernate.jdbc.batch_size; implementing database connection pooling
properly with HikariCP; using projections or native queries for read operations that don't need
entire entities; applying appropriate fetch strategies (lazy loading where possible); implementing
proper indexing in database tables; using query caching for frequently executed queries;
implementing pagination for large result sets; using optimistic locking for concurrency control;
and employing read-write splitting where appropriate. Additionally, consider using Redis or other
caching solutions to reduce database load for read-heavy operations.

75. How do you implement asynchronous operations in


Spring Boot?
Implement asynchronous operations with @EnableAsync on a configuration class and @Async
on methods that should execute asynchronously. Configure a custom TaskExecutor bean to
control thread pool parameters. Methods can return CompletableFuture<T>,
ListenableFuture<T>, or Future<T> for tracked results, or void for fire-and-forget operations.
Handle exceptions using AsyncUncaughtExceptionHandler or return types that support
exception handling. For more complex flows, consider using Spring Integration or Spring Cloud
Stream. When implementing @Async methods, be aware of proxy limitations-calls from within
the same class won't be intercepted.

76. How would you implement reactive programming in


Spring Boot?

Copyright © 2025 by SkillForgePrep


Implement reactive programming in Spring Boot by using Spring WebFlux instead of Spring
MVC. Add spring-boot-starter-webflux dependency and remove spring-boot-starter-web to avoid
conflicts. Use reactive types like Mono and Flux from Project Reactor to represent single and
multiple asynchronous values. Create reactive controllers with @RestController that return Flux
or Mono objects. Integrate with reactive repositories like Spring Data R2DBC for databases or
Spring Data Reactive MongoDB. Configure non-blocking clients with WebClient instead of
RestTemplate. Use backpressure strategies and operators like map, flatMap, and filter to
transform reactive streams efficiently.

77. How can you optimize resource utilization in a Spring


Boot application?
Optimize resource utilization by configuring appropriate connection pool sizes (database, HTTP
client) based on your workload characteristics. Use lazy initialization where applicable.
Implement connection release mechanisms to prevent leaks. Configure thread pools with
sensible maximum sizes to prevent resource exhaustion. Use non-blocking I/O with reactive
programming for I/O-bound operations. Implement proper caching strategies. Set appropriate
JVM memory parameters (-Xmx, -Xms) and garbage collection algorithms. Use resource pools
for expensive resources. Monitor resource usage with Actuator metrics and optimize based on
actual usage patterns, not theoretical maximums.

78. What are the best practices for implementing


bulkhead patterns in Spring Boot?
Implement bulkhead patterns in Spring Boot using separate thread pools for different types of
operations. Use Resilience4j's @Bulkhead annotation to isolate failures and prevent cascading
failures. Configure different TaskExecutors for various domains of functionality with appropriate
queue sizes and rejection policies. For reactive applications, use Schedulers.parallel() or
custom Schedulers for different operation types. Combine bulkheads with circuit breakers to
handle failures gracefully. Monitor thread pool saturation with metrics from Actuator. This
separation ensures that issues in one functional area don't consume resources needed by
others.

79. How would you implement backpressure handling in


Spring Boot applications?
Implement backpressure handling in reactive Spring Boot applications using Project Reactor's
operators. Configure appropriate buffer sizes in reactive streams using operators like
onBackpressureBuffer(), onBackpressureDrop(), or onBackpressureLatest() to handle different
scenarios. For Kafka consumers, set appropriate consumer group configurations like
max.poll.records and fetch.max.wait.ms. For non-reactive applications, use semaphores or

Copyright © 2025 by SkillForgePrep


thread pool queues with rejection policies to limit concurrent operations. Monitor queue depths
and rejected tasks with Actuator metrics. This prevents system overload by controlling the rate
at which data flows through the system.

80. What is the role of connection pooling in Spring Boot


and how would you tune it?
Connection pooling in Spring Boot reuses database connections instead of creating new ones
for each operation, greatly improving performance. Spring Boot auto-configures HikariCP by
default. Tune it by setting appropriate pool sizes-typically (2 * CPU cores) + effective disk
spindle count for optimal throughput. Configure connection timeout, maximum lifetime, and idle
timeout based on your database's behavior. Use leak detection with appropriate thresholds. Set
validation queries and test-while-idle for connection health checks. Monitor pool metrics via
Actuator to detect connection starvation, high wait times, or pool exhaustion, and adjust
accordingly.

81. What are the different ways to package and deploy


Spring Boot applications?
Spring Boot applications can be packaged and deployed in several ways: as executable JARs
with embedded servers using java -jar (the most common approach); as traditional WAR
files deployed to external servers; as OCI-compliant container images using Cloud Native
Buildpacks or Dockerfiles; as native executables using GraalVM; or as OS-specific
installers/services. For Kubernetes deployments, use Spring Boot's built-in container image
support or Jib. For serverless environments, consider Spring Cloud Function with appropriate
adapters. Each approach has different tradeoffs in terms of portability, startup time, resource
utilization, and operational complexity.

82. How does Spring Boot support containerization and


Docker deployment?
Spring Boot supports containerization through several features: layered JARs that optimize
Docker layer caching and reduce image size; Cloud Native Buildpacks integration via
bootBuildImage task; container-friendly health endpoints for orchestration platforms;
externalized configuration suitable for container environments; and graceful shutdown hooks to
handle termination signals properly. The spring-boot-docker-compose dependency automates
Docker Compose integration for development. Spring Boot applications can be configured to be
OCI-compliant with appropriate memory limits awareness and support for Kubernetes probes
through dedicated actuator endpoints.

Copyright © 2025 by SkillForgePrep


83. What is the purpose of layered JARs in Spring Boot
and how do they work?
Layered JARs optimize Docker image building by separating the application into layers with
different change frequencies, leveraging Docker's layer caching. They extract the JAR content
into distinct layers: dependencies (rarely change), spring-boot-loader classes, snapshot
dependencies, and application classes (change frequently). When configured with
spring-boot-maven-plugin using the layers configuration, the JAR includes a layers.idx
file that defines the layer structure. During Docker image building, each layer can be individually
extracted and added, ensuring that only changed layers are rebuilt. This significantly reduces
build times and image sizes in CI/CD pipelines.

84. How would you implement graceful shutdown in


Spring Boot applications?
Implement graceful shutdown in Spring Boot by setting server.shutdown=graceful
property (Spring Boot 2.3+). This allows the server to stop accepting new requests while
completing in-flight requests within a configurable timeout
(spring.lifecycle.timeout-per-shutdown-phase). For web applications, configure
connection draining at the load balancer level to complement this. Implement
ApplicationListener<ContextClosedEvent> for custom shutdown logic. For integrations with
message brokers, implement SmartLifecycle with appropriate stop() method implementations. In
Kubernetes environments, ensure proper terminationGracePeriodSeconds configuration to
allow time for graceful shutdown before the container is forcibly terminated.

85. How do you implement Zero Downtime Deployment


with Spring Boot?
Implement Zero Downtime Deployment with Spring Boot using Blue-Green or Rolling
deployment strategies. Ensure backward compatibility between versions, particularly for
database schemas using incremental migrations with Flyway or Liquibase. Use readiness
probes with Spring Boot Actuator's health endpoints to control traffic routing. Implement proper
connection draining with graceful shutdown (server.shutdown=graceful). For stateful
applications, use session replication or external session stores. In Kubernetes, configure
appropriate readiness/liveness probes, terminationGracePeriodSeconds, and deployment
strategies. Test deployments in staging environments first and implement automated rollback
mechanisms based on health metrics.

Copyright © 2025 by SkillForgePrep


86. What is the Spring Boot Buildpack support and how
does it differ from Dockerfile-based containerization?
Spring Boot Buildpack support (via bootBuildImage task) uses Cloud Native Buildpacks to
create OCI-compliant container images without requiring a Dockerfile. It automatically detects
application requirements, selects appropriate buildpacks for JVM version and dependencies,
and creates optimized layer-structured images. Compared to Dockerfile approaches, buildpacks
provide better security through automatic patching, standardized image structure, optimal layer
caching, and reduced configuration complexity. However, they offer less customization than
Dockerfiles. Buildpacks follow best practices for Java applications automatically, including
memory settings, user permissions, and entrypoint configuration.

87. How would you implement feature flags in a Spring


Boot application?
Implement feature flags in Spring Boot using the @ConditionalOnProperty annotation for static
feature flags that require restart, or using a dynamic approach with a feature flag service. For
the dynamic approach, create a FeatureFlagService bean that checks flag status from a source
like a database, Redis, or dedicated feature flag service (like LaunchDarkly or Flagsmith).
Implement a custom @FeatureFlag annotation and an aspect that intercepts annotated
methods. Use Spring Boot's @RefreshScope for dynamically updating feature flags. Store
feature configurations in Spring Cloud Config for centralized management. Implement
appropriate fallbacks for when features are disabled.

88. How do you manage database schema migrations in a


continuous deployment pipeline?
Manage database schema migrations in a continuous deployment pipeline using Flyway or
Liquibase integrated with Spring Boot. Create versioned, incremental migration scripts that are
backward compatible. Execute migrations automatically on application startup
(spring.flyway.baseline-on-migrate=true). Validate migrations in CI/CD with a dedicated
verification step using a test database. Implement a rollback strategy for each migration. For
multi-service environments, consider a dedicated migration service or use database-per-service
pattern. Avoid schema locks by using techniques like CREATE/DROP instead of ALTER when
possible, and schedule breaking changes during maintenance windows.

89. What are the best practices for externalizing


configuration in Spring Boot applications?

Copyright © 2025 by SkillForgePrep


Best practices for externalizing configuration include: using application.yml/properties for default
values; leveraging environment variables for environment-specific values; using Spring Cloud
Config for centralized, version-controlled configuration; implementing @ConfigurationProperties
beans with validation for type-safe configuration; keeping sensitive information in secret stores
(HashiCorp Vault, AWS Secrets Manager, etc.); using profiles for environment-specific
configurations; organizing properties with meaningful namespaces; documenting configuration
options with metadata; and implementing configuration validation on startup. Additionally, use
relaxed binding and implement configuration health checks to detect configuration issues early.

90. How would you implement canary deployments with


Spring Boot applications?
Implement canary deployments with Spring Boot by leveraging platform capabilities like
Kubernetes or service mesh technologies (Istio, Linkerd). Use Spring Boot Actuator's health and
metrics endpoints to monitor canary instances. Implement feature flags to selectively enable
new functionality. For traffic routing, configure your ingress controller or service mesh to direct a
percentage of traffic to canary instances based on criteria like user IDs or request headers.
Collect detailed metrics using Micrometer and monitor error rates, response times, and business
KPIs. Implement automated rollback triggers based on error thresholds. Use distributed tracing
to compare request flows between canary and stable versions.

91. How would you test Spring Boot applications with


TestContainers?
TestContainers allows testing with real dependencies like databases or message brokers in
lightweight Docker containers. Add testcontainers dependencies and use the @Testcontainers
annotation on your test class. Define containers with @Container annotation, either as static for
shared containers or instance fields for per-test containers. Use JUnit 5's lifecycle methods with
TestContainers to start/stop containers automatically. Configure your Spring Boot application to
use the container's connection details via dynamic properties. This approach provides realistic
testing environments without manual setup while ensuring test isolation and reproducibility.

java
@SpringBootTest
@Testcontainers
class OrderServiceIntegrationTest {

@Container
static PostgreSQLContainer<?> postgres = new
PostgreSQLContainer<>("postgres:14")
.withDatabaseName("test")

Copyright © 2025 by SkillForgePrep


.withUsername("test")
.withPassword("test");

@DynamicPropertySource
static void registerPgProperties(DynamicPropertyRegistry registry)
{
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username",
postgres::getUsername);
registry.add("spring.datasource.password",
postgres::getPassword);
}

@Test
void testOrderCreation() {
// Test using real PostgreSQL database
}
}

92. What is the difference between @MockBean and


traditional mocking frameworks?
@MockBean is a Spring Boot testing annotation that creates a Mockito mock and replaces the
corresponding bean in the application context, allowing it to be injected wherever the original
bean would be. Unlike traditional Mockito mocks created with @Mock, @MockBean integrates
with Spring's dependency injection mechanism, affecting all autowired instances. This makes it
ideal for replacing specific beans in integration tests while keeping the rest of the context intact.
However, it's slower than pure unit tests since it requires loading the Spring context. Use
@MockBean for integration tests where context is important and traditional mocks for focused
unit tests with faster execution.

93. How do you implement contract testing in Spring


Boot microservices?
Implement contract testing using Spring Cloud Contract. The provider service defines contracts
as Groovy DSL or YAML files that specify request/response interactions. These contracts
generate both stub servers (for consumer testing) and automated verification tests (for provider
testing). Consumer services use WireMock with the generated stubs to test against the

Copyright © 2025 by SkillForgePrep


provider's contract without calling the actual service. Provider services run auto-generated tests
to verify they fulfill their contracts. This creates a feedback loop ensuring API compatibility.
Integrate with build tools to run tests automatically and publish stubs to a repository for sharing
between teams.

94. What is the role of test slices in Spring Boot and when
would you use them?
Test slices in Spring Boot load only specific parts of the application context to test particular
layers in isolation, improving test performance. Examples include @WebMvcTest (web layer),
@DataJpaTest (repository layer), @JsonTest (JSON serialization), and @RestClientTest (REST
clients). Use test slices when you need to test a specific layer without the overhead of loading
the entire application. For instance, use @WebMvcTest to test controllers with mocked services,
@DataJpaTest to test repositories with an actual database, or @JsonTest to verify object
serialization. They provide focused environments with appropriate auto-configurations while
excluding unrelated components.

95. How would you test reactive components in Spring


Boot?
Test reactive components using WebTestClient for WebFlux endpoints and StepVerifier for
Reactor types. For endpoint testing, use @WebFluxTest with WebTestClient to perform requests
and assert on responses without blocking. For service layer testing, use StepVerifier to step
through reactive sequences, verifying emissions and terminal signals. Test time-dependent
operations with VirtualTimeScheduler to control time progression. Use TestPublisher for
controlled emission testing and ProjectReactor's test utilities for manipulating context and
backpressure. Always verify error handling by ensuring errors are properly propagated or
handled. Include subscription verification to prevent cold publishers from not being subscribed.

96. What is Test-Driven Development (TDD) in the context


of Spring Boot applications?
TDD in Spring Boot follows the red-green-refactor cycle: first write a failing test (red) for the
desired functionality, then implement the minimal code to make the test pass (green), and finally
refactor while keeping tests passing. For Spring Boot applications, this often starts with defining
controller contracts using @WebMvcTest or integration points using appropriate test slices.
Begin with unit tests for service layer logic, then integration tests for database operations or
external service interactions, and finally end-to-end tests. Spring Boot's test slices facilitate this
approach by allowing focused testing of specific application layers.

Copyright © 2025 by SkillForgePrep


97. How would you implement load testing for Spring
Boot applications?
Implement load testing using tools like Apache JMeter, Gatling, or k6 to simulate user load.
Create realistic test scenarios that exercise critical application paths. Deploy your application in
an environment similar to production with actuator endpoints enabled for metrics. Configure the
load testing tool to gradually increase concurrent users while monitoring throughput, response
time percentiles, and error rates. Collect metrics using Prometheus and visualize with Grafana
dashboards. Look for bottlenecks in CPU, memory, connection pools, or external dependencies
using Spring Boot Actuator metrics. Set performance SLOs (Service Level Objectives) and
automate performance testing in your CI/CD pipeline.

98. What are the best practices for writing maintainable


tests in Spring Boot?
Best practices for maintainable Spring Boot tests include: using appropriate test slices to keep
tests focused; organizing tests to mirror application structure; following the AAA pattern
(Arrange, Act, Assert); using descriptive test names that explain behavior being tested; avoiding
test interdependencies; creating test data builders or factories for complex objects; using
@DirtiesContext judiciously; keeping test data minimal and relevant; leveraging test fixtures for
common setup; isolating integration tests from external systems when possible; writing
assertions that clearly communicate intent; and categorizing tests by execution speed (fast unit
tests vs. slower integration tests).

99. How would you test Spring Boot applications with


multiple profiles?
Test Spring Boot applications with multiple profiles by using @ActiveProfiles annotation to
explicitly activate required profiles for each test. For testing behavior across different profiles,
create separate test classes with different active profiles. Use TestPropertySource to override
specific properties within tests. For conditional behavior testing, use profile-specific test
configurations with @TestConfiguration and @Profile annotations. To test profile-specific beans,
verify their presence or absence using ApplicationContext assertions. When testing
profile-specific property values, use @Value injection in tests or leverage the Environment bean
to retrieve and assert on properties.

100. How do you implement security testing in Spring


Boot applications?

Copyright © 2025 by SkillForgePrep


Implement security testing in Spring Boot applications with @WebMvcTest or @SpringBootTest
combined with Spring Security Test. Use @WithMockUser or @WithUserDetails to simulate
authenticated users with specific roles. Test authorization rules with different user contexts to
ensure proper resource protection. For OAuth2/JWT, use @WithMockJwtAuthentication or
configure a mock OAuth2 server. Implement penetration testing with tools like OWASP ZAP
integrated into your CI/CD pipeline. Test CSRF protection, proper header security policies, and
authentication flows. Verify that sensitive information isn't leaked in responses, logs, or error
messages.

101. What is the difference between JdbcTemplate,


NamedParameterJdbcTemplate, and SimpleJdbcInsert?
JdbcTemplate uses standard JDBC with positional parameters (?),
NamedParameterJdbcTemplate uses named parameters (:name) for better readability, and
SimpleJdbcInsert is a higher-level abstraction for INSERT operations. JdbcTemplate is best for
simple queries with few parameters, NamedParameterJdbcTemplate improves maintenance
with complex parameters, and SimpleJdbcInsert reduces boilerplate for inserts by inferring table
metadata. All three handle resources properly and translate SQL exceptions to Spring's
DataAccessException hierarchy, but differ in their parameter handling approach and level of
abstraction.

102. How does Spring Boot handle database


initialization?
Spring Boot can initialize databases using SQL scripts (schema.sql and data.sql), Hibernate
schema generation, or migration tools like Flyway and Liquibase. The behavior is controlled by
spring.sql.init.* and spring.jpa.hibernate.ddl-auto properties. For embedded databases (H2,
HSQLDB), initialization runs by default, while for production databases, it's disabled unless
explicitly enabled. Spring Boot 2.5+ separates Hibernate initialization from SQL script execution
with improved ordering control. The initialization sequence respects dependencies, with schema
creation happening before data loading, and everything completing before application beans are
created.

103. What is R2DBC and how does it integrate with


Spring Boot?
R2DBC (Reactive Relational Database Connectivity) is a specification for reactive SQL
database access. It integrates with Spring Boot through the spring-boot-starter-data-r2dbc
dependency, which auto-configures ConnectionFactory beans based on application properties.
Unlike JDBC, R2DBC supports non-blocking database operations, returning Mono/Flux types
that enable reactive data pipelines. Spring Data R2DBC provides repository abstractions similar

Copyright © 2025 by SkillForgePrep


to Spring Data JPA but with reactive return types. This allows building fully reactive applications
with relational databases, avoiding the traditional blocking nature of JDBC while maintaining
familiar Spring patterns.

104. How do you implement auditing in Spring Boot data


applications?
Implement auditing in Spring Boot data applications using Spring Data's built-in auditing
support. Enable it with @EnableJpaAuditing (for JPA) or similar annotations for other data
stores. Create entities that implement Auditable or use annotations like @CreatedDate,
@LastModifiedDate, @CreatedBy, and @LastModifiedBy. Implement AuditorAware<T>
interface to provide the current user for creator/modifier fields, typically from security context.
For more complex auditing needs, use Hibernate Envers with @Audited annotations or
implement database triggers. This automatically tracks creation and modification metadata
without cluttering business logic with manual audit field updates.

105. What are the performance implications of N+1 query


problems and how do you solve them?
The N+1 query problem occurs when accessing a collection of entities triggers one query for the
parent entities and N additional queries for their children. This causes significant performance
degradation due to network round-trips and database overhead. Solve it using: fetch joins with
JPQL/HQL (JOIN FETCH); entity graphs with @EntityGraph annotation; batch fetching with
@BatchSize; DTO projections that include only needed data; or native SQL queries with explicit
joins. In Spring Data JPA, prefer query methods with appropriate fetch joins or use
@EntityGraph to specify which associations to load eagerly for specific queries.

106. How would you implement multi-tenancy in Spring


Boot applications?
Implement multi-tenancy in Spring Boot using one of three approaches: separate database per
tenant (most isolated), separate schema per tenant (balanced), or shared schema with tenant
discriminator column (most efficient). For database/schema approach, implement a custom
DataSource that selects the appropriate connection based on the tenant ID from a ThreadLocal
or request parameter. For the discriminator approach, use Hibernate filters or implement AOP
aspects that automatically add tenant criteria to queries. Secure tenant boundaries with proper
authentication/authorization and consider using AbstractRoutingDataSource for dynamic tenant
switching. Store tenant configuration in a central registry for management.

Copyright © 2025 by SkillForgePrep


107. What is the difference between findById() and
getOne() methods in Spring Data JPA?
findById() returns an Optional<T> containing the entity if found, otherwise an empty Optional. It
executes an immediate select query and returns a fully initialized entity. getOne() (or
getReference() in newer versions) returns a proxy reference without hitting the database initially.
It throws EntityNotFoundException if the entity doesn't exist when the proxy is accessed.
findById() is eager loading and suitable when you need the entity immediately, while getOne() is
lazy loading and better when you only need the reference or may not access all proxy
properties. Use findById() for safety, getOne() for performance when using the entity as a
reference.

108. How do you implement database sharding with


Spring Boot?
Implement database sharding with Spring Boot using a custom routing data source (extending
AbstractRoutingDataSource) that determines the appropriate shard based on sharding keys.
Create a ShardingAspect to intercept repository methods and set the current shard key in a
ThreadLocal. Configure multiple data sources representing different shards. Implement a
consistent hashing algorithm for distributing data across shards. For complex sharding, consider
using specialized solutions like ShardingSphere, which integrates with Spring Boot via starters.
Ensure transactional integrity within shards and implement cross-shard join strategies like
application-side joins or denormalization where necessary.

109. What is the Spring Boot AutoConfiguration for


different databases?
Spring Boot provides auto-configuration for various databases through dedicated starter
dependencies. For instance, spring-boot-starter-data-jpa with H2 dependency auto-configures
an embedded H2 database with Hibernate as the JPA provider. When MySQL dependency is
detected, it configures a MySQL datasource with appropriate drivers and dialect. The
auto-configuration creates DataSource, EntityManagerFactory, and TransactionManager beans
with sensible defaults based on the detected database. Additional database-specific
configurations are applied automatically, such as connection pool settings, statement caching,
and SQL dialect options optimized for each database vendor.

110. How do you implement read/write splitting in Spring


Boot data access?

Copyright © 2025 by SkillForgePrep


Implement read/write splitting using AbstractRoutingDataSource with a custom determination
key (read or write). Create separate DataSource beans for read and write operations.
Implement an AOP aspect that intercepts repository methods, analyzing whether they're
read-only (@Transactional(readOnly=true) or naming patterns) or write operations, and sets the
appropriate routing key. Configure TransactionManager to work with the routing DataSource.
For automated solutions, consider using specialized libraries like Seata or MyCat that provide
read/write splitting capabilities. This approach improves performance by directing read queries
to replicas while ensuring writes go to the primary database.

111. What is the difference between @RestController and


@Controller?
@Controller is a stereotype annotation for Spring MVC controllers that traditionally return view
names for template rendering. Methods typically use @RequestMapping and return String view
names or ModelAndView objects. @RestController combines @Controller and
@ResponseBody, indicating that the controller returns serialized objects directly as response
bodies rather than view references. With @RestController, method return values are
automatically serialized to the response using appropriate HttpMessageConverters (JSON by
default). Use @Controller for traditional web applications with server-side rendering and
@RestController for RESTful API endpoints returning data directly.

112. How does content negotiation work in Spring Boot?


Content negotiation in Spring Boot determines the response format based on request headers,
URL parameters, or extensions. It's configured through ContentNegotiationConfigurer in
WebMvcConfigurer. Spring examines the Accept header, format query parameter, or file
extension to determine the desired media type. HttpMessageConverters handle the conversion
between Java objects and response formats (JSON, XML, etc.). You can customize this by
registering additional HttpMessageConverters or configuring content negotiation strategies.
Spring Boot defaults to JSON responses with Jackson, but supports XML (with
jackson-dataformat-xml) and other formats through appropriate converters.

113. What is WebClient and how does it differ from


RestTemplate?
WebClient is a non-blocking, reactive HTTP client introduced in Spring 5 to replace the
synchronous RestTemplate. It provides a fluent API and returns Mono or Flux objects from
Project Reactor. WebClient supports streaming scenarios and better concurrency through its
non-blocking nature. It handles backpressure and connects seamlessly with other reactive
components. RestTemplate is synchronous and blocking, using thread-per-request model,
making it simpler for basic scenarios but less efficient under high load. WebClient is the

Copyright © 2025 by SkillForgePrep


preferred choice for new applications, especially those using reactive programming, while
RestTemplate is maintained for backward compatibility.

114. How would you implement request/response logging


in a Spring Boot application?
Implement request/response logging with a custom filter by creating a class that extends
OncePerRequestFilter. Override the doFilterInternal method to wrap the HttpServletRequest
and HttpServletResponse with custom implementations that can capture input/output streams.
Use ContentCachingRequestWrapper and ContentCachingResponseWrapper from Spring to
buffer request/response bodies. Log the relevant information after the request is processed but
before the response is sent. Alternatively, use Spring Boot's CommonsRequestLoggingFilter by
setting logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG
and customizing it with includePayload, includeHeaders, etc.

java
@Component
public class RequestResponseLoggingFilter extends OncePerRequestFilter
{
private static final Logger log =
LoggerFactory.getLogger(RequestResponseLoggingFilter.class);

@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws
ServletException, IOException {
ContentCachingRequestWrapper requestWrapper = new
ContentCachingRequestWrapper(request);
ContentCachingResponseWrapper responseWrapper = new
ContentCachingResponseWrapper(response);

long startTime = System.currentTimeMillis();


filterChain.doFilter(requestWrapper, responseWrapper);
long timeTaken = System.currentTimeMillis() - startTime;

String requestBody = new


String(requestWrapper.getContentAsByteArray(),
requestWrapper.getCharacterEncoding());

Copyright © 2025 by SkillForgePrep


String responseBody = new
String(responseWrapper.getContentAsByteArray(),
responseWrapper.getCharacterEncoding());

log.info("Request: {} {} - {} bytes, Response: {} - {} bytes,


Time: {} ms",
request.getMethod(), request.getRequestURI(),
requestBody.length(),
response.getStatus(), responseBody.length(),
timeTaken);

// Don't forget this line to copy response to the original


response
responseWrapper.copyBodyToResponse();
}
}

115. What is the difference between @RequestParam,


@PathVariable, and @RequestBody?
These annotations bind different parts of an HTTP request to controller method parameters:
@RequestParam binds query parameters, form data, or multipart form fields (e.g., /users?id=1);
@PathVariable extracts values from the URI path (e.g., /users/{id}); and @RequestBody
deserializes the request body into a Java object using HttpMessageConverters.
@RequestParam and @PathVariable typically bind simple values (strings, numbers), while
@RequestBody handles complex JSON or XML structures. @RequestParam can be optional
with required=false and defaultValue attributes, @PathVariable is typically required, and
@RequestBody is used for POST/PUT requests with content in the request body.

116. How does Spring Boot handle CORS configuration?


Spring Boot handles CORS (Cross-Origin Resource Sharing) through multiple approaches:
global configuration via WebMvcConfigurer.addCorsMappings() method, controller-level
configuration with @CrossOrigin annotation, or filter-based configuration with CorsFilter. Global
configuration in Spring Boot can be done through application properties (spring.mvc.cors.*) or
by creating a WebMvcConfigurer bean. The configuration specifies allowed origins, methods,
headers, credentials support, and max age. Spring Security requires additional configuration
with http.cors(). This enables controlled cross-origin requests that would otherwise be blocked
by browsers' same-origin security policy.

Copyright © 2025 by SkillForgePrep


117. What is the concept of media types in RESTful
applications and how does Spring Boot handle them?
Media types in RESTful applications define the format of request and response data, specified
in Content-Type and Accept headers. Spring Boot handles media types through
ContentNegotiationManager and HttpMessageConverters. Controllers can use
@RequestMapping with consumes attribute to restrict accepted request formats and produces
attribute to specify supported response formats. Methods can be annotated with
@RequestBody and @ResponseBody (or use @RestController) to automatically convert
between Java objects and specified media types. Spring Boot auto-configures appropriate
converters for common formats like application/json, application/xml, and text/plain based on
classpath dependencies.

118. How would you implement API versioning in Spring


Boot?
Implement API versioning in Spring Boot using one of several approaches: URI path versioning
with @RequestMapping("/api/v1/resource"), request parameter versioning with
@RequestParam("version"), custom header versioning with
@RequestHeader("X-API-Version"), media type versioning with "Accept:
application/vnd.company.app-v1+json", or content negotiation using request headers. Each
approach can be implemented at the controller level or using a
RequestMappingHandlerMapping customization. For complex scenarios, create separate
controller implementations for each version or use API versioning libraries. Consider including
version information in API documentation and implementing proper deprecation strategies for
older versions.

119. What is Spring HATEOAS and how would you


implement it?
Spring HATEOAS (Hypermedia as the Engine of Application State) enhances RESTful services
by adding hypermedia links to responses, making APIs more discoverable. Implement it by
adding spring-boot-starter-hateoas dependency and creating resource models that extend
RepresentationModel. Use WebMvcLinkBuilder to create links to controller methods, enhancing
response objects with links to related resources using
.add(linkTo(methodOn(Controller.class).method()).withRel("relationship")). This creates
self-documenting APIs where clients can navigate available actions from any response without
prior knowledge of the API structure, improving discoverability and reducing coupling between
client and server.

Copyright © 2025 by SkillForgePrep


120. How do you implement request rate limiting in
Spring Boot applications?
Implement request rate limiting in Spring Boot using bucket4j-spring-boot-starter for token
bucket algorithm implementation, or resilience4j-ratelimiter for more advanced rate limiting.
Configure limits based on client identifiers (IP address, API key, user ID) extracted from
requests. Implement a custom filter or interceptor that applies rate limiting logic before request
processing. Use Spring Boot Actuator to expose metrics about rate limiting. For distributed
systems, use Redis or Hazelcast to maintain shared rate limit counters across instances. Return
appropriate HTTP 429 (Too Many Requests) responses with Retry-After headers when limits are
exceeded.

121. How would you implement custom authentication


filters in Spring Security?
To implement custom authentication filters in Spring Security, create a class extending
AbstractAuthenticationProcessingFilter. Override attemptAuthentication() to extract credentials
and create an Authentication object. Configure the success/failure handlers in the filter
constructor or with setters. Register the filter in the security chain with http.addFilterBefore() or
http.addFilterAfter() in a WebSecurityConfigurerAdapter or SecurityFilterChain bean. Ensure
your filter creates a properly populated Authentication object and sets it in the
SecurityContextHolder upon successful authentication. This approach is useful for non-standard
authentication mechanisms like API keys, tokens, or custom headers.

java
@Component
public class ApiKeyAuthFilter extends
AbstractAuthenticationProcessingFilter {

public ApiKeyAuthFilter() {
super(new AntPathRequestMatcher("/**"));
setAuthenticationSuccessHandler((request, response,
authentication) -> {

SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
});
setAuthenticationFailureHandler((request, response, exception)
-> {
response.setStatus(HttpStatus.UNAUTHORIZED.value());

Copyright © 2025 by SkillForgePrep


response.getWriter().write("Invalid API Key");
});
}

@Override
public Authentication attemptAuthentication(HttpServletRequest
request,
HttpServletResponse
response) {
String apiKey = request.getHeader("X-API-Key");
if (apiKey == null || apiKey.isEmpty()) {
throw new AuthenticationCredentialsNotFoundException("No
API key found");
}

ApiKeyAuthToken authRequest = new ApiKeyAuthToken(apiKey);


return getAuthenticationManager().authenticate(authRequest);
}
}

122. How do you implement defense against common


security vulnerabilities in Spring Boot?
Implement defense against security vulnerabilities by enabling CSRF protection with proper
token validation for state-changing operations. Prevent XSS by using Content-Security-Policy
headers, output encoding with Thymeleaf or proper Jackson serialization settings, and
HttpOnly/Secure cookie flags. Mitigate SQL injection with prepared statements (default in Spring
Data) and parameterized queries with JdbcTemplate. Configure security headers using Spring
Security's headers() configuration. Prevent CORS issues with proper cross-origin configuration.
Implement rate limiting and brute force protection. Use Spring Security's built-in protection
against CSRF, session fixation, clickjacking (X-Frame-Options), and ensure secure password
storage with modern hashing algorithms.

Copyright © 2025 by SkillForgePrep

You might also like