Spring Boot interview questions for 5 years experience

By | October 11, 2024

1. Why Spring Boot over Spring framework?

Spring vs Spring Boot

The Spring Boot framework is built on top of the Spring framework, and it is used for a rapid production-ready environment that enables the developers to directly focus on the business logic instead of struggling with the configuration and setup; those will be automatically configured as we add dependencies to the pom.xml file. Spring Boot autoconfigures the necessary beans and components, allowing us to skip boilerplate codes.

2. How does autoconfiguration work in Spring Boot?

When we add any spring boot starter project or dependency, Maven pulls all the required jars of that project. In those jars, one of the jars is called the configuration jar. This configuration jar has a directory called META-INF, which contains the spring.factories file. 

The spring.factories file is actually responsible for the autoconfiguration; it contains all the configuration that needs to be active or deactivated depending on some conditions. For example: If we add spring-data-jap, then the JPA will be active and spring boot will autoconfigure JPA.

spirng.factories

3. What is Spring Boot starter parent maven dependency?

The spring boot starter parent dependency is a parent POM (Project Object Model) that simplifies the configuration in a Spring Boot application. It adds a wide range of default settings and dependencies provided by the Spring Boot framework, which helps to reduce the boilerplate configuration and ensure consistent dependency management. Following things are done by the spring boot starter parent dependencies:

  • Dependency Management: The spring boot starter parent dependency implicitly manages the versions for common dependencies such as Spring, Hibernate, Jackson, etc.
  • Common Properties: It implicitly defines the common properties in a Spring Boot application, such as Java version, encoding, etc.; if required, we can override these properties.
  • Default Plugin Configuration: It adds the default configuration of Maven plugins such as Maven JAR, Maven Surefire, etc.
XML
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.1.4</version> <!-- Example version -->
    <relativePath/> <!-- Lookup parent from Maven repository -->
</parent>

4. How to change default server in Spring Boot?

By default, the embedded server that comes in Spring Boot is Tomcat. We can change the default embedded server from Tomcat to any other server such as Jetty or Undertow by using the exclusion tag in the pom.xml file. We need to exclude the Tomcat dependency and add the Jetty dependency.

pom.xml
<dependencies>
    <!-- Spring Boot Web without Tomcat -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    
    <!-- Add Jetty as the server -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>
</dependencies>

5. What is Spring Boot actuators?

The Spring Boot actuator is a production-ready feature that is used to manage and monitor the application with the help of HTTP endpoints. We need to add the spring-boot-starter-actuator dependency, and Spring Boot will automatically configure it and expose an endpoint “/actuator”. Say our application is running locally; it will expose http://localhost:8080/actuator. We can include endpoint urls for beans, health, environment, cache, etc. using the configuration in the application.properties file.

application.properties
management.endpoints.web.exposure.include=beans
management.endpoints.web.exposure.include=cache

#We can enable all the endpoints using * operator
management.endpoints.web.exposure.include=*

#In order to change the base path from /actuator to something else 
management.endpoints.web.exposure.base-path=/admin

6. How to configure custom endpoint in Spring Boot actuator?

application.properties
#In order to change the base path from /actuator to something else 
management.endpoints.web.exposure.base-path=/admin

7. What is Spring Boot Dev Tool and how does DevTools helps to enhance development?

Spring Boot DevTools enhance the development workflow and can be used to achieve faster development by enabling automatic restarts of applications, live reload of the servers, and applying configuration instantly. In order to use DevTools, we need to add the following dependency to our pom.xml file.

Java
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-devtools</artifactId>
  <scope>runtime</scope>
</dependency>

8. What is Global Exception Handling in Spring Boot?

The Global Exception handling in Spring Boot is used to handle the exception globally, that is, throughout the complete application. To implement global exception handling in Spring Boot, we use @ControllerAdvice and @ExceptionHandler annotations in our application.

  • @ControllerAdvice in Spring Boot allows you to handle the exceptions across the complete application in one global handler class.
  • @ExceptionHandler in Spring Boot is used to specify the method that will handle the particular method.
Java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.WebRequest;

@ControllerAdvice
public class GlobalExceptionHandler {

    // Handle NotFoundException
    @ExceptionHandler(NotFoundException.class)
    public ResponseEntity<String> handleNotFoundException(NotFoundException ex, WebRequest request) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }

    // Handle BadRequestException
    @ExceptionHandler(BadRequestException.class)
    public ResponseEntity<String> handleBadRequestException(BadRequestException ex, WebRequest request) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
    }
}

Trigger the exceptions in the Controller class.

Java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExampleController {

    @GetMapping("/find")
    public String findItem(@RequestParam String item) {
        if ("unknown".equalsIgnoreCase(item)) {
            throw new NotFoundException("Item not found: " + item);
        } else if ("bad".equalsIgnoreCase(item)) {
            throw new BadRequestException("Invalid request for item: " + item);
        }
        return "Found item: " + item;
    }
}

9. How to you implement pagination and sorting in Spring Boot application.

In order to implement pagination and sorting, we can use the repository of Spring Data JPA, i.e., PaginationAndSortingRepository.

Java
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
    // Additional query methods can be added here if needed
}

In your service or controller class, use Pageable and PageRequest as follows:

Java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

/**
 * Service class for managing User data with pagination and sorting.
 * Provides methods to retrieve a paginated and sorted list of User entities.
 * 
 * @author ankur.pal
 */
@Service
public class UserService {

    // Injecting the UserRepository to interact with the database.
    @Autowired
    private UserRepository userRepository;

    /**
     * Retrieves a paginated and sorted list of users based on the provided parameters.
     *
     * @param page      the page number to retrieve (0-based index)
     * @param size      the number of records per page
     * @param sortBy    the field to sort by (e.g., "name" or "age")
     * @param direction the sorting direction (either "asc" for ascending or "desc" for descending)
     * @return a Page of User entities based on the provided pagination and sorting options
     */
    public Page<User> getUsers(int page, int size, String sortBy, String direction) {
        
        // Determine the sorting direction (ascending or descending).
        Sort sort = direction.equalsIgnoreCase(Sort.Direction.ASC.name()) 
                    ? Sort.by(sortBy).ascending() 
                    : Sort.by(sortBy).descending();
        
        // Create a Pageable object with the specified page number, size, and sort criteria.
        Pageable pageable = PageRequest.of(page, size, sort);
        
        // Retrieve the paginated and sorted list of users from the repository.
        return userRepository.findAll(pageable);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *