Table of contents
1.
Introduction
2.
Beginner-Level Spring Boot and Microservices Interview Questions
2.1.
1. How does Spring Boot differ from the traditional Spring framework?
2.2.
2. What is the purpose of the @SpringBootApplication annotation?
2.3.
3. What are Spring Boot starters & how are they useful?
2.4.
4. How do you configure properties in a Spring Boot application?
2.5.
5. What is containerization?
2.6.
6. How do you set up a database connection in Spring Boot?
2.7.
7. What are the different ways to run a Spring Boot application?
2.8.
8. Spring vs Spring Boot?
2.9.
9. What are the key dependencies of Spring Boot?
2.10.
10. What is @annotation in Spring Boot?
3.
Intermediate Spring Boot and Microservices Interview Questions
3.1.
11. How do you perform integration testing in Spring Boot?
3.2.
12. What is the purpose of the @Conditional annotations in Spring Boot?
3.3.
13. What is the starter dependency of the Spring Boot module?
3.4.
14. What is Spring Initializer?
3.5.
15. What is the difference between @RestController & @Controller in Spring Boot?
3.6.
16. What is an IOC container?
3.7.
17. What is the role of the @SpringBootTest annotation?
3.8.
18. What is the @RestController annotation in Spring Boot?
3.9.
19. What is Spring Boot CLI & how do you use it?
3.10.
20. How do you handle exceptions in a Spring Boot application?
4.
Advanced Spring Boot and Microservices Interview Questions
4.1.
21. What is the purpose of using @ComponentScan in the class files?
4.2.
22. What differentiates Spring Data JPA & Hibernate?
4.2.1.
Hibernate
4.2.2.
Spring Data JPA
4.3.
23. How are the @RestController & @Controller annotations different?
4.3.1.
@Controller
4.3.2.
@RestController
4.4.
24. Describe the flow of HTTPS requests through the Spring Boot application.
4.4.1.
SSL/TLS Handshake
4.4.2.
Request Handling
4.4.3.
Dispatching to the Controller
4.4.4.
Request Processing
4.4.5.
Response Preparation
4.4.6.
Response Encryption
4.4.7.
Client Receives Response
4.5.
25. What is the difference between RequestMapping & GetMapping?
4.5.1.
@RequestMapping
4.5.2.
@GetMapping
4.6.
26. What annotations are used to create an interceptor?
4.6.1.
@Component
4.6.2.
@Order or @Priority
4.6.3.
HandlerInterceptor interface
4.7.
27. What are the differences between @SpringBootApplication & @EnableAutoConfiguration annotations?
4.7.1.
@SpringBootApplication
4.7.2.
@EnableAutoConfiguration
4.7.3.
The main differences between @SpringBootApplication & @EnableAutoConfiguration are:
4.8.
28. How to enable debugging log in the Spring Boot application?
4.9.
29. What is dependency injection & its types?
4.10.
30. How to connect the Spring Boot application to a database using JDBC?
5.
Conclusion
Last Updated: Jul 18, 2025
Medium

Spring Boot and Microservices Interview Questions

Author Rahul Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Spring Boot & microservices are popular tools for building modern web applications. Spring Boot simplifies the development process by providing auto-configuration & starter dependencies, while microservices break down complex systems into smaller, independently deployable services. 

Spring Boot and Microservices Interview Questions

In this article, we'll discuss some common Spring Boot and Microservices Interview Questions and Answers, which include concepts like annotations, testing, & more. 

Beginner-Level Spring Boot and Microservices Interview Questions

1. How does Spring Boot differ from the traditional Spring framework?

Spring Boot is built on top of the Spring framework but aims to simplify & speed up development. It provides auto-configuration based on classpath dependencies, embedded servers, & opinionated defaults. This reduces boilerplate code & manual setup compared to traditional Spring. Spring Boot also offers starter dependencies that bundle related libraries together.

2. What is the purpose of the @SpringBootApplication annotation?

The @SpringBootApplication annotation is used on the main class of a Spring Boot application. It combines three annotations: @Configuration to enable Java-based configuration, @EnableAutoConfiguration to activate auto-configuration, & @ComponentScan to scan for components in the current package & its sub-packages. This single annotation bootstraps the entire application.

3. What are Spring Boot starters & how are they useful?

Spring Boot starters are dependency descriptors that include related libraries needed for specific functionality. For example, spring-boot-starter-web includes libraries for building web apps like Spring MVC, Tomcat, & Jackson. Starters simplify dependency management by providing compatible versions of libraries that work well together. They reduce the need to manually manage individual dependencies.

