Top Spring boot interview question (2021)

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

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)

What happens if you combine Field and Setter injection in the same Class?

Consider the following Class:

class Food {

  private Ingredient ingredient;

  Topping getIngredient() {
    return ingredient;

  void setIngredient(Ingredient ingredient) {
    this.ingredient = ingredient;

In the above example, we have added the @Autowired annotation to both the setter and the field. In this case, Spring injects dependency using the setter injection method.

Note that it’s bad practice to mix injection types on a single class as it makes the code less readable.

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.

Why is Spring Boot called an opinionated framework?

Opinionated is a software design pattern that decides or guides you into their way of doing things. Spring Boot is opinionated because it follows the opinionated default configuration that reduces developer efforts to configure the application.

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:

  1. @Configuration, which is used in Java-based configuration on Spring framework
  2. @ComponentScan to enable component scanning of components you write like @Controller classes,
  3. @EnableAutoConfiguration itself, which allows auto-configuration in Spring Boot application.

What does it mean that Spring Boot supports relaxed binding?

Relaxed binding maps the Environment property to the bean property name even it is not an exact match. For example, dash-separated environment properties (app-name bound to appName) or capitalized properties as in PORT (bound to port). Spring boot supports relaxed binding.

Spring Boot interview questions – Web applications

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.

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.

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 architechture 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.

How do you add Javascript code to your Spring Boot application?

/src/main/resources/static is the suggested folder for static content in Spring boot.

You can create a JS file for sending an alert by creating a custom file named custom.js in /src/main/resources/static/js/ directory with below code

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 useJavaFX

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:


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.

Spring Boot interview questions – Security

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.

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

Which Security Context is available in a method which is @Async?

Consider the following block:

public void asyncCall() {"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:

public DelegatingSecurityContextAsyncTaskExecutor taskExecutor(ThreadPoolTaskExecutor delegate) { 
    return new DelegatingSecurityContextAsyncTaskExecutor(delegate); 

By doing so, Spring will use the current SecurityContext inside each @Async call.

Spring Boot interview questions- Data persistence

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.

The other option is Spring Data JDBC which is a skimmed version of Spring Data JPA (an abstraction over Hibernate’s EntityManager).

Spring Data JDBC, part of the larger Spring Data family, makes it easy to implement JDBC based repositories. This module deals with enhanced support for JDBC based data access layers. It makes it easier to build Spring powered applications that use data access technologies.

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.

Which are the steps to connect Spring Boot to multiple databases?

  1. Add an additional datasource configuration to your
  2. Set the SQL Dialect to “default” in your to let Spring autodetect the different SQL
  3. Create a Configuration Class for each database

How can I disable database related autoconfiguration ?

 You can do it in two ways. Using annotations:

@EnableAutoConfiguration(exclude = {
public class Application {

    public static void main(String[] args) {, args);

Or using the file:

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration

Spring Boot interview questions – various

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.

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.

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:

  1. Translates exceptions into http statuses
  2. Returns special responses as ExceptionResponse class

Here is a sample @ExceptionHandler:

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:

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.

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.

public void asyncMethodWithVoidReturnType() {
    System.out.println("Execute method asynchronously. " 
      + Thread.currentThread().getName());

Spring Boot Interview questions – Microservices and cloud

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

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.

Leave a comment