Spring Boot Interview Questions

To put your best foot forward, browse through our top spring boot interview questions and answers. Just spend an hour every day before your interview on these questions. Your next spring boot interview will convert into a sure job offer.

  • 4.5 Rating
  • 22 Question(s)
  • 25 Mins of Read
  • 9798 Reader(s)

Advanced

Spring boot checks if any class is annotated as @ControllerAdvice and @ExceptionHandler and called from rest end point layer, when any exception occurs than spring boot calls the corresponding annotated class to handle the error message.

  • Spring boot provides the below annotation to create the custom handler which eventually catch the exception from rest endpoint.
  • Spring boot provides the cross-cutting concern to handle the exception being generated by rest layer.
  • Leverage to use the error message code comprehensively. 
  • @ControllerAdvice is an annotation, to handle the exceptions globally.
  • @ExceptionHandler is an annotation used to handle the specific exceptions and sending the custom responses to the client.

The real-time scenario is like, let’s say that most of the exception message is system generated and has a straightforward information, which is sometimes difficult to interpret by the user interface and understand by layman user, to solve this issue spring boot handle the error message and convert into the meaningful and comprehensive message which easy to understand and interpret. 

Interceptor is one of the prominent features of spring boot and must use the @Component annotated class that supports it and it should implement the HandlerInterceptor interface.

There are three methods which are used to implement the interceptor.

  • preHandle() method − This method is predominantly used  to perform the operation by intercepting the call and getting the information present in the request.
  • postHandle() method − This method is used  to perform the operation by intercepting  the call information present in the response.
  • afterCompletion() method − This is used to perform operations when the request and response get completed.

Below code structure represent the main method of spring boot which use to kick start the spring boot application along with the configuration details which is in annotated form.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/* Below code is sample code to run the spring boot application from main method.
*  We have to add the ComponentScan annotation to instantiate the bean for onfigure class.
*  Need to add the EnableAuutoConfiguration to do auto configuraion according to the * *dependencies.  
* SpringBootApplication annotation responsible to make the class as a spring boot application.
*/
@ComponentScan
@EnableAutoConfiguration
@SpringBootApplication
public class SpringBootApplication {
  public static void main(String[] args) {
    // Below syntax use to run the spring boot application with internal configure web server,       //which publish deploy and publish the web services, once this process succcessful and web //seriver is up, the web service is available for the configure request.
     SpringApplication.run(SpringBootApplication.class, args);
  }
}

To run the above code, we have to run the below command either from command prompt or shell: mvn spring-boot: run

Below code structure represent the Rest Controller class developed using spring boot framework which use to act as Http Get method.

// Below series of import is important package specially org.springframework package.
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.practise.springboot.model.Product;
// Need to mention the RestController so that it will behave as rest end point.
@RestController
public class ProductServiceController {
  private static Map<String, Product> productRepo = new HashMap<>();
  static {
     Product honey = new Product();
     honey.setId("1");
     honey.setName("Honey");
     productRepo.put(honey.getId(), honey);
     Product almond = new Product();
     almond.setId("2");
     almond.setName("Almond");
     productRepo.put(almond.getId(), almond);
  }
// Below method act as a GET method, which is responsible to receive the HTTP GET call and return back the Product details as a response along with the HTTP Status OK.
  @RequestMapping(value = "/products",  method = RequestMethod.GET)
  public ResponseEntity<Object> getProduct() {
     return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
  }
}

Below code structure represent the Rest Controller class developed using spring boot framework which use to act as Http Post method.

import java.util.HashMap;
import java.util.Map;
// Below series of import is important package specially org.springframework package
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.practise.springboot.Product;
// Need to mention the RestController so that it will behave as rest end point.
@RestController
public class ProductServiceController {
  private static Map<String, Product> productRepo = new HashMap<>();
  // Below method works as a POST method, which is responsible to receive the HTTP Post //method call along with RequestBody which has a product information, need to persist in    //Database and will return the HTTP Status as Created.
  @RequestMapping(value = "/products", method = RequestMethod.POST)
  public ResponseEntity<Object> createProduct(@RequestBody Product product) {
     productRepo.post(product.getId(), product);
     return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
  }
}

}