4. How do you configure properties in a Spring Boot application?

Spring Boot allows configuring properties via an application.properties or application.yml file. These files are placed in the src/main/resources directory. Properties can be injected using the @Value annotation. For example:

@Value("${app.name}")
private String appName;


Spring Boot also supports external configuration via command line arguments, environment variables, & more. The @ConfigurationProperties annotation can map properties to POJOs.

5. What is containerization?

Containerization is the process of packaging an application with its dependencies into a container image. Containers provide an isolated runtime environment & abstract away differences in underlying infrastructure. Technologies like Docker are commonly used for containerization. In the context of microservices, each service can be packaged into a container, enabling independent deployment & scaling. Containerization enhances portability & consistency across environments.

6. How do you set up a database connection in Spring Boot?

Spring Boot provides auto-configuration for common databases. To set up a connection, include the appropriate database driver dependency (e.g., spring-boot-starter-jdbc for JDBC) & configure the connection properties. For example, to connect to MySQL:

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

Spring Boot will automatically create a DataSource bean based on these properties. You can then use this DataSource to interact with the database using JDBC, JPA, or other supported libraries.

7. What are the different ways to run a Spring Boot application?

There are several ways to run a Spring Boot application:

  • Using the java command: Build the application into a JAR file using Maven or Gradle & run it with java -jar app.jar.
     
  • Using the Maven plugin: Run mvn spring-boot:run to start the application using the Spring Boot Maven plugin.
     
  • Using an IDE: Most IDEs like IntelliJ IDEA or Eclipse have built-in support for running Spring Boot applications.
     

As a containerized application: Package the application into a container image (e.g., Docker) & run it using a container runtime.

8. Spring vs Spring Boot?

Spring is a powerful framework for building Java applications, providing features like dependency injection, AOP, data access, & more. However, setting up a Spring project can involve significant configuration & boilerplate code.

Spring Boot builds on top of Spring & aims to simplify the development process. It provides auto-configuration based on classpath dependencies, embedded servers, & opinionated defaults. This reduces the need for manual setup & allows developers to focus on writing business logic. Spring Boot also offers starter dependencies that bundle related libraries together.

In summary, Spring Boot is a convention-over-configuration approach built on Spring, designed to streamline application development & deployment.

9. What are the key dependencies of Spring Boot?

Spring Boot has several key dependencies:

  • spring-boot-starter: The core starter that provides basic functionality & auto-configuration support.
     
  • spring-boot-starter-web: Includes libraries for building web applications like Spring MVC, Tomcat, & Jackson.
     
  • spring-boot-starter-data-jpa: Provides support for JPA-based data access using Hibernate.
     
  • spring-boot-starter-security: Offers authentication & authorization features using Spring Security.
     
  • spring-boot-starter-test: Includes testing libraries like JUnit, Mockito, & Spring Test.
     

These are just a few examples. Spring Boot offers many more starters for different purposes like logging, caching, messaging, etc.

10. What is @annotation in Spring Boot?

In Spring Boot, @annotation is used as a general placeholder to refer to any specific annotation that Spring Boot provides or supports. Annotations in Spring Boot are a special form of syntactic metadata that can be added to Java source code.

Intermediate Spring Boot and Microservices Interview Questions

11. How do you perform integration testing in Spring Boot?

Spring Boot provides the @SpringBootTest annotation for integration testing. It loads the full application context & allows testing end-to-end scenarios.

Here's an example of an integration test:

@SpringBootTest
@AutoConfigureMockMvc
class MyControllerTest {
@Autowired
private MockMvc mockMvc;

@Test
void testEndpoint() throws Exception {
    mockMvc.perform(get("/api/endpoint"))
        .andExpect(status().isOk())
        .andExpect(content().string("Hello, World!"));
}
}


The @SpringBootTest annotation initializes the application context. @AutoConfigureMockMvc enables MockMvc support for testing web endpoints. The test method uses MockMvc to send a request to the endpoint & verifies the response status & content.

Spring Boot also supports other testing utilities like @DataJpaTest for testing JPA repositories, @WebMvcTest for testing MVC controllers in isolation, & more.

12. What is the purpose of the @Conditional annotations in Spring Boot?

The @Conditional annotations in Spring Boot allow for conditional configuration based on certain conditions. They enable or disable configuration classes or beans depending on whether the specified conditions are met.

