Here is our collection of Spring Boot interview questions which will let you check the level of knowledge of Spring Boot framework from many angles.
Spring Boot interview questions – general
Question: How do I choose between Spring and Spring Boot and why?
The Spring Framework offers you features like dependency injection IOC, transactions loose coupling and easy testability, it also acts as a foundation for other Spring frameworks such as Spring Boot.
Spring Boot includes all the features of the conventional Spring however it makes developing applications much easier by reducing the amount of code and configuration needed. This is especially true for REST applications which you can create and maintain more easily in Spring Boot thanks to its no configuration feature.
On the top of that, if you plan to target your applications on a Kubernetes environment, it is much easier to containerize and deploy Spring Boot applications once you package them as standalone application. On the top of that, several companies like Red Hat support Spring Boot applications when deployed on their Enterprise Kubernetes (OpenShift)
Question: How does Spring Boot provide default configurations for applications?
Spring Boot provides default configurations for applications through its use of starter dependencies and auto-configuration.
Starter dependencies are built-in groups of dependencies that you can include in a project to enable a particular set of functionality. For example, the spring-boot-starter-web
dependency includes a number of dependencies that are commonly used for building web applications, such as spring-webmvc and tomcat-embed-jasper.
Auto-configuration is a feature of Spring Boot that automatically configures beans in the application context based on the presence of certain classes on the classpath and the values of various properties. For example, if the classpath contains a library like HSQLDB and the spring.datasource.url
property is set, Spring Boot will automatically configure an in-memory data source using HSQLDB.
By using starter dependencies and auto-configuration, Spring Boot greatly simplifies the process of setting up and configuring a Spring-based application. It enables developers to get up and running quickly with minimal effort and without the need to manually define and configure beans in the application context.
Question: Can you discuss the use of external properties in Spring Boot and how you can use them to customize application behavior?
Answer: Spring Boot allows you to customize the behavior of your application through the use of external properties. External properties in Spring Boot refer to configuration values that are external to the application code and can be specified in a variety of ways, such as in application.properties or application.yml files, as system properties, or as command-line arguments.
Spring Boot provides a number of ways to use external properties to customize the behavior of your application. One common use case is to use external properties to configure the application’s dependencies, such as databases and messaging systems. For example, you might use external properties to set the connection URL, username, and password for a database that your application needs to connect to.
Another use case for external properties is to customize the behavior of Spring Boot itself, such as by turning off certain auto-configuration features or by specifying the names of specific beans to create.
Overall, the use of external properties in Spring Boot enables you to easily customize the behavior of your application without the need to make code changes, making it easier to deploy and run your application in different environments.
Question: Are there any drawbacks to using Spring Boot in the development of applications?
Yes, as for every framework there are some potential drawbacks. One potential drawback is that Spring Boot can make it more difficult to understand the underlying Spring concepts and configurations if you are new to the framework. This is because Spring Boot automatically configures many things behind the scenes, which can make it harder to understand how everything fits together.
Another potential drawback is that Spring Boot can be opinionated, meaning that it has certain opinions about how things should be done and may not provide as much flexibility as the raw Spring framework. This can be seen as a trade-off for the simplicity and ease of use that Spring Boot provides.
Another potential issue is that the use of starter dependencies and auto-configuration can result in larger application sizes and slower start-up times compared to a manually-configured Spring application. Although you can use the Spring Boot “thin jar” feature, which allows you to create smaller executables by only including the classes that you need in your application.
Question: Which are the Java and Jakarta EE standards supported in Spring Boot 3 ?
Spring boot 3 relies on the Spring framework version 6. Therefore, you need a Java 17+ and supports Jakarta EE 9+ .
Questions and Answers about Annotations
Question: How do I release resources acquired from a @Bean?
You can add to the bean a public close() or shutdown() method, and it will be automatically used as the destroy-method.
As an alternative, you can use the destroyMethod parameter in your Bean declaration the name of the method you want to use for releasing resources:
@Bean(destroyMethod = "destroy") public MyBean myBean(){...
Question: Why Should I Use Constructor Injection?
Firstly, we can be sure that all required dependencies are available at Initialization Time. The IoC container makes sure that all the arguments provided in the constructor are available before passing them into the constructor. This helps in preventing NullPointerException.
Then, it helps refactoring your code: Constructor injection helps us to identify if our bean is dependent on too many other objects. We may want to think about refactoring our code to better address proper separation of concerns.
Next it helps in preventing Errors in Tests: Constructor injection simplifies writing unit tests. The constructor forces us to provide valid objects for all dependencies. Using mocking libraries like Mockito, we can create mock objects that we can then pass into the constructor.
Finally, consider immutability: Constructor injection helps in creating immutable objects because a constructor’s signature is the only possible way to create objects. Once we create a bean, we cannot alter its dependencies anymore. With setter injection, it’s possible to inject the dependency after creation, thus leading to mutable objects which may not be thread-safe.
Question: What is the difference between @SpringBootApplication vs @EnableAutoConfiguration annotations in Spring Boot?
@SpringBootApplication has a much wider scope than @EnableAutoConfiguration. It’s actually a combination of three annotations:
- @Configuration, which is used in Java-based configuration on Spring framework
- @ComponentScan to enable component scanning of components you write like @Controller classes,
- @EnableAutoConfiguration itself, which allows auto-configuration in Spring Boot application.

Question: What is the usage of the @ConditionalOnProperty annotation in Spring Boot ?
You can use the @ConditionalOnProperty annotation to specify that a particular bean should only be registered if a certain property is set to a specific value. This is useful for controlling the auto-configuration of beans in Spring Boot, as it allows you to enable or disable the configuration of certain beans based on the presence or value of certain properties.
For example, you might use the @ConditionalOnProperty annotation to specify that a particular bean should only be registered if a certain property is set to true:
@Bean @ConditionalOnProperty(name = "example.enabled", havingValue = "true") public ExampleBean exampleBean() { return new ExampleBean(); }
Question: Can you explain the difference between the @ComponentScan and @EntityScan annotations in the context of Spring Boot?
Component scanning is a feature of the Spring Framework that allows it to automatically discover and register beans in the application context. By default, Spring will search for beans in the package and its sub-packages where the @ComponentScan annotation is used.
Entity scanning is similar to component scanning, but it is used specifically to find and register entity classes in the application context. Entity classes are typically used in the context of a Java Persistence API (JPA) implementation and are used to represent data stored in a database.
Web applications interview question
Question: Which framework and Web server is available if I include the spring-boot-starter-web ?
By including the spring-boot-starter-web in your application, Spring Boot will detect that you have a Spring MVC controller and start up an embedded Apache Tomcat instance, by default.
Question: Which Web servers can you use in Spring Boot applications?
- spring-boot-starter-web brings Tomcat (default Web server)
- spring-boot-starter-jetty brings Jetty Web server
- spring-boot-starter-undertow lets you use Undertow
- spring-boot-starter-webflux brings Spring WebFlux, which provides reactive programming support for web applications.
To learn how to use Undertow as Web server check this tutorial: Configure Spring Boot to use Undertow Web server
Question: What is the difference between Spring MVC and Spring RESTful web service?
The basic difference between Spring MVC and Spring REST is: MVC is a complete web application package, with a where you can write a view in JSP, controller in spring (@controller) and the model could be your pojo objects of db. In controller you can inject spring services like AOP, IOC etc.
Whereas Spring REST gives you a rest template which you can use in any REST API implementation. In this case typically you don’t have any dedicated view for your controller (@restcontroller) and return a json object. You can use this api in any application n any view.
In spring MVC the binding of controller and view is quite strong. It provides a server side view through DispatcherServlet. It is this Servlet which defines and sends model to a particular controller and then Model and View come again to this servlet.
In Spring Rest it also works on MVC architecture only. But in this RestController sets Model object directly into Http response. There it is converted to JSON/XML automatically. So if we define flow here then request comes from client which goes dispatcherServlet, then the dispatcherServlet with the use of handlerMapping send it to particular controller, then this controller sets Model in Http response with the help HttpMessageConverters and this response is sent to client.
Question: Can you explain the role of the DispatcherServlet in a Spring Boot web application and how it works with the application context?
In a Spring Boot web applications, the DispatcherServlet is the front-controller responsible for handling all incoming HTTP requests and delegating request processing to the appropriate handler.
The DispatcherServlet is configured in the application’s web.xml file. For example, if the application context contains a controller bean that is mapped to a particular URL pattern, the DispatcherServlet will delegate requests matching that URL pattern to the controller bean for processing.

Question: How can you implement asynchronous request processing in a Spring Boot web application and what benefits does it provide?
To implement asynchronous request processing in a Spring Boot web application, you can use the @Async
annotation on a method to indicate that it should be executed asynchronously. This annotation can be used in combination with the @EnableAsync
annotation on a @Configuration
class to enable support for asynchronous method execution.
Here is an example of a method that is annotated with @Async
and can be called asynchronously:
@Async public void processRequestAsynchronously() { // Code to process request asynchronously }
Asynchronous request processing can improve the performance and scalability of a web application by allowing requests to be processed concurrently, rather than sequentially. This can be especially useful for long-running requests that might otherwise block other requests from being processed.
Asynchronous request processing can also make it easier to develop and maintain web applications by allowing you to decouple different parts of the application and avoid the need for complex thread management.
Question: How do you add Javascript code to your Spring Boot application?
One option is to include JavaScript files in the src/main/resources/static directory of your application. These files will be automatically served by Spring Boot at runtime and can be accessed using a URL that matches the path of the file in the static directory.
For example, if you have a file src/main/resources/static/js/main.js, you can include it in an HTML page using a script tag like this:
<script src="/js/main.js"></script>
Question: What is the best front-end framework for Spring Boot and why?
There are several alternatives. Some of the most popular are:
- AngularJS with Spring Boot: This is a very powerful combination to create Web application with light footprint. You can scaffold a front end project with Angular CLI and connect it with Spring Boot backend
- React browser UI with Spring Boot @RestController: React is a JavaScript library for creating user interfaces. Calling our Spring Boot API requires setting up our React application’s package.json file to configure a proxy when calling the API.
- Spring MVC and Thymeleaf: Thymeleaf is a Java template engine for processing and creating HTML, XML, JavaScript, CSS, and text. You can use it as the View layer of a Spring MVC application.
For Desktop UI, it is pretty common to use JavaFX
REST Controller questions
Question: Can you discuss the various ways to create a RESTful service using Spring Boot?
- One way to create a RESTful service with Spring Boot is to use the Spring MVC framework and its
@RestController
annotation. This allows you to create a traditional, request-response style REST service by annotating your controller class and methods with the appropriate MVC annotations. - Another way to create a RESTful service with Spring Boot is to use Spring WebFlux and its
@RestController
annotation. This allows you to create a reactive, non-blocking REST service that is designed to scale under high load. - You can also use Spring Data REST to easily expose a Spring Data repository as a RESTful service. This is a convenient way to create a CRUD-style REST service with minimal coding and configuration.
- Finally, you can use the Spring REST Template to create a REST client and invoke RESTful services from within your Spring Boot application.
Question: How can you customize the JSON serialization and deserialization process in a Spring Boot REST application?
In a Spring Boot REST application, you can customize the JSON serialization and deserialization process by using the following approaches:
- One way to customize the JSON serialization process is to use the
@JsonView
annotation on your model classes. This annotation allows you to specify different views of your model class, and you can then use theMappingJacksonValue
class to specify which view to use when serializing the object to JSON. - Another way to customize the JSON serialization process is to use custom serializers and deserializers. You can write your own implementation of the
JsonSerializer
andJsonDeserializer
interfaces and then register them with theObjectMapper
used by Spring MVC to serialize and deserialize objects. - You can also customize the JSON serialization process by configuring the
ObjectMapper
bean directly. This can be done using thespring.jackson.*
properties in your application’s configuration or by configuring theObjectMapper
bean directly in your application code.
Question: Can you discuss the use of HATEOAS in a Spring Boot REST application and how it can be implemented?
HATEOAS, or Hypermedia as the Engine of Application State, is a constraint of the REST architecture that requires a RESTful service to include links to related resources in its responses. This allows a client to navigate the API by following these links, rather than needing to hard-code URLs or construct them manually.
For example:
@GetMapping("/users/{id}") public Resource<User> getUser(@PathVariable long id) { User user = userRepository.findById(id); Link selfLink = linkTo(methodOn(UserController.class).getUser(id)).withSelfRel(); Link usersLink = linkTo(methodOn(UserController.class).getUsers()).withRel("users"); return new Resource<>(user, selfLink, usersLink); }
In this example, the getUser
method returns a Resource
object that represents a user resource and includes links to the current resource and a list of all users.
Question: What is Actuator in Spring Boot?
Actuator is a spring boot tool which helps us to monitor and manage our applications. When you push an application in production, it provides HTTP endpoints with which we can monitor and get metrics of your application.
To enable this feature you should add this dependency into your pom.xml file:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
That’s it.Now you can get your metrics by simply going to the URL http://host:port/actuator
Some of the EndPoints actuator provides are:
- /env – Returns a list of properties in the current environment
- /health – Returns application health information.
- /threaddump – It performs a thread dump.
- /trace – Returns HTTP trace logs
- /metrics – It shows several useful metrics information like JVM memory used, system CPU usage, open files, and much more.
Question: How can you generate documentation for a Spring Boot REST API?
One way to generate documentation for a Spring Boot REST API is to use the Spring REST Docs project. Spring REST Docs is a library that helps you to document RESTful services by using a combination of test-driven development and Asciidoctor.
In this example, we are coding a Test case with Spring REST Docs API to document the request and response details:
@Test public void example() throws Exception { this.mockMvc.perform(get("/example")) .andExpect(status().isOk()) .andDo(document("example", responseFields( fieldWithPath("field1").description("The first field"), fieldWithPath("field2").description("The second field") ) )); }
Include the include the spring-restdocs-mockmvc and asciidoctor-spring-boot-starter dependencies. Then, use the mvn package
command to generate the documentation as an HTML file.
Security interview questions
Question: How to integrate JWT with Spring Boot?
In previous versions of the Spring Security OAuth stack you could set up an Authorization Server as a Spring Application. Then you had to configure it to use JwtTokenStore so that we could use JWT tokens.
However, the OAuth stack is now deprecated so the best option is to use an Authorization Server to act as Authorization Server. A common strategy is to use an embedded Keycloak as Authorization Server for your Spring Boot app. Keycloak issues JWT tokens by default, so there is no need for any other configuration in this regard.
Question: What would you use to secure REST Services with Spring Boot?
The easiest way to secure end points is adding the spring-boot-starter-security maven dependency to the pom.xml. This would generate a unique password every time the application starts. This is not robust and you should not use it for production grade systems.
The most commonly used methodology while securing a REST API is token based authentication. In layman terms, every request carries a token (in header usually) and token is validated before processing the request. The token is generated by the application when the user provides his credentials for the first time. The token is time bound and set to expire after the time set. Its up to the application design to take a call on how to reset the expired token. In general, when there is only one day left for the token expiry a new token will be returned to be used going further.
The token based authentication can be further enhanced using Spring Security. It provides a basic framework for authentication and authorization of requests.
The token is usually encrypted and carries a unique identifier of the user. The user details are fetched using this unique id and are used for request processing.
If you need even more sophisticated solution with minimal load on the app server, go ahead with the following combination:
- Using JWT (JSON Web Token) with Spring Boot
- Authenticating API Clients with JWT and NGINX
Question: Which Security Context is available in a method which is @Async?
Consider the following block:
@Async public void asyncCall() { log.info("Calling the @Async logic: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal()); }
By default, the security context inside the @Async method will have a null value.
If we want to have access to the principal inside the async thread, just as we have access to it outside, we’ll need to create the DelegatingSecurityContextAsyncTaskExecutor bean:
@Bean public DelegatingSecurityContextAsyncTaskExecutor taskExecutor(ThreadPoolTaskExecutor delegate) { return new DelegatingSecurityContextAsyncTaskExecutor(delegate); }
By doing so, Spring will use the current SecurityContext inside each @Async call.
Data persistence Spring Boot interview questions
Question: What are your options to persist data in Spring Boot if you don’t want to use JPA/Hibernate?
There are mainly two options you can use:
Spring JDBC provides a tool that makes it straightforward to work with JDBC: JdbcTemplate and its starter org.springframework.boot spring-boot-starter-jdbc
JdbcTemplate works as a generic database client that allows you to write and execute SQL statements… Compared with plain JDBC, Spring JdbcTemplate eliminates common challenges such as:
- Write a lot of code before and after executing the query, such as creating connection, statement, closing resultset, connection etc.
- Perform exception handling code on the database logic.
- Handle transactions.
Spring Data JDBC is a skimmed version of Spring Data JPA. It aims at being conceptually easy. In order to achieve this it does NOT offer caching, lazy loading, write behind or many other features of JPA. This makes Spring Data JDBC a simple, limited, opinionated ORM.
Question: Which are the steps to connect Spring Boot to multiple databases?
- Add an additional datasource configuration to your application.properties
- Set the SQL Dialect to “default” in your application.properties to let Spring autodetect the different SQL
- Create a Configuration Class for each database
Question: How can I disable database related autoconfiguration ?
You can do it in two ways. Using annotations:
@SpringBootApplication @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) public class Application { public static void main(String[] args) { SpringApplication.run(PayPalApplication.class, args); } }
Or using the application.properties file:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
Various Spring Boot interview questions
Question: How Spring Boot DevTools can help me?
Spring Boot Dev Tools plugs into SpringBoot’s classloader to provide a way to restart the application context on-demand or to reload changed static files without a restart.
To do that, Spring Boot Dev Tools splits the application’s classpath into two classloaders:
- The base classloader, which contains seldom changing resources such as Spring Boot JARs or 3rd party libraries
- The restart classloader, which contains our application files that change during development.
Spring Boot Dev Tools listens to changes in our application files and then throws away and recreates the restart classloader. This is faster than a full application restart because the container will restart only the application classes.
Question: Are transactions enabled by default in Spring Boot?
if we’re using a Spring Boot project and have a spring-data-* or spring-tx dependencies on the classpath, then transaction management will be enabled by default.
Question: How do you handle Exceptions in Spring Boot without writing try/catch blocks?
Spring @ExceptionHandler allows you to do that. Behind the scenes it does the following:
- Translates exceptions into http statuses
- Returns special responses as ExceptionResponse class
Here is a sample @ExceptionHandler:
@ExceptionHandler(UserNotFoundException::class) @ResponseStatus(HttpStatus.UNAUTHORIZED) @ResponseBody public ExceptionResponse handleUserNotFoundException(HttpServletRequest request, UserNotFoundException ex) { return ExceptionResponse("failure"); }
Here we specify what type of exception we are dealing with (you can handle different exceptions in different ways). And also we specify what status code and what body should a response have.
Having this handler up and running we can write our code without try/catch. Example:
@GetMapping("/api/user/{id}") public String api_one(@PathVariable Integer id) throws UserNotFoundException { var user = userService.getUserById(id); return "success"; }
Now we don’t need to deal with exception when we write code. We can even call userService.getUserById(id) from any other place/controller and still have this exception handled properly by framework.
Question: How do you execute a method asynchronously in Spring Boot?
You can do it by annotating a method of a bean with @Async. That will make it execute in a separate thread. As a result, the caller will not wait for the completion of the called method.
@Async public void asyncMethodWithVoidReturnType() { System.out.println("Execute method asynchronously. " + Thread.currentThread().getName()); }
Microservices and cloud interview questions
Question: Can you show me an example on how two Spring Boot applications can communicate?
To establish communication between two spring boot applications you can use this pattern:
- Implement REST APIs: This can be achieved by using RestTemplate or configure Feign client.
- Configure a publish/Subscribe model, making use of message broker such as ActiveMQ or a Streaming Server like Kafka
Question: What’s the best strategy to scale MicroServices developed in Spring Boot?
Scaling is part of runtime lifecycle whereas things like framework, programming language and communication mechanism are implementation details.
That means that the platform running and managing your microservices should be completely unaware of these details but only know about which services it has to manage and where to get them from and where it can be run on.
One example setup could be:
- Spring Boot – used to implement the service
- Docker – used to define the runtime the service needs to be run in
- OpenShift – used for deploying, operating and scaling the docker images on a cluster of nodes
- AWS – cloud platform to run the Kubernetes master- & node-servers on
The advantages of this setup are: If you want to move from AWS to GCE, Azure or whatever, this can be done without any change to your application. If you decide to rewrite the service in another language you don’t need to make any changes to your cluster of nodes. You could also start with a cluster on an on-premise VM or Bare Metal Server and than later you can move services independently to the cloud. This setup is known as Hybrid.
Other interview questions
Check the following JBoss / WildFly interview questions