Below code structure represent the Rest Controller class developed using spring boot framework which use to act as Http Put method.

import java.util.HashMap;
import java.util.Map;
// Below series of import is important package specially org.springframework package
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.practise.springboot.Product;
// Need to mention the RestController so that it will behave as rest end point.
@RestController
public class ProductServiceController {
  private static Map<String, Product> productRepo = new HashMap<>();
  // Below method responsible to handle the HTTP PUT request, which will receive the Path
  //variable {id } as a  parameter and responsible to update the database information according
 // to the id parameter.
  @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
  public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
     productRepo.remove(id);
     product.setId(id);
     productRepo.put(id, product);
     return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
  }
}

Below code structure represent the Rest Controller class developed using spring boot framework which use to act as Http Delete method.

import java.util.Map;
// Below series of import is important package specially org.springframework package
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.practise.springboot.Product
// Need to mention the RestController so that it will behave as rest end point.
@RestController
public class ProductServiceController {
  private static Map<String, Product> productRepo = new HashMap<>();
 // Below method responsible to handle the HTTP DELETE request, which will receive the Path
  //variable {id } as a  parameter and responsible to delete  the database information according
 // to the id parameter.
  @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)
  public ResponseEntity<Object> delete(@PathVariable("id") String id) {
     productRepo.remove(id);
     return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
  }
}

Below code structure represent the ControllerAdvice  class developed using spring boot framework to handle the  exception.

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
            // Need to mention the RestController so that it will behave as a controller class
@ControllerAdvice
public class ProductExceptionController {
// Below method use to handle the exception, which is being generated by the rent //endpoint method. This method also act as a User define exception.
  @ExceptionHandler(value = ProductNotfoundException.class)
  public ResponseEntity<Object> exception(ProductNotfoundException exception) {
     return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND);
  }
}
  1. Rest controller class which generate the exception
import java.util.HashMap;
import java.util.Map;
// Below series of import is important package specially org.springframework package
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.demo.exception.ProductNotfoundException;
import com.tutorialspoint.demo.model.Product;
// This class represents how to call the exception handler class which is mention above.
@RestController
public class ProductServiceController {
  private static Map<String, Product> productRepo = new HashMap<>();
  static {
     Product honey = new Product();
     honey.setId("1");
     honey.setName("Honey");
     productRepo.put(honey.getId(), honey);
     Product almond = new Product();
     almond.setId("2");
     almond.setName("Almond");
     productRepo.put(almond.getId(), almond);
  }
  // Below rest end points method throwing the exception if id is not found in databases,   //so rather than call the runtime exception its calling the handler class, to catch the //exception and generate the appropriate message
  @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
  public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
     if(!productRepo.containsKey(id))
throw new ProductNotfoundException();
     productRepo.remove(id);
     product.setId(id);
     productRepo.put(id, product);
     return new ResponseEntity<>("Product is updated successfully", HttpStatus.OK);
  }
}

Beginner

Spring Boot is an open source Java-based spring framework, which ease to develop a stand-alone and production ready micro service-based applications:

  • Spring boot is a combination of spring framework, embedded HTTP servers and configuration annotation

  • It follows “Opinionated Defaults Configuration” Approach to avoid lot of boilerplate code and configuration to improve Development, Unit Test and Integration Test Process.
  • Spring boot reduce Development, Unit Test and Integration Test time and to ease the development of Production ready web applications.
  • Spring boot comes with auto configuration, for instance, we must mention the dependency it will configure the spring boot accordingly, just we need to add the @EnableAutoConfiguration annotation
  • Spring boot support both Java and Groovy. 
  • Spring boot also support Spring Initializer to generate the base project.
  • @SpringBootApplication annotation requires to configure the spring boot application.
  • Spring boot embedded HTTP server generally run on 8081 server port.

Spring boot ease and simplify the development of rest full web service and provide a quicker development technique by using the key features provided by spring boot framework.

Spring boot is predominately used to develop the micros services-based application, most of the key features leverage to ease the configuration development and deployment of the microservices architecture.

  • Spring boot comes with the monitoring tool called as an Actuator which does the health check of spring boot production application.
  • Externalised configuration 

@Value("${cassandra.password}")