Some common @Conditional annotations include:

  • @ConditionalOnClass: Checks if a specific class is present on the classpath.
     
  • @ConditionalOnMissingBean: Checks if a bean of a specific type is not already defined.
     
  • @ConditionalOnProperty: Checks if a specific property is present & has a certain value.
     
  • @ConditionalOnResource: Checks if a specific resource (e.g., file) is present.
     

These annotations are used in auto-configuration classes to conditionally enable or disable configuration based on the presence or absence of certain dependencies, properties, or resources. They help in creating flexible & adaptable applications.

13. What is the starter dependency of the Spring Boot module?

The starter dependency of the Spring Boot module is spring-boot-starter. It is the core starter that provides basic functionality & auto-configuration support. It includes the following:

  • spring-boot: The core Spring Boot library.
     
  • spring-boot-autoconfigure: Provides auto-configuration capabilities.
     
  • spring-boot-starter-logging: Configures logging using Logback.
     
  • spring-core: The core Spring framework library.
     
  • spring-context: Provides the application context & dependency injection features.
     

The spring-boot-starter dependency is typically used as the base dependency for other Spring Boot starters. It ensures that the essential Spring Boot libraries & auto-configuration support are available in the application.

14. What is Spring Initializer?

Spring Initializer is a web-based tool that helps bootstrap Spring Boot projects quickly. It provides a user-friendly interface for generating project structures with desired dependencies & configurations.

