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.
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.
<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.
<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.
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=/admin6. How to configure custom endpoint in Spring Boot actuator?
#In order to change the base path from /actuator to something else
management.endpoints.web.exposure.base-path=/admin7. 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.
<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.
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.
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.
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:
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);
}
}10. Can Entity class in Hibernate (JPA) required @Id annotation or primary key?
According to JPA documentation, every entity class must have a primary key that uniquely identifies each record in the database table.
There are situations where we are required to create an entity class without a primary key. In JPA, those entities are considered embedded entities that are part of another entity and do not have a separate existence in the database. In order to use embedded entities, we need to use the @Embeddable annotation over the entities that we want to add to another entity.
import jakarta.persistence.Embeddable;
import lombok.Getter;
import lombok.Setter;
/**
* 1. Mark the Address class with @Embeddable annotation
* 2. This annotation will make it of Embeddable type so,
* that it can be embedded in another class
* @author paulsofts
*/
@Getter
@Setter
@Embeddable
public class Address {
private String street;
private int pin;
private String city;
private String state;
private String country;
}Above, we have annotated the Address class with the @Embeddable annotation, and we will add it to the Employee class.
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import lombok.Getter;
import lombok.Setter;
/**
* 1. We have created Employee class as Entity
* 2. Embedded the Address class
* @author paulsofts
*/
@Entity
@Getter
@Setter
public class Employee {
private int empId;
private String empName;
@Embedded
private Address address;
}11. What is the default maven dependency scope?
The Maven dependency scope is an attribute that is used to set the visibility of the dependency in different lifecycle stages such as build, run, compile, test, etc. The default dependency scope in Maven is compile.
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<!-- We can skip this scope, as it is the default scope -->
<scope>compile</scope>
</dependency>Maven has the following dependency scopes:
- <scope>compile</scope>
- <scope>runtime</scope>
- <scope>provided</scope>
- <scope>test</scope>
- <scope>import</scope>
- <scope>system</scope>
12. In a Spring Boot application, if any exception occurs in the repository layer and we do not want to handle it in the repository layer, instead we want to handle it in the service layer, how can we do that?
In Java, the throws keyword is used for exception propagation. The above scenario can be easily achieved with the help of the throws declaration.
13. How to convert Java object to JSON string?
In order to convert a Java object to a JSON string, we can use any library that supports serialization and de-serialization. For example, Jackson.
import com.fasterxml.jackson.databind.ObjectMapper;
public class Employee {
int empId;
String empName;
public Employee(int empId, String empName) {
super();
this.empId = empId;
this.empName = empName;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public static void main(String[] args) {
String output = "";
Employee employee = new Employee(101, "Bindhiya");
ObjectMapper mapper = new ObjectMapper();
try {
output = mapper.writeValueAsString(employee);
}catch(Exception e) {
e.printStackTrace();
}
System.out.println(output);
}
}14. How to lock version of dependency in Maven?
We can lock the version of a dependency in Maven by specifying the <version> tag in the pom.xml file.
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>3.3.0</version>
</dependency>15. What is Bean in Spring and Spring bean lifecycle?
In Spring, the object that forms the backbone of the application and are managed by the Spring IOC are called beans.
When we run a Spring application, First of all, the Spring container gets started; after that, the container creates the instances of the bean as per requirement, and then their dependencies are injected. After the application completes its execution, the beans are destroyed when the spring container is closed.

Spring Boot indeed simplifies the development process by handling configurations automatically. It’s impressive how it allows developers to focus on the business logic rather than the setup. The use of starter parent dependencies reduces the need for repetitive boilerplate code. I’m curious about how it handles exceptions in the Controller class. What are the best practices for using Pageable and PageRequest in service or controller classes? Have you faced any challenges while implementing these features in your projects?