private String password;

  • Embedded server’s support for example Tomcat, Jetty.
  • No need to deploy the war file, simply run it.
  • Provide convention over configuration using Auto-Configuration feature, example like below annotation.

@EnableAutoConfiguration

@ComponentScan 

  • Support Feign Integration which is basically an HTTP client. To enable this feature, we need to add the org.springframework.cloud:spring-cloud-starter-feign  maven dependency.

There are significant advantages of using spring boot over the JAX-RS which is listed below.

  • Easy deployment
  • Simple scalability
  • Compatible with Containers
  • Minimum configuration
  • Lesser production time
  • Easy to understand, develop and configure the spring application
  • Increase the productivity 
  • Reduce the development time.
  • Provide the health check and monitoring feature.
  • Easy to orchestrate using docker.

All this advantage makes spring boot is one of best alternative to develop the microservices application, along with one of the key benefits is, to make it compatible to use the other framework like messaging services, hibernate and spring cloud.

Besides advantages, there are few issues, where we should think about to adopt the spring boot framework to develop the microservice based architecture. 

  • Spring boot unnecessary increase the size of the build with unused dependencies.
  • Not able to create the war file manually and difficult to configure externally.
  • Doesn’t provide much control and tuning the running build.
  • It’s only suitable for micro-services which eventually need to deploy in docker, but not large or mono lithics web services. 

Spring boot doesn’t provide good compatibility if we are integrating third party framework. 

Spring boot provides good compatibility with other spring frameworks which is used to provide the security, persistency features. Spring boot provides good support with docker containerization, which makes it a good choice to deploy the microservice based application and easy to maintain.

  • Provide the easiest way to configure the java beans.
  • Provide a powerful batch processing and manage rest endpoints.
  • Provide auto-configuration mechanism, that means no manual configuration needed. 
  • Provide annotation-based configuration, so no need to configure the xml file manually.
  • Ease the dependency management.
  • It includes the Embedded servlet container.  

Spring boot comes with spring cloud framework, which has many libraries which are used to handle all types of nonfunctional requirement, which is usually not available in other frameworks.

Spring boot provides many abstraction layers to ease the development, underneath there are vital libraries which work for us. 

Below is the key function performing internally.

  • Using @EnableAutoConfigure annotation the spring boot application configures the spring boot application automatically. 
  • E.g. If you need MySQL DB in your project, but you haven’t configured any database connection, in that case, Spring boot auto configures as in memory database.
  • The entry point of spring boot application is a class which contains @SpringBootApplication annotation and has the main method.
  • Spring boot scan all the components included in the project by using @ComponentScan annotation.
  • Let’s say we need the Spring and JPA for database connection, then we no need to add the individual dependency we can simply add the spring-boot-starter-data-jpa in the project.
  • Spring boot follows the naming convention for dependency like spring-boot-starter. 

Considering above there are other internal functions which play a significant role in spring boot.

Below are the key dependencies which you need to add in maven based or Gradle based applications, to make the application compatible to use spring boot functionality. 

  • spring-boot-starter-parent
  • spring-boot-starter-web
  • spring-boot-starter-actuator
  • spring-boot-starter-security
  • spring-boot-starter-test
  • spring-boot-maven-plugin

These dependencies come with associated child dependencies, which are also downloaded as a part of parent dependencies. 

Below is the basic component, which plays a vital role in spring boot framework for configuration, development, deployment, and execution of microservices based application.

  • Spring boot starter. 
  • Spring boot auto configurator.
  • Spring boot actuator.
  • Spring boot CLI.

Spring boot Initilizr.

Spring boot autoconfiguration, check what are the jars that are available in the classpath, according to that autoconfiguration provides a basic configuration to the application according to that jars or library available.

  • Spring Boot autoconfigurator is used by Spring Boot Framework to provide “Auto-Configuration”.
  • Auto-configuration solves the problem of doing amount of configuration in Spring framework, it detects the dependency in a pom.xml file and according to that it configures the spring boot application.
  • Below is the key annotation which we need to use to enable autoconfiguration

@EnableAutoConfiguration

  • We have a below option to enable the specific class to autoconfigure with the existing application.

@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })

  • If we need to enable the external properties file, we can use the below annotation.

@EnableConfigurationProperties(MySQLDataSourceProperties.class)

  • Below annotation works when there is no bean available in the class path than its configure with configure bean class.