To use Spring Initializer:

  • Visit the Spring Initializer website (https://start.spring.io/).
     
  • Select the project type (Maven or Gradle), language (Java, Kotlin, or Groovy), & Spring Boot version.
     
  • Specify project metadata like group, artifact, name, description, & packaging.
     
  • Choose the desired dependencies from the available options.
     
  • Click on the "Generate" button to download the project as a ZIP file.
     

The generated project includes the necessary structure, configuration files, & dependencies based on the selected options. It provides a starting point for developing Spring Boot applications, saving time in manual setup.

Spring Initializer supports a wide range of dependencies, including web, data access, security, messaging, & more. It helps kickstart projects with best practices & recommended configurations.

15. What is the difference between @RestController & @Controller in Spring Boot?

The @Controller & @RestController annotations are used to define controllers in Spring Boot, but they serve different purposes.
 

@Controller:

  • Indicates that the class is a Spring MVC controller.
     
  • Typically used for serving web pages or rendering views.
     
  • Requires explicit mapping of request methods using annotations like @GetMapping, @PostMapping, etc.
     
  • Returns a view name or a ModelAndView object.
     

@RestController:

  • A combination of @Controller & @ResponseBody annotations.
     
  • Indicates that the class is a controller that returns JSON, XML, or other media types.
     
  • Each method in the controller automatically serializes the returned object into the response body.
     
  • Suitable for building RESTful APIs.

 

Here's an example of a @RestController:

@RestController
@RequestMapping("/api")
public class MyRestController {
@GetMapping("/hello")
public String hello() {
    return "Hello, World!";
}
}


In this case, accessing the "/api/hello" endpoint will return the string "Hello, World!" directly in the response body, without the need for an explicit @ResponseBody annotation.

16. What is an IOC container?

An IOC (Inversion of Control) container is a core component of the Spring framework that manages the lifecycle & dependencies of objects (beans) in an application. It is responsible for creating, configuring, & managing objects, as well as injecting dependencies between them.

The main tasks of an IOC container include:

  • Instantiating beans based on configuration (XML, Java annotations, or Java code).
     
  • Resolving dependencies between beans by injecting required collaborators.
     
  • Managing the lifecycle of beans (creation, initialization, destruction).
     
  • Providing a consistent way to access & use beans throughout the application.
     

The IOC container promotes loose coupling & modularity by allowing objects to be defined & wired together externally. This makes the code more maintainable, testable, & flexible.

Spring provides two types of IOC containers:

  • BeanFactory: A basic container that provides fundamental functionality for managing beans.
     
  • ApplicationContext: An advanced container that extends BeanFactory & adds more enterprise-specific features like AOP, internationalization, & event propagation.
     

In Spring Boot, the ApplicationContext is automatically created & configured based on the application's configuration & dependencies. It serves as the central point of control for the entire application.

17. What is the role of the @SpringBootTest annotation?

The @SpringBootTest annotation is used for integration testing in Spring Boot applications. It is placed on a test class & tells Spring Boot to load the full application context for testing purposes.

When @SpringBootTest is used, Spring Boot starts up the application context, initializes all the beans, & makes them available for testing. This allows testing the application end-to-end, including the interaction between different components, controllers, & services.

Some key features of @SpringBootTest include:

  • Loading the full application context, including auto-configuration & bean registration.
     
  • Providing a convenient way to specify the web environment (mock or random port) for testing web endpoints.
     
  • Supporting the injection of beans & dependencies into the test class using @Autowired.
     
  • Integrating with other testing utilities like @MockBean & @SpyBean for mocking dependencies.

 

Here's an example of a test class using @SpringBootTest:

@SpringBootTest
@AutoConfigureMockMvc
class MyControllerTest {
@Autowired
private MockMvc mockMvc;

@Test
void testEndpoint() throws Exception {
    mockMvc.perform(get("/api/endpoint"))
        .andExpect(status().isOk())
        .andExpect(content().string("Hello, World!"));
}
}


In this example, @SpringBootTest initializes the application context, & @AutoConfigureMockMvc enables MockMvc support for testing web endpoints. The test method uses MockMvc to send a request to the endpoint & verifies the response status & content.

@SpringBootTest is a powerful annotation that simplifies integration testing in Spring Boot applications by providing a full application context & enabling end-to-end testing scenarios.

18. What is the @RestController annotation in Spring Boot?

The @RestController annotation in Spring Boot is used to define a controller that handles HTTP requests & returns data in a specific format, typically JSON or XML. It combines the functionality of @Controller & @ResponseBody annotations.

When a class is annotated with @RestController, Spring Boot automatically serializes the returned objects into the appropriate format based on the request's Accept header or the produces attribute of the mapping annotation.

Here's an example of a @RestController:

@RestController
@RequestMapping("/api")
public class MyRestController {
@GetMapping("/hello")
public String hello() {
    return "Hello, World!";
}
@GetMapping("/user")
public User getUser() {
    return new User("John", "Doe");
}
}


In this example, the @RestController annotation indicates that the class is a controller that handles HTTP requests. The @RequestMapping annotation defines the base URL path for the controller.

The hello() method is mapped to the "/api/hello" endpoint using @GetMapping. When this endpoint is accessed, the method returns the string "Hello, World!" directly in the response body.

The getUser() method is mapped to the "/api/user" endpoint. It returns a User object, which will be automatically serialized into JSON format & sent in the response body.

By using @RestController, you can easily create RESTful APIs that return data in a structured format without the need for explicit view rendering or manual serialization.

@RestController is commonly used in building microservices or backend APIs where the primary focus is on exchanging data rather than serving web pages. It simplifies the process of creating endpoints that expose data in a consumable format for client applications.

19. What is Spring Boot CLI & how do you use it?

Spring Boot CLI (Command Line Interface) is a command-line tool that allows for quickly running Spring Boot applications with minimal setup. It supports running Groovy scripts with Spring Boot features embedded.

To use Spring Boot CLI:

  • Install the CLI by downloading the distribution & adding it to your PATH.
     
  • Create a Groovy script with the necessary Spring Boot annotations & code.
     
  • Run the script using the spring run command, e.g., spring run app. groovy.
     

The CLI takes care of resolving dependencies & starting the application. It's useful for quick prototyping or running simple applications without setting up a full project structure.

20. How do you handle exceptions in a Spring Boot application?

In a Spring Boot application, exceptions can be handled using the @ExceptionHandler annotation. This annotation is used on methods within a @Controller or @RestController class to define custom exception handling logic.

Here's an example:

@RestController
public class MyController {
@GetMapping("/example")
public String getExample() {
    // Code that may throw an exception
    throw new CustomException("Something went wrong");
}
@ExceptionHandler(CustomException.class)
public ResponseEntity<String> handleCustomException(CustomException ex) {
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage());
}
}


In this example, if the getExample() method throws a CustomException, the handleCustomException() method annotated with @ExceptionHandler will be invoked. It takes the exception as a parameter & returns a ResponseEntity with an appropriate HTTP status & the exception message in the response body.

Spring Boot also provides a global exception handling mechanism using the @ControllerAdvice annotation. You can define exception handling methods in a separate class annotated with @ControllerAdvice, & they will be applied across all controllers in the application.

Advanced Spring Boot and Microservices Interview Questions

21. What is the purpose of using @ComponentScan in the class files?

The @ComponentScan annotation is used in Spring Boot to specify the base packages where the application should scan for components (beans). It tells Spring to look for classes annotated with @Component, @Service, @Repository, @Controller, etc., within the specified packages & their sub-packages.

By default, Spring Boot uses the package of the main class (annotated with @SpringBootApplication) as the base package for component scanning. However, you can override this behavior by explicitly specifying the packages to scan using @ComponentScan.

Here's an example:

@SpringBootApplication
@ComponentScan(basePackages = {"com.example.package1", "com.example.package2"})
public class MyApplication {
// ...
}


In this case, Spring Boot will scan the com.example.package1 & com.example.package2 packages & their sub-packages for components.

Using @ComponentScan helps in modularizing the application & keeping the components organized in separate packages. It allows Spring to automatically discover & register beans from the specified packages without the need for explicit configuration.

22. What differentiates Spring Data JPA & Hibernate?

Spring Data JPA & Hibernate are both related to database persistence in Java applications, but they serve different purposes:

Hibernate

  • Hibernate is an Object-Relational Mapping (ORM) framework that simplifies the mapping between Java objects & relational database tables.
     
  • It provides a way to define entity classes that represent database tables & perform database operations using object-oriented techniques.
     
  • Hibernate focuses on the low-level interaction with the database & provides features like caching, lazy loading, & transaction management.

Spring Data JPA

  • Spring Data JPA is a higher-level abstraction built on top of Hibernate (or other JPA providers).
     
  • It simplifies the implementation of data access layers by providing repository interfaces & common CRUD operations.
     
  • Spring Data JPA eliminates the need to write boilerplate code for database interactions & provides a consistent programming model across different persistence technologies.
     
  • It offers features like query creation from method names, pagination, & sorting.
     

In summary, Hibernate is an ORM framework that handles the low-level database interaction, while Spring Data JPA is a higher-level abstraction that builds on top of Hibernate (or other JPA providers) to provide a simpler & more productive programming model for data access.

Spring Data JPA uses Hibernate as the default JPA provider but also supports other providers like EclipseLink. It abstracts away the low-level details & provides a more convenient way to work with databases in Spring applications.

23. How are the @RestController & @Controller annotations different?

The @Controller & @RestController annotations in Spring Boot are used to define controller classes, but they have some differences:

@Controller

  • Indicates that the class is a Spring MVC controller.
     
  • Typically used for serving web pages & handling user interactions.
     
  • Requires explicit mapping of request methods to handler methods using annotations like @GetMapping, @PostMapping, etc.
     
  • Returns a view name or a ModelAndView object, which is then resolved by a view resolver to render the appropriate view template.

@RestController

  • A specialized version of @Controller that is used for building RESTful web services.
     
  • Combines the @Controller & @ResponseBody annotations.
     
  • Automatically serializes the return value of each method into the response body, typically in JSON or XML format.
     

Suitable for creating endpoints that return data rather than views.

Here's an example of a @Controller:

@Controller
public class MyController {
@GetMapping("/hello")
public String hello(Model model) {
    model.addAttribute("message", "Hello, World!");
    return "hello";
}
}


In this case, the hello() method returns the view name "hello", which is resolved by the view resolver to render the corresponding view template (e.g., hello.html) with the "message" attribute.

Here's an example of a @RestController:

@RestController
public class MyRestController {
@GetMapping("/api/hello")
public String hello() {
    return "Hello, World!";
}
}


In this case, the hello() method directly returns the string "Hello, World!", which is automatically serialized & sent as the response body when the "/api/hello" endpoint is accessed.

The main difference is that @Controller is used for handling web requests & returning views, while @RestController is used for creating RESTful APIs that return data directly in the response body.

24. Describe the flow of HTTPS requests through the Spring Boot application.

When an HTTPS request is made to a Spring Boot application, it goes through the following flow:

SSL/TLS Handshake

  • The client initiates an SSL/TLS handshake with the server to establish a secure connection.
     
  • The server presents its SSL/TLS certificate, & the client verifies it.
     
  • If the certificate is valid, the client & server negotiate encryption keys & establish a secure communication channel.

Request Handling

  • The HTTPS request reaches the server & is received by the embedded web server (e.g., Tomcat, Jetty) in Spring Boot.
     
  • The embedded web server decrypts the request using the established encryption keys.
     
  • The decrypted request is then passed to the Spring Boot application.