@ConditionalOnMissingBean

Spring boot autoconfiguration brings certain level of intelligence into the application so that it removes the hurdles to provide the configuration manually. One can debug the spring boot application by using the below approach:

  • Switch on the debug logging
  • Trigger the spring boot actuator 

Spring boot starter comprises of templates which provide a Rapid Application Development, spring boot starter contains a combination of all the relevant transitive dependencies.  

  • Spring boot starter is a jar file which predominantly solves the auto-dependency resolution in a spring boot application. 
  • Spring boot starter follows the unified pattern, like every dependency start with spring-boot-starter-X, where X will be the name of dependencies.  
  • For instance, if we add the dependency like spring-boot-starter-web, the spring boot starter will internally resolve and download all the associated dependencies, add to the application. 
  • Spring boot also checks and resolves the transitive dependencies internally.

Below are some of the popular Spring boot starters:

  • Spring-boot-starter-web
  • Spring-boot-starter-mvc
  • Spring-boot-starter-security
  • Spring-boot-starter-jpa
  • Spring-boot-starter-tomcat
  • Spring-boot-starter-jetty
  • Spring-boot-starter-json

Spring boot CLI is a command line interface, which use and run test the microservices application based on spring boot.

  • Spring Boot CLI is a module of Spring boot application which use to run and test Spring Boot applications from the command prompt.
  • When we run Spring Boot applications using CLI, then it internally uses Spring Boot Starter and Spring Boot Autoconfiguration components to resolve all dependencies and execute the application.
  • Internally contains Groovy file which is a JAR Dependency Manager to add Spring Boot Defaults and resolve all dependencies automatically. 
  • Spring Boot CLI operation is a combination of below component:
  • Auto Dependency Resolution 
  • Auto-Configuration
  • Management Endpoints
  • Embedded HTTP Servers

The benefits that we achieved from using spring boot CLI is, that we don’t need to use any import, no need to do the xml configuration, no web.xml and no dispatcherservlet declaration and no need to create war file manually.

Spring boot Initilizr is a web application which use to generate the common templates of spring boot application according to the configuration providing in the user interface.

  • Spring boot Initilizr provides a UI where we need to mention the below information.
  • Group
  • Artifact
  • Required dependencies
  • According to the above information, it creates a maven based spring boot project for ready to use.
  • Spring Initilizr also supports the gradle build tools.
  • Spring Initilizr supports the language such as Java, Groovy, Kotlin to develop the spring boot application.  
  • URL for spring Initilizr is https://start.spring.io/
  • Below is the User interface for same.

 All the configurations mentioned at the time of generation of spring boot application will reflect in a pom.xml file, also provided the typical uniform architecture of the project

Spring boot interceptor is typically used to intercept the request and response call made by the UI and microservices-based application, the need of this to add, filter, modified the information contain in request and response. 

  • Interceptor in Spring Boot one can use to add the request header before sending the request to the controller 
  • Interceptor in Spring Boot can add the response header before sending the response to the client.
  • Spring boot works on the below technique. 
  • Before sending the request to the controller
  • Before sending the response to the client
  • After completing the request and response.

The real-world use case of spring-boot interceptor is authentication and authorization, where   we filter the information from the request which contain the credential information which use to authenticate and other information like role which require authorization. 

  • @RestController: Define at class level, so that spring container will consider as RestENd point
  • @RequestMapping(value = "/products"): Define the REST URL for method level.
  • @PathVariable:  Define as a method argument
  • @RequestBody:  Define as a method argument
  • @ResponseEntity: To convert the domain object into the response format
  • @hasAuthority:     To grant the access of corresponding endpoints 
  • @GetMapping: To make endpoint compatible for get request.
  • @PostMapping: To make endpoint compatible for post request.
  • @PutMapping: To make endpoint compatible for put request.
  • @DeleteMapping: To make endpoint compatible for delete request.
  • @ResponseStatus:  To generate the HTTP status.
  • @ResponseBody:  To Generate the response message.

Description

To put your best foot forward, browse through our top spring boot interview questions and answers. Just spend an hour every day before your interview on these questions. Your next spring boot interview will convert into a sure job offer.
Levels