Dispatching to the Controller

  • Spring Boot's dispatcher servlet maps the request to the appropriate controller based on the URL & HTTP method.
     
  • The request is routed to the corresponding controller method annotated with request mapping annotations (@GetMapping, @PostMapping, etc.).

Request Processing

  • The controller method receives the request & performs the necessary processing.
     
  • It may interact with services, repositories, or other components to fetch or manipulate data.
     
  • The controller method prepares the response data.

Response Preparation

  • If the controller method returns a view name, the view resolver resolves it to the appropriate view template.
     
  • The view template is rendered with the response data to generate the HTML response.
     
  • If the controller method is annotated with @ResponseBody or the controller is a @RestController, the response data is directly serialized (e.g., to JSON or XML).

Response Encryption

  • The response is encrypted using the established encryption keys from the SSL/TLS handshake.
     
  • The encrypted response is sent back to the client over the secure communication channel.

Client Receives Response

  • The client receives the encrypted response & decrypts it using the encryption keys.
     
  • The decrypted response is then processed by the client application or displayed to the user.

Throughout this flow, Spring Boot handles the request processing, controller mapping, view resolution, & response preparation. The embedded web server & SSL/TLS configuration ensure secure communication between the client & the server.

Spring Boot provides easy configuration options for enabling HTTPS, such as configuring SSL/TLS certificates & specifying the HTTPS port in the application.properties or application.yml file.

By following this flow, Spring Boot applications can securely handle HTTPS requests, ensuring the confidentiality & integrity of the data exchanged between the client & the server.

25. What is the difference between RequestMapping & GetMapping?

The @RequestMapping & @GetMapping annotations in Spring Boot are used to map HTTP requests to controller methods, but they have some differences:

@RequestMapping

  • A general-purpose annotation used to map HTTP requests to controller methods.
     
  • Supports multiple HTTP methods (GET, POST, PUT, DELETE, etc.) by specifying the method attribute.
     
  • If the method attribute is not specified, it maps to any HTTP method.
     
  • Can be used at the class level to define a base URL path for all methods in the controller.

@GetMapping

  • A specialized version of @RequestMapping specifically for HTTP GET requests.
     
  • Equivalent to @RequestMapping(method = RequestMethod.GET).
     
  • Used to map HTTP GET requests to controller methods.
     
  • Provides a more readable & specific way to handle GET requests.

Here's an example using @RequestMapping:

@Controller
@RequestMapping("/api")
public class MyController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() {
    return "Hello, World!";
}
}


In this case, the hello() method is mapped to the HTTP GET request for the "/api/hello" endpoint using @RequestMapping with the method attribute set to RequestMethod.GET.

Here's an equivalent example using @GetMapping:

@Controller
@RequestMapping("/api")
public class MyController {
@GetMapping("/hello")
public String hello() {
    return "Hello, World!";
}
}


In this case, the hello() method is mapped to the HTTP GET request for the "/api/hello" endpoint using @GetMapping, which specifically handles GET requests.

The main difference is that @RequestMapping is a general-purpose annotation that can handle multiple HTTP methods, while @GetMapping is a specialized annotation specifically for HTTP GET requests.

Using @GetMapping provides better readability & clarity in the code, as it explicitly indicates that the method handles GET requests. It also eliminates the need to specify the method attribute explicitly.

Similarly, there are other specialized annotations like @PostMapping, @PutMapping, & @DeleteMapping for handling HTTP POST, PUT, & DELETE requests, respectively.

26. What annotations are used to create an interceptor?

In Spring Boot, interceptors are used to intercept & preprocess or postprocess requests & responses. To create an interceptor, you need to use the following annotations:

@Component

  • This annotation is used to mark the interceptor class as a Spring component.
     
  • It enables Spring Boot to automatically detect & register the interceptor bean.

@Order or @Priority

  • These annotations are used to specify the order or priority of the interceptor.
     
  • Interceptors with a higher priority (lower numeric value) are executed before interceptors with a lower priority.
     
  • If multiple interceptors are configured, the order determines the sequence in which they are applied.

HandlerInterceptor interface

  • The interceptor class needs to implement the HandlerInterceptor interface provided by Spring.
     
  • This interface defines three methods: preHandle(), postHandle(), & afterCompletion().
     
  • These methods allow you to perform actions before the request is handled, after the request is handled but before the view is rendered, & after the complete request-response cycle, respectively.
     

Here's an example of creating an interceptor:

@Component
@Order(1)
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // Perform pre-handling logic
    return true; // Return true to continue the request processing
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    // Perform post-handling logic
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    // Perform cleanup or logging after the request-response cycle
}
}


In this example, the MyInterceptor class is annotated with @Component to make it a Spring component. It implements the HandlerInterceptor interface & overrides the preHandle(), postHandle(), & afterCompletion() methods to define the interceptor logic.

The @Order(1) annotation specifies the priority of the interceptor. A lower numeric value indicates a higher priority.

To register the interceptor, you need to configure it in a configuration class that extends the WebMvcConfigurer interface:

@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private MyInterceptor myInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(myInterceptor);
}
}


In this configuration class, the addInterceptors() method is overridden to register the MyInterceptor with the InterceptorRegistry.

By using these annotations & implementing the HandlerInterceptor interface, you can create custom interceptors in Spring Boot to perform cross-cutting concerns, such as logging, authentication, or request/response modification.

27. What are the differences between @SpringBootApplication & @EnableAutoConfiguration annotations?

The @SpringBootApplication & @EnableAutoConfiguration annotations are both used in Spring Boot applications, but they serve different purposes:

@SpringBootApplication

  • A convenience annotation that combines three annotations: @Configuration, @EnableAutoConfiguration, & @ComponentScan.
     
  • Typically used on the main class of a Spring Boot application.
     
  • Indicates that the class is a configuration class, enables auto-configuration, & performs component scanning in the current package & its sub-packages.
     
  • Provides a single annotation to bootstrap a Spring Boot application with default settings.
     

Here's an example of using @SpringBootApplication:

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

@EnableAutoConfiguration

  • An annotation that enables Spring Boot's auto-configuration mechanism.
     
  • Instructs Spring Boot to automatically configure beans based on the classpath dependencies & the defined configuration.
     
  • Attempts to create & configure beans that are commonly used in Spring applications, such as DataSource, JdbcTemplate, EntityManagerFactory, etc.
     
  • Can be used in combination with @Configuration & @ComponentScan annotations.
     

Here's an example of using @EnableAutoConfiguration:

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class MyConfiguration {
// Additional configuration or bean definitions
}

The main differences between @SpringBootApplication & @EnableAutoConfiguration are:

Purpose

  • @SpringBootApplication is a convenience annotation that combines multiple annotations to bootstrap a Spring Boot application with default settings.
     
  • @EnableAutoConfiguration is a specific annotation that enables auto-configuration in Spring Boot.

Usage

  • @SpringBootApplication is typically used on the main class of a Spring Boot application.
     
  • @EnableAutoConfiguration can be used in combination with @Configuration & @ComponentScan annotations in a configuration class.

Composition

  • @SpringBootApplication includes @EnableAutoConfiguration, along with @Configuration & @ComponentScan.
     
  • @EnableAutoConfiguration is a standalone annotation that focuses solely on enabling auto-configuration.
     

In most cases, using @SpringBootApplication on the main class is sufficient to bootstrap a Spring Boot application with auto-configuration, component scanning, & other default settings. It provides a convenient way to get started quickly.

However, if you have a specific need to customize the configuration or have multiple configuration classes, you can use @EnableAutoConfiguration along with @Configuration & @ComponentScan annotations to achieve more fine-grained control over the application setup.

28. How to enable debugging log in the Spring Boot application?

To enable debugging log in a Spring Boot application, you can configure the logging level in the application.properties or application.yml file. Here are the steps to enable debugging log:

Open the application.properties or application.yml file in your Spring Boot project.

Add the following line to set the logging level to DEBUG for the desired package or class:

For application.properties:

logging.level.com.example.package=DEBUG
For application.yml:
logging:
  level:
    com.example.package: DEBUG

 

  • Replace com.example.package with the actual package or class for which you want to enable debugging log.
     
  • If you want to enable debugging log for the entire application, you can set the root logging level to DEBUG:
     

For application.properties:

logging.level.root=DEBUG

For application.yml:
logging:
  level:
    root: DEBUG

 

  • Save the application.properties or application.yml file.
     
  • Start or restart your Spring Boot application.
     

With these configurations, Spring Boot will output debugging log statements for the specified package, class, or the entire application, depending on your configuration.

  • Spring Boot provides flexibility in configuring logging settings, allowing you to customize the logging behavior based on your application's needs.
     
  • Remember to adjust the logging level appropriately in production environments to avoid performance overhead. The debugging log should be used primarily during the development & troubleshooting phases.
     
  • By enabling debugging logs, you can gain insights into the application's behavior, track the flow of execution, & diagnose issues more effectively during development & debugging sessions.

29. What is dependency injection & its types?

Dependency Injection (DI) is a design pattern & a key principle in Spring Boot that allows the management of object dependencies. It involves providing the required dependencies to an object, rather than the object creating or managing its own dependencies.

In Spring Boot, dependency injection is achieved through the Inversion of Control (IoC) container, which manages the creation, configuration, & lifecycle of objects, known as beans.

There are two main types of dependency injection in Spring Boot:

Constructor Injection:

  • Dependencies are injected through the constructor of a class.
     
  • The IoC container invokes the constructor with the required dependencies.
     
  • Constructor injection ensures that the dependencies are available when the object is created.
     
  • It promotes immutability & makes it clear what dependencies a class requires.

 

Example of constructor injection:

@Component
public class MyService {
    private final MyDependency dependency;

    public MyService(MyDependency dependency) {
        this.dependency = dependency;
    }
}


Setter Injection (or Method Injection):

  • Dependencies are injected through setter methods or any other method of a class.
     
  • The IoC container invokes the setter methods to provide the dependencies after the object is created.
     
  • Setter injection allows for optional dependencies & provides flexibility to change dependencies after object creation.
     

Example of setter injection:

@Component
public class MyService {
    private MyDependency dependency;

    @Autowired
    public void setDependency(MyDependency dependency) {
        this.dependency = dependency;
    }
}


In both cases, the @Autowired annotation is used to indicate that the dependency should be injected by the IoC container. Spring Boot automatically resolves the dependencies based on their types or qualifiers.

There is also a third type of injection called Field Injection, where dependencies are injected directly into the fields of a class using the @Autowired annotation. However, this approach is generally discouraged as it makes testing & maintenance more challenging.

Dependency injection provides several benefits:

  • Loose coupling: Objects are not tightly coupled to their dependencies, making the code more modular & easier to maintain.
     
  • Testability: Dependencies can be easily mocked or replaced during testing, allowing for better unit testing & isolation of components.
     
  • Reusability: Objects can be reused in different contexts since they are not responsible for creating their own dependencies.
     
  • Modularity: Dependencies can be easily swapped or updated without modifying the dependent objects.
     

Spring Boot's dependency injection mechanism simplifies the management of object dependencies & promotes a loosely coupled & modular application architecture.

30. How to connect the Spring Boot application to a database using JDBC?

To connect a Spring Boot application to a database using JDBC (Java Database Connectivity), you need to follow these steps:

Add the necessary dependencies:

  • For JDBC, include the spring-boot-starter-jdbc dependency in your project's build file (pom.xml for Maven or build.gradle for Gradle).
     
  • Add the driver dependency for your specific database (e.g., mysql-connector-java for MySQL).
     
  • Configure the database connection properties:
     

In the application.properties or application.yml file, specify the database connection details.

For example, for MySQL:

  • spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
     
  • spring.datasource.username=myusername
     
  • spring.datasource.password=mypassword
     
  • spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
     

Use the JdbcTemplate:

Spring Boot auto-configures a JdbcTemplate bean that can be injected into your repository or service classes.

Use the JdbcTemplate to execute SQL queries & perform database operations.

Here's an example of a repository class that uses JdbcTemplate:

@Repository
public class UserRepository {
    private final JdbcTemplate jdbcTemplate;
    public UserRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    public List<User> findAll() {
        String sql = "SELECT * FROM users";
        return jdbcTemplate.query(sql, new UserRowMapper());
    }
    public void save(User user) {
        String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
        jdbcTemplate.update(sql, user.getName(), user.getEmail());
    }
}


In this example, the UserRepository class is annotated with @Repository to indicate that it's a Spring repository. It has a constructor that accepts a JdbcTemplate instance, which is automatically injected by Spring Boot.

The findAll() method uses the JdbcTemplate's query() method to execute a SELECT query & map the results to a list of User objects using a custom UserRowMapper.

The save() method uses the JdbcTemplate's update() method to execute an INSERT query & save a new user to the database.

Conclusion

We hope you have gained some insights on Spring Boot and Microservices Interview Questions through this article. We hope this will help you excel in your interviews and enhance your knowledge of Spring Boot and Microservices, and related stuff. 

Recommended Readings:

Live masterclass