Are you struggling to find the most important and frequently asked Spring Boot interview questions, especially the real-time questions asked in face-to-face interviews at top MNCs like TCS, Infosys, LTI Mindtree, Accenture, Tech Mahindra, PWC, KPMG, and many others?
If yes, take a deep breath because you’ve finally landed in the right place!
On this page, we’ve compiled a list of 60+ Spring Boot interview questions for 4+ years experienced Java developers, covering real scenarios, some hands-on coding patterns, and commonly asked concepts. This is not just a random collection. The writer of this article, Prakash Kumar, has personally attended over 50–60 technical interviews throughout his 7+ years of experience as a Java developer, Spring Boot, Microservices and this list is the result of that practical exposure.
In this post, he has carefully included real interview questions, including both conceptual and scenario-based Spring Boot questions, that cover everything from annotations and dependency injection to configuration, auto-wiring, REST APIs, Actuator, and microservice integrations.
💡 This resource is most helpful for fresher to 4 years experienced Spring boot developers.
👉 If you’re more experienced (4+ years), this blog is best for you!
⚙️ Don’t Just Stop at Spring Boot – Prepare Java Too!
If you’re preparing for Spring Boot interviews, it’s important to also brush up on core Java and Java 8 functional programming concepts, as most interviews combine all three.
To take your preparation to the next level, check out these resources:
🔗 Java 8 Scenario-Based Questions Using Employee Class — Highly practical and often asked in real interviews.
🔗 Java 8 Real-World Coding Questions — Perfect for mid to senior-level rounds.
🔗 Java Programming Interview Questions for Freshers & Experienced (2025) — Updated for the latest trends.
🔗 Java Interview Questions for Experienced – Asked in MNCs — A must-read if you’re targeting top-tier companies.
🚀 Now, let’s begin with the most essential:
Most Frequently asked Real Spring Boot Questions
1. What is Spring Boot? How does it differ from the Spring framework?
Spring Boot is an open-source Java framework built on top of the Spring Framework. It helps developers to create easily production-ready, stand-alone, and microservice-based applications with less effort. It provides a various dependency that helps to integrated desired library in the project very easily by just adding in the POM.xml file.
Traditional Spring requires significant boilerplate code and configuration, typically done through XML or annotations.
Key Differences Spring vs Spring Boot
Feature | Spring Framework | Spring Boot |
---|---|---|
Setup | Manual configuration | Auto-configuration |
Server | External server required | Embedded server (e.g., Tomcat) |
Boilerplate Code | More | Minimal |
Deployment | .war file | Runnable .jar file |
Learning Curve | Steeper | Easier and faster to get started |
Microservices Support | Requires setup | Built-in features |
2. Explain the advantages of Using Spring Boot.
Advantages of Spring Boot
- Rapid Development: Spring Boot reduces the need for writing a lot of boilerplate code. It allowing developers to focus on business logic rather than dependency configuration.
- Microservices: Spring boot is the well-suited and popular java framework for building microservices applications. It is possible because of its modular and self-contained nature.
- Auto-Configuration: It automatically configures application components based on dependencies present in the classpath.
- Embedded Servers: Spring Boot comes with embedded servers like Tomcat, Jetty, and Undertow, making deployment easier. We need only pom.xml file configurations.
- Production-Ready: Built-in features like health checks, metrics, and security make applications ready for production deployment.
- Easy Testing: Spring Boot supports various testing frameworks, making unit and integration testing simpler.
3. What are the Different Ways to Create a Spring Boot Application?
Different Ways to Create a Spring Boot Application
1. Spring Initializr
- Web-Based Tool: Use Spring Initializr to generate a Spring Boot project.
- Configuration: Choose your project type (Maven/Gradle), language (Java/Kotlin/Groovy), Spring Boot version, and dependencies.
- Download: Click on “Generate” to download a zip file containing the project structure.
2. IDE Integration
- Eclipse/STS: Use Spring Tool Suite (STS) or Eclipse with the Spring plugin to create a Spring Boot project directly from the IDE.
- IntelliJ IDEA: Use IntelliJ IDEA (Ultimate Edition) which has built-in support for Spring Boot project creation via its New Project wizard.
3. Command Line Interface (CLI)
- Spring Boot CLI: Install the Spring Boot CLI and use command-line commands to create and run Spring Boot applications.
- Example: You can create an application using a Groovy script file, which can be executed directly with the CLI.
4. Manual Setup
- Configuration: Manually set up the project structure, main application class, and configuration files.
- Maven/Gradle: Create a new Maven or Gradle project manually and include Spring Boot dependencies in the
pom.xml
orbuild.gradle
file.
4. Can you walk me through the steps you follow to deploy your Spring Boot application in a production environment?
You can answer this what you have used in your spring boot project. It will depend on your project.
Here Some basic steps are mentioned. To deploy a Spring Boot application in production, I first package it as a JAR using Maven or Gradle. Then, I set up the environment variables and external configurations. Next, I deploy the JAR on a production server (like AWS EC2, Docker container, or Kubernetes). I use a reverse proxy like Nginx, ensure proper logging and monitoring are in place (via Prometheus, ELK, etc.), and configure security settings like HTTPS and CORS. Finally, I test the APIs, set up backups, and enable health checks for uptime monitoring.
5. What Spring version are you using currently? Can you mention some of its latest features?
Currently, I’m using Spring Boot 3.2, which is built on top of Spring Framework 6. It fully supports Java 17+ and embraces Jakarta EE 10. Some of its latest features include virtual thread support from Project Loom, improved observability with Micrometer and tracing, native compilation using GraalVM for faster startups, and enhanced support for modular applications using the new spring-modulith
project. It also has better integration with modern cloud-native patterns and Spring Cloud updates
6. How does Spring Boot Simplify the Configuration Process?
Spring Boot simplifies the configuration process in many ways for the developer. It makes setup and configuration process easier for developers. It allows developers to focus more on writing business logic instead of boilerplate code and complex configurations. It provides several key features that automate and streamline the configuration workflow.
Some key features that simplify the configuration process are
1). Auto-Configuration
Automatically configures Spring beans based on the dependencies present in the classpath. No need for manual XML or Java config for most common setups.
2). Starter Dependencies
Spring Boot provides pre-defined starter POMs (e.g., spring-boot-starter-web
, spring-boot-starter-data-jpa
) that bundle commonly used dependencies, reducing version conflicts and setup effort.
3). Default Configuration
Provides sensible default settings, so you can get up and running with minimal configuration.
4). Property Binding
Easily map application properties from application.properties
or application.yml
to Java classes using @ConfigurationProperties
.
5). Profile Management
Supports environment-specific configurations through profiles (e.g., application-dev.properties
, application-prod.properties
).
6). Embedded Servers
Comes with embedded servers like Tomcat, Jetty, or Undertow — no need for external server setup.
7). Production-Ready Actuators
Provides built-in endpoints for monitoring and managing the application health, metrics, and environment, reducing the need for external tools.
8). Spring Boot CLI (Command Line Interface)
Allows rapid prototyping using Groovy-based scripts without needing full Java compilation or build setup.
7. What is the purpose of the @SpringBootApplication annotation?
@SpringBootApplication annotation is used to mark the main class of a Spring Boot application. It is basically a starting point of the spring boot applications. It combines three annotations: @SpringBootConfiguration, @EnableAutoConfig
uration
, and @ComponentScan.
@SpringBootConfiguration
: This indicates that the class is a configuration class and can be used by the Spring IoC (Inversion of Control) container as a source of bean definitions. The class annotated with @SpringBootApplication
typically contains the main
method, which serves as the entry point for the application. The main
method uses SpringApplication.run()
to launch the Spring application.
@EnableAutoConfiguration
: This enables Spring Boot’s auto-configuration feature, allowing the framework to automatically configure beans based on the dependencies present on the classpath. For example, if Spring MVC is in the classpath, Spring Boot will automatically configure a web application context.
@ComponentScan
: This tells Spring to scan the package where the annotated class is located and its sub-packages for components, configurations, and services. This is essential for detecting Spring-managed components (e.g., @Component
, @Service
, @Repository
) so that they can be registered in the application context.
8. Explain the auto-configuration feature in Spring Boot.
Spring Boot’s auto-configuration automatically configures Spring beans based on the libraries and dependencies detected on the classpath without requiring explicit configuration by the developer. It eliminates the need for manual bean configuration, making the application setup more convenient and faster.
How auto-configuration Works:
- When you run a Spring Boot application, the
@EnableAutoConfiguration
annotation (part of@SpringBootApplication
) triggers the auto-configuration mechanism. - Spring Boot scans your classpath and applies sensible default configurations for common frameworks like Spring MVC, JPA, MongoDB, RabbitMQ, etc.
- For example, if Spring Boot detects
spring-boot-starter-data-jpa
, it will auto-configure:- A DataSource
- EntityManagerFactory
- TransactionManager
9. How can you Customize the default behavior of Spring Boot?
Spring Boot’s default behavior can be customized by providing our own configuration classes, defining custom beans, or overriding default properties in application.properties
or application.yml
.
We can also override or replace auto-configured beans to fit specific application needs. Additionally, using conditional annotations like @ConditionalOnMissingBean
allows flexible customization without breaking the default setup.
10. How does Spring Boot support the development of microservices?
Spring Boot supports the development of microservices by providing a lightweight framework that simplifies the creation and deployment of individual services. It enables rapid development through its auto-configuration and starter dependencies, which streamline the setup process.
Spring Boot also includes features like embedded servers, which allow microservices to run independently without external server configuration. Additionally, it integrates seamlessly with Spring Cloud, offering tools for service discovery, load balancing, circuit breakers, and configuration management. These capabilities facilitate the building of scalable, resilient, and easily deployable microservices architectures.
11. What is Spring Boot Actuator and What are its main functionalities?
Spring Boot Actuator is a set of monitoring tool provided by the spring boot. It helps in production to monitor the spring boot application health and many more. It helps to monitor and manage applications by exposing various endpoints, such as health, metrics, info, and more.
Its main functionality includes
- Health Checks: It offers endpoints to check the health status of the application and its components, allowing you to ensure that the application is running smoothly.
- Metrics Gathering: Actuator collects various application metrics, such as memory usage, request counts, and response times, providing insights into performance and resource consumption.
- Application Environment: It exposes information about the application environment, including configuration properties and active profiles.
- Custom Endpoints: Developers can create custom endpoints to expose additional application-specific information or functionality.
- Monitoring and Management: Actuator integrates with monitoring tools like Prometheus and Grafana, enabling real-time monitoring and alerting.
12. How do you enable Actuator endpoints in a Spring Boot application?
Actuator endpoints can be enabled by adding the spring-boot-starter-actuator
dependency to your project’s pom.xml
file. The endpoints are enabled by default, but you can configure which ones to expose and their properties.
13. Can you enable actuator in dev environment?
Yes, I can enable Actuator in the dev environment by adding the spring-boot-starter-actuator
dependency. Then I configure the desired endpoints in application-dev.properties
or application.yml
using profiles. For example, I set management.endpoints.web.exposure.include=*
to expose all endpoints during development, but restrict them in production for security reasons.
14. What are some commonly used Actuator endpoints?
/actuator/health: Provides information about the health of the application.
/actuator/metrics: Exposes application metrics.
/actuator/info: Displays custom application information.
/actuator/env: Shows properties from the application’s environment.
15. How can you secure Actuator endpoints in Spring Boot?
Actuator endpoints are sensitive, so by default, only a few are exposed. To secure them, I configure Spring Security to require authentication and roles for access. I use application.properties
to expose specific endpoints (e.g., management.endpoints.web.exposure.include=health,info
) and secure them by defining role-based access rules in the security configuration class. This ensures only authorized users can access critical actuator endpoints like /env
, /beans
, or /metrics
16. How do you implement a custom health indicator in Spring Boot?
To implement a custom health indicator in Spring Boot, we will create a class that implements the HealthIndicator
interface and override the health()
method. Inside this method, we define the logic to check the health of a specific component like a database, external API, or custom service. Finally, We annotate the class with @Component
so Spring Boot picks it up automatically and includes it in the /actuator/health
endpoint.
Example
@Component
public class MyServiceHealthIndicator implements HealthIndicator {
@Override
public Health health() {
boolean serviceIsUp = checkMyServiceHealth();
if (serviceIsUp) {
return Health.up().withDetail("MyService", "Available").build();
} else {
return Health.down().withDetail("MyService", "Unavailable").build();
}
}
private boolean checkMyServiceHealth() {
// custom logic here
return true;
}
}
17. How do you expose custom metrics in Spring Boot?
To expose custom metrics in Spring Boot, define and register custom Meter
types like Counter
, Gauge
, or Timer
using the Micrometer API, which is integrated with Spring Boot Actuator. These metrics are automatically exposed via the /actuator/metrics
endpoint.
For example, inject MeterRegistry
and register a custom metric:
@Component
public class CustomMetrics {
private final Counter customCounter;
public CustomMetrics(MeterRegistry meterRegistry) {
this.customCounter = meterRegistry.counter("custom_metric_counter");
}
public void increment() {
customCounter.increment();
}
}
To view or consume these metrics, expose the metrics endpoint by configuring:
management.endpoints.web.exposure.include=metrics
18. What is the purpose of the @RestController annotation?
In Spring Boot Framework, @RestController annotation is used to indicate that a class is a specialized version of the @Controller class. It is used in building RESTful web services. It combines @Controller and @ResponseBody, indicating that the methods in the class return the response body directly. List of the @RestController annotations purpose are Creating REST Endpoints, Response Serialization, No Need for @ResponseBody etc.
19. Explain the difference between @Controller and @RestController in Spring Boot.
In Spring Boot, both @Controller
and @RestController
are used to handle HTTP requests and build web applications.
@Controller
- The @Controller annotation is used to mark a class as a Spring MVC controller.
- Controllers are responsible for handling incoming HTTP requests, processing them, and returning an appropriate response. They are commonly used to create dynamic web pages where the response might include HTML templates and view rendering.
- Methods within a @Controller class are typically responsible for returning logical view names, which are resolved to actual view templates for rendering.
@RestController
- The @RestController annotation is a specialized version of @Controller that is tailored for building RESTful web services.
- Classes annotated with @RestController still handle incoming HTTP requests, but their primary focus is on returning data in various formats like JSON or XML, rather than rendering views.
- Methods within a @RestController class automatically have the @ResponseBody annotation applied to them, meaning that the return values of these methods are directly serialized into the response body.
20. What is the purpose of the @RequestBody and @ResponseBody annotations in Spring Boot?
@RequestBody:
Used to bind the incoming HTTP request body (usually in JSON format) directly to a Java object. It allows automatic deserialization of JSON/XML into Java POJOs using the configured message converters (e.g., Jackson).
Usage:
Helps in handling POST, PUT, or PATCH requests where data is sent in the request body and needs to be deserialized into a Java object.
RequestBody Example
@PostMapping("/users")
public ResponseEntity<String> addUser(@RequestBody User user) {
// 'user' object is automatically populated from JSON request
return ResponseEntity.ok("User added");
}
@ResponseBody:
Indicates that the return value of a method should be written directly to the HTTP response body, instead of rendering a view. It enables automatic serialization of Java objects to JSON/XML.
Usage:
Commonly used in REST APIs to send data back as a response.
ResponseBody Example
@GetMapping("/users")
@ResponseBody
public List<User> getUsers() {
return userService.getAllUsers(); // returned as JSON
}
Basically
RestController = @Controller + @ResponseBody
21. What’s the difference between @Bean
and @Component
annotations in Spring?
Aspect | @Bean | @Component |
---|---|---|
Definition | Declares a bean manually in a configuration class. | Marks a class as a Spring-managed component. |
Placement | Used on methods inside a @Configuration class. | Used directly on the class itself. |
Control | Provides fine-grained control over bean instantiation. | Relies on classpath scanning and automatic detection. |
Use Case | Best for third-party classes or when full control over the bean creation is needed. | Best for application-specific classes like services, repositories, or controllers. |
Example | @Bean public DataSource dataSource() { return new DataSource(); } | @Component public class UserService {} |
22. What is Spring Data JPA and how does it work with Spring Boot?
Spring Data JPA is a tool provided by Spring that helps in working with databases easily. It sits on top of JPA and removes the need to write boilerplate code like SQL queries or EntityManager. With it, we can just create interfaces and Spring will automatically generate the code to perform common database operations like save, update, delete, and find.
Example for Spring Data JPA
// Step 1: Entity Class
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and Setters
}
// Step 2: Repository Interface
public interface UserRepository extends JpaRepository<User, Long> {
// Spring will create the implementation at runtime
List<User> findByEmail(String email);
}
// Step 3: Using the Repository in a Service or Controller
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void createUser() {
User user = new User();
user.setName("John");
user.setEmail("[email protected]");
userRepository.save(user); // No SQL needed
}
}
23. What are the differences between CrudRepository
and JpaRepository
?
CrudRepository
provides only the basic CRUD operations like save, findById, and delete. But JpaRepository
extends it and adds more powerful features like pagination, sorting, batch processing, and flush operations. So, if the project needs full JPA functionality, it’s better to use JpaRepository
.
Differences
Feature | CrudRepository | JpaRepository |
---|---|---|
Inheritance | Extends Repository | Extends PagingAndSortingRepository , which in turn extends CrudRepository |
Basic Operations | Supports basic CRUD operations like save() , findById() , delete() , etc. | Inherits all methods of CrudRepository and adds more JPA-specific features |
Additional Methods | Minimal set of methods | Adds advanced methods like flush() , saveAndFlush() , findAll(Sort sort) , and batch operations |
Pagination & Sorting | Not available | Supported out of the box |
Use Case | Suitable for simple CRUD operations | Recommended for full JPA support and advanced operations |
24. How do you use RestTemplate in Spring Boot?
RestTemplate
is used to call external REST APIs from a Spring Boot application. First, a RestTemplate
bean is created using @Bean
. Then it’s injected wherever needed to perform HTTP operations like GET, POST, PUT, and DELETE. It simplifies communication between microservices or with third-party APIs.
It is a synchronous client provided by Spring to make HTTP requests to other RESTful services (like GET, POST, PUT, DELETE).
Steps to Use RestTemplate
Define RestTemplate
Bean
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Inject and Use RestTemplate
@Service
public class ApiService {
@Autowired
private RestTemplate restTemplate;
public String getUserData() {
String url = "https://api.example.com/users/1";
return restTemplate.getForObject(url, String.class);
}
}
25. Can you tell me what is bean and its scope?
A Bean in Spring is an object that is managed by the Spring IoC (Inversion of Control) container. It is created, configured, and maintained by the container, and it can be injected wherever needed using dependency injection.
Spring Beans help in managing application components in a clean, modular, and loosely-coupled way.
Bean Scope
Bean Scope defines the lifecycle and visibility of a bean within the Spring container i.e., how many times a new instance of the bean will be created and where it will be used. By default, Spring beans are singleton, meaning the same instance is used across the application. But we can change it to prototype, request, or other scopes depending on our use case.
Types of Bean Scopes in Spring
Scope Name | Description |
---|---|
singleton (default) | Only one instance per Spring container. |
prototype | A new bean instance is created every time it is requested. |
request | One instance per HTTP request (used in web apps). |
session | One instance per HTTP session. |
application | One instance per ServletContext. |
websocket | One instance per WebSocket session. |
26. How are you handling exceptions in your Spring Boot application? How global exception handling works in Spring Boot @ExceptionHandler
and @ControllerAdvice
?
Exception handling is a critical aspect of building robust and user-friendly applications. In Spring Boot, there are several mechanisms to manage exceptions gracefully, ensuring that your application can recover from errors or provide meaningful feedback to the user.
In Spring Boot, Exception handling is centralized using @ControllerAdvice
in Spring Boot. It allows defining global error-handling logic for all controllers in one place. Inside the class, different methods annotated with @ExceptionHandler
handle specific exceptions and return proper HTTP responses.
For custom business errors, custom exception classes are created and annotated with @ResponseStatus
to define appropriate HTTP status codes like 404 or 400. This approach makes the error handling clean, reusable, and user-friendly.
Example for @ControllerAdvice
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGeneral(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Something went wrong");
}
}
Custom Exception Example
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
27. Exception Handling in Spring Boot (Including Validation & REST API).
In my Spring Boot application, exception handling is done in a structured and centralized way using @ControllerAdvice
. This helps capture and handle exceptions globally across all REST controllers. Inside the @ControllerAdvice
class, I use @ExceptionHandler
methods to catch specific exceptions like ResourceNotFoundException
, IllegalArgumentException
, or any custom business exceptions. Each handler returns a meaningful error response with the correct HTTP status code.
For validation errors, Spring Boot integrates with @Valid
and BindingResult
or throws MethodArgumentNotValidException
, which I catch in the global exception handler to return detailed error messages for each invalid field.
Custom exception classes are also used, annotated with @ResponseStatus
, to automatically map business-level exceptions to appropriate HTTP responses like 400 (Bad Request) or 404 (Not Found).
Validation Example with @Valid
and Exception Handling
1. DTO with Validation Annotations
public class UserDTO {
@NotBlank(message = "Name is required")
private String name;
@Email(message = "Email must be valid")
private String email;
// Getters and Setters
}
2. Controller
@PostMapping("/users")
public ResponseEntity<String> createUser(@Valid @RequestBody UserDTO user) {
// Logic to save user
return ResponseEntity.ok("User created");
}
3. Global Exception Handler for Validation
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidationErrors(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error ->
errors.put(error.getField(), error.getDefaultMessage())
);
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleAll(Exception ex) {
return new ResponseEntity<>("An unexpected error occurred", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
28. How do you handle cross-cutting concerns like logging and exception handling in Spring Boot?
In Spring Boot, cross-cutting concerns like logging and exception handling are handled using Aspect-Oriented Programming (AOP) and global exception handling mechanisms.
1. Logging
SLF4J and Logback: Spring Boot uses SLF4J (Simple Logging Facade for Java) with Logback as the default logging framework. You can log application events using the Logger
API, which provides various logging levels such as INFO
, DEBUG
, WARN
, and ERROR
.
Custom Logging with AOP: You can create custom aspects using AOP to log method execution times, method calls, or return values. This allows you to separate logging logic from business logic.
@Aspect
@Component
public class LoggingAspect {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Before("execution(* com.example.service.*.*(..))")
public void logBeforeMethod(JoinPoint joinPoint) {
logger.info("Method called: " + joinPoint.getSignature().getName());
}
}
2. Global Exception Handling
@ControllerAdvice: Spring Boot provides the @ControllerAdvice
annotation to handle exceptions globally. By using this annotation with @ExceptionHandler
methods, you can catch and handle exceptions across multiple controllers in one place.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleResourceNotFound(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGenericException(Exception ex) {
return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
In summary, cross-cutting concerns like logging and exception handling are managed in Spring Boot using logging frameworks and global exception handling mechanisms, keeping the application clean, modular, and maintainable.
29. How do you define or configure database connections in your Spring Boot application?
Database connections in Spring Boot can be configure properties in the application.properties or application.yml file. Spring Boot provides auto-configuration for various databases, and you can also customize the configuration.
application.properties
# Database configuration
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=myuser
spring.datasource.password=mypassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
application.yml
# Database configuration
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: myuser
password: mypassword
driver-class-name: com.mysql.cj.jdbc.Driver
30. Explain the use of Spring Boot Starter POMs.
Spring Boot Starter POMs simplify dependency management. Instead of adding multiple individual dependencies, we can include a single starter like spring-boot-starter-web
, and it automatically brings in everything required to build a web application. This helps avoid version conflicts and speeds up project setup.
Starter are added in the project’s build configuration (like pom.xml
) to automatically manage the dependencies required for specific functionalities.
Starter POM | Purpose |
---|---|
spring-boot-starter-web | Adds dependencies for building web apps (Spring MVC, Tomcat, Jackson) |
spring-boot-starter-data-jpa | Adds JPA, Hibernate, and Spring Data support |
spring-boot-starter-security | Adds Spring Security for authentication and authorization |
spring-boot-starter-test | Adds JUnit, Mockito, and Spring Test for testing support |
spring-boot-starter-thymeleaf | Adds Thymeleaf template engine for web views |
31. What is the purpose of the @ComponentScan annotation?
The @ComponentScan
annotation is used to enable automatic detection and registration of beans in a Spring application. It tells Spring where to look for classes annotated with stereotypes like @Component
, @Service
, @Repository
, and @Controller
.
How It Works:
This eliminates the need for manual bean registration and supports rapid development. When placed on a configuration class (commonly the main class annotated with @SpringBootApplication
), it instructs Spring to scan the specified package and its sub-packages for eligible components.
Customization and Flexibility
- Custom Scanning: Developers can customize the base package to scan by specifying the
basePackages
orbasePackageClasses
attribute of the@ComponentScan
annotation. This is particularly useful when your components are located in packages outside of the main application package.
@ComponentScan(basePackages = "com.example.services")
- Filtering:
@ComponentScan
allows for the inclusion or exclusion of components through filters usingincludeFilters
andexcludeFilters
attributes. This provides finer control over which components are registered.
@ComponentScan(
basePackages = "com.example",
excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Controller.class)
)
32. Explain the Concept of Dependency Injection in Spring Boot.
Dependency Injection (DI) is is one of the core features of the Spring Framework. It allows Spring Boot to manage the dependencies of your application classes automatically. This is part of the Inversion of Control (IoC) principle, where the control of creating and managing objects is handed over to the Spring container, rather than done manually. It’s a technique to achieve loose coupling between classes and their dependencies, making an application more modular, easier to test, and maintain.
Types of Dependency Injection in Spring Boot
Constructor Injection
Dependencies are provided through a class constructor.
@Component
public class MyService {
private final MyRepository myRepository;
@Autowired
public MyService(MyRepository myRepository) {
this.myRepository = myRepository;
}
}
Setter Injection
Dependencies are provided through setter methods.
@Component
public class MyService {
private MyRepository myRepository;
@Autowired
public void setMyRepository(MyRepository myRepository) {
this.myRepository = myRepository;
}
}
Field Injection
Dependencies are injected directly into the class fields.
@Component
public class MyService {
@Autowired
private MyRepository myRepository;
}
Practical Example
Consider a service class in a Spring Boot application that requires a repository class to access the database. Instead of instantiating the repository class inside the service class, Spring Boot can inject this dependency through the constructor or a setter method annotated with @Autowired
. This approach decouples the service class from the specific implementation of the repository, making the service class easier to test and maintain.
Spring Annotations That Support DI
Annotation | Role |
---|---|
@Component | Declares a class as a Spring-managed bean |
@Autowired | Requests Spring to inject a dependency |
@Qualifier | Used to resolve conflicts when multiple beans are available |
33. What is tight coupling? How does dependency injection help eliminate it in Spring?
Tight coupling
Tight coupling happens when classes are hardwired together, meaning one class directly creates or manages the lifecycle of another.
Example of Tight Coupling:
public class Car {
private Engine engine = new Engine(); // Direct instantiation
}
In this case, Car
is tightly coupled to Engine
. If we want to change the engine type or replace Engine
with a mock in testing, we have to modify the Car class itself.
Problems with Tight Coupling:
- ❌ Difficult to test (can’t inject mock objects easily)
- ❌ Hard to extend or change components
- ❌ Increases code dependencies and reduces flexibility
How Dependency Injection Fixes This?
Dependency Injection (DI) allows us to inject the dependencies from outside the class, removing the need to instantiate them manually.
🔧 Loose Coupling via Spring DI:
@Component
public class Car {
private final Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
}
Now Car
doesn’t care about how Engine
is created. Spring handles that. This promotes loose coupling, making it:
- ✅ Easy to swap
Engine
with a new implementation - ✅ More testable (you can inject mock objects in unit tests)
- ✅ Easier to maintain and scale
34. What is the Difference between @Autowired and @Inject annotations?
Feature | @Autowired | @Inject |
---|---|---|
Source | Spring Framework | Java standard (JSR-330) |
Flexibility | More flexible with additional options like required=false | Simpler, without extra configuration options |
Usage | Predominantly used in Spring projects for seamless integration with Spring features | Can be used in any Java project, promoting portability and adherence to standard |
Options | Allows specifying whether a dependency is required or not | Provides straightforward dependency injection without additional options |
Compatibility | Specific to Spring, not natively supported outside Spring context | Supports use in various Java environments, encouraging use in diverse projects |
This table summarizes the main differences, making it clear that @Autowired
offers Spring-specific enhancements and flexibility, while @Inject
adheres to Java standards and promotes broader compatibility.
35. How do you handle form submissions in Spring Boot?
Handling form submissions in Spring Boot involves creating a controller to process the form data, defining a model to bind form data, and setting up a view template to display the form.
Here’s a step-by-step guide:
1. Define a Model Class
First, define a model class that corresponds to the data you expect from the form. Spring uses this class to bind form data to objects.
public class User {
private String name;
private String email;
// No-argument constructor
public User() {
}
// Parameterized constructor
public User(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
2. Create a Controller
Create a controller with methods to show the form and to handle the form submission. Use @GetMapping
to display the form and @PostMapping
to process the form submission.
@Controller
public class UserController {
@GetMapping("/register")
public String showForm(Model model) {
model.addAttribute("user", new User());
return "register_form"; // Thymeleaf template
}
@PostMapping("/register")
public String submitForm(@ModelAttribute("user") User user) {
System.out.println(user);
return "register_success"; // Success template
}
}
3. Create the Form in a View Template
Assuming you’re using Thymeleaf as your template engine, create an HTML form in the register_form.html
file. Use Thymeleaf syntax to bind form fields to the model attributes.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Register</title>
</head>
<body>
<form action="#" th:action="@{/register}" th:object="${user}" method="post">
<label for="name">Name:</label>
<input type="text" id="name" th:field="*{name}" />
<label for="email">Email:</label>
<input type="email" id="email" th:field="*{email}" />
<button type="submit">Submit</button>
</form>
</body>
</html>
4. Process the Form Submission
In the submitForm
method of your controller, you can process the form submission. Here, you might save the data to a database, send an email, or perform other business logic.
5. Create a Success Page
After the form is submitted, users can be redirected to a success page. Create a simple register_success.html
to inform the user of the successful submission.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Registration Successful</title>
</head>
<body>
<h1>Registration Successful!</h1>
<p>Thank you for registering with us.</p>
</body>
</html>
36. Explain the concept of Profiles in Spring Boot.
In Spring Boot, profiles are a way to group different configuration settings for various environments (e.g., development, testing, production). They allow you to define environment-specific properties and beans that will be activated only when a specific profile is selected.
Key Concepts:
1). Profile-Specific Configuration Files
You can define separate configuration files for different profiles using the naming convention application-{profile}.properties
or application-{profile}.yml
. For example:
application-dev.properties
: for the development environment.application-prod.yml
: for the production environment.
Spring Boot will load the appropriate configuration file based on the active profile.
2). Activating Profiles
Profiles can be activated in multiple ways:
In application.properties
spring.profiles.active=dev
Via command-line argument:
java -jar myapp.jar --spring.profiles.active=prod
Using environment variables:
export SPRING_PROFILES_ACTIVE=prod
3). @Profile Annotation
You can also define beans or components that are specific to a certain profile using the @Profile
annotation. These beans will only be loaded when the corresponding profile is active.
@Service
@Profile("dev")
public class DevDatabaseService implements DatabaseService {
// Dev-specific implementation
}
@Service
@Profile("prod")
public class ProdDatabaseService implements DatabaseService {
// Prod-specific implementation
}
How Profiles Can Be Used?
Testing: Profiles can be used to configure different settings for integration or unit testing without affecting production configurations.
Environment-Specific Configurations: Use profiles to separate configurations like database URLs, API keys, logging levels, etc., for development, testing, and production.
Conditional Bean Loading: You can conditionally load beans depending on the active profile, ensuring that only the relevant components for the current environment are initialized.
37. How can you Implement Caching in a Spring Boot Application?
Implementing caching in a Spring Boot application is like giving your application a memory boost. It helps your application to remember things it has already done, so it doesn’t have to do them again. This can make your application faster, especially if it often does the same tasks.
Steps to implement Caching
Step1: Add Caching Dependencies
First, add Spring Boot’s caching starter to your pom.xml
or build.gradle
file. This step is like getting the tools you need.
If you’re using Maven, add this to your pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
For Gradle, add this line to your build.gradle
:
implementation 'org.springframework.boot:spring-boot-starter-cache'
Step 2: Enable Caching
Next, turn on caching in your application. It’s like flipping a switch to activate caching. Add @EnableCaching
annotation to one of your configuration classes, usually the main application class.
@SpringBootApplication
@EnableCaching
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Step 3: Use Cache Annotations
Now, decide what data you want to cache. Use annotations to tell Spring Boot what to remember and when.
- @Cacheable: Use this on methods to cache their results. The first time the method is called, its result is stored in cache. Later calls with the same arguments return the cached result.
- @CachePut: Updates the cache with the result of the method it annotates every time the method is called.
- @CacheEvict: Removes data from the cache. Useful for deleting outdated or unused data.
Step 4: Configure the Cache
Configure cache properties in your application.properties
or application.yml
. This step is like setting up rules for how the cache should work.
For example, to specify the cache names and other settings, add to your application.properties
:
spring.cache.cache-names=books, authors
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s
38. What is the purpose of the @Scheduled annotation?
The <strong>@Scheduled</strong>
annotation in Spring Framework is used to define methods that should be executed at regular intervals or at specific times. It enables developers to easily schedule tasks without the need for manual timers or schedulers.
It Supports various ways to specify when the task should run, including fixed-rate, fixed-delay, and cron expressions, offering flexibility to address different scheduling needs.
- Fixed-rate scheduling runs the specified task at a fixed interval every time the previous task completes.
- Fixed-delay scheduling runs the task with a fixed delay between the completion of the last invocation and the start of the next.
- Cron expression scheduling allows for more complex scheduling patterns, such as “every day at 6 pm”, or “every weekday at 8 am”.
To use <strong>@Scheduled</strong>
, you need to enable scheduling in your Spring application, typically done with the @EnableScheduling
annotation on one of your configuration classes. This tells Spring to look for @Scheduled
annotations and process them accordingly.
Example of @Scheduled
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTasks {
@Scheduled(fixedRate = 3000)
public void reportCurrentTime() {
System.out.println("Current time: " + System.currentTimeMillis());
}
}
39. Explain the role of Spring Boot Starters in the Development Process.
Spring Boot Starters streamline the development process by pre-packaging sets of dependencies and auto-configuration logic needed for specific types of projects.
Some key points
- Simplify Dependency Management: Starters bundle related dependencies together, so developers only need to include a single starter dependency for a specific functionality, such as web applications, data access, or security, instead of manually managing multiple related libraries.
- Ensure Compatibility: They manage version compatibility of included libraries, reducing the risk of version conflicts and saving developers the hassle of version management.
- Accelerate Project Setup: By providing a ready-to-use configuration, starters allow developers to quickly bootstrap new projects with less boilerplate code and configuration, enabling a focus on business logic from the get-go.
- Promote Best Practices: Spring Boot starters are designed based on the best practices and recommendations for using the Spring framework, helping developers adhere to industry standards.
40. What is the purpose of the @EnableAutoConfiguration annotation?
The @EnableAutoConfiguration
annotation in Spring Boot is designed to simplify the configuration process of your application. It automatically configures your Spring application based on the dependencies present on the classpath.
@EnableAutoConfiguration
tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. For instance, if Spring MVC is on the classpath, Spring Boot automatically sets up a web application context and configures a dispatcher servlet.
Typically, we won’t use @EnableAutoConfiguration
directly; instead, we’ll use the @SpringBootApplication
annotation, which is a convenience annotation that includes @EnableAutoConfiguration
, @ComponentScan
, and @Configuration
.
41. How do you ensure or define that your Spring Boot application is scalable?
To ensure my Spring Boot application is scalable, I focus on designing it with loose coupling, statelessness, and horizontal scalability in mind. I use best practices like:
- Building with microservices architecture
- Leveraging Spring Cloud components (like Eureka, Gateway, Config Server)
- Stateless REST APIs to allow multiple instances
- Externalizing configurations for environment flexibility
- Using load balancers and containerization (e.g., Docker + Kubernetes)
- Monitoring with Spring Actuator + Prometheus + Grafana
- Caching (using Redis, Caffeine) to reduce load on services
- Asynchronous processing with queues (RabbitMQ/Kafka)
These collectively ensure the app can scale horizontally and handle increasing load efficiently.
42. How do you enable cross-origin requests (CORS) in a Spring Boot application?
Enabling cross-origin requests in a Spring Boot application is essential for allowing web applications hosted on different domains to interact with your server. This can be achieved using Spring Security and the @CrossOrigin
annotation or by global configuration.
Using @CrossOrigin Annotation
1. Method-Level Cross-Origin Configuration:
You can annotate individual controller methods with @CrossOrigin
to enable cross-origin requests specifically for those endpoints.
@RestController
public class TestController {
@CrossOrigin(origins = "http://localhost:3000") // allow React app origin
@GetMapping("/example")
public String example() {
return "Cross-Origin Requests Allowed";
}
}
2. Controller-Level Cross-Origin Configuration:
Placing the @CrossOrigin
annotation at the class level enables CORS for all handler methods within that controller.
@CrossOrigin(origins = "*") // allow all origins
@RestController
public class TestController {
@GetMapping("/test")
public String test() {
return "This endpoint allows CORS";
}
}
43. Can you explain what CQRS is and how it’s implemented in a Spring Boot application?
CQRS (Command Query Responsibility Segregation) is a design pattern where the read operations (queries) and write operations (commands) are handled by separate models. This allows better scalability, maintainability, and optimization of both reads and writes.
CQRS(Command Query Responsibility Segregation)
- Command = Any operation that changes state (like
create
,update
,delete
) - Query = Any operation that reads data (like
getById
,getAll
,filterByDate
)
CQRS separates these concerns into independent code paths, making your application easier to scale, understand, and maintain.
In a Spring Boot application, CQRS can be implemented by
- Separating the command (write) and query (read) responsibilities into different service classes.
- Using different data models or DTOs for commands and queries.
- Optionally combining it with Event Sourcing or messaging systems like Kafka to handle complex workflows or microservices communication.
44. Explain the @Transactional
annotation in Spring Boot. Where you have used in your project.
The @Transactional
annotation in Spring Boot is used to manage database transactions. It ensures that a series of database operations are executed within a transaction, meaning they either all succeed or are all rolled back in case of failure. This helps maintain data consistency and integrity.
Key Purposes:
Declarative Transactions: By simply using @Transactional
, Spring manages the transaction lifecycle without requiring explicit transaction management code.
Transaction Management: It wraps a method or class in a database transaction, ensuring that all operations within the transaction are either fully completed or none are, in case of an error.
Automatic Rollback: If any exception occurs during the execution of the annotated method, the transaction is automatically rolled back, preventing partial changes to the database.
Where I Used @Transactional
in My Project:
In my recent project in the healthcare domain, I used
@Transactional
in the appointment booking module.
When a patient books an appointment, we:
- Save the appointment.
- Update the doctor’s availability.
- Send a notification record to the queue.
@Transactional public void bookAppointment(AppointmentRequest request) { appointmentRepository.save(request.toEntity()); doctorAvailabilityService.updateSlot(request.getDoctorId(), request.getTime()); notificationService.scheduleEmailNotification(request.getEmail()); }
45. How can you implement security in a Spring Boot application?
In Spring Boot 3.x, I implement security using Spring Security 6 by defining a SecurityFilterChain
bean, which replaces the older WebSecurityConfigurerAdapter
. I secure endpoints based on roles, disable CSRF for stateless APIs, and use method-level annotations like @PreAuthorize
for fine-grained access control. For authentication, I can use in-memory users or integrate with a database and secure passwords using BCryptPasswordEncoder
.
Step-by-Step Implementation:
1. Add Dependency:
In Pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2. Create a Security Configuration Class:
@Configuration
@EnableMethodSecurity // Enables @PreAuthorize, @Secured, etc.
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withUsername("admin")
.password(passwordEncoder().encode("password"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Key Features in Spring Security 6 / Spring Boot 3:
- Functional Security Configuration using
SecurityFilterChain
bean - No need to extend
WebSecurityConfigurerAdapter
(which is now deprecated) - Use of
@EnableMethodSecurity
for method-level protection - Modern Password Encoding using
BCryptPasswordEncoder
Securing Endpoints
@RestController
@RequestMapping("/api")
public class DemoController {
@GetMapping("/public/hello")
public String publicHello() {
return "This is a public endpoint.";
}
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin/hello")
public String adminHello() {
return "This is a protected admin endpoint.";
}
}
46. Explain the role of the Spring Boot DevTools and how they enhance the development process.
Spring Boot DevTools is a set of tools designed to make the development process with Spring Boot faster and more efficient. DevTools monitors changes in your project files. When you save a change to any class or resource, it automatically restarts your application. This restart is faster than a cold start because DevTools uses two classloaders to keep the base application context cached.
Enabling Spring Boot DevTools
For Maven:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
</dependencies>
47. What is the purpose of the @RequestMapping annotation?
@RequestMapping
is used to map HTTP requests to specific handler methods in a Spring controller. It can be used to define the URL path, HTTP method, and other request details. It helps in routing incoming web requests to the appropriate methods in a RESTful application.
Purpose of the @RequestMapping
- Used to define the URL pattern, HTTP method, headers, params, or produces/consumes types a method can handle.
- Can be applied at class level and/or method level.
Example
@RestController
@RequestMapping("/api/users") // Base URL for all methods in the class
public class UserController {
@RequestMapping(method = RequestMethod.GET)
public List<User> getUsers() {
return userService.getAllUsers();
}
@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public User getUserById(@PathVariable Long id) {
return userService.getUser(id);
}
}
48. How do you enable HTTP response compression in a Spring Boot application?
Spring Boot provides built-in support for HTTP response compression to reduce the size of responses and improve performance, especially for large JSON, text, or HTML payloads.
To enable HTTP response compression in Spring Boot, just set a few properties like server.compression.enabled=true
in application.properties
. It reduces response payload size and improves performance for clients by compressing supported MIME types like JSON or HTML when the response exceeds a defined size.
Steps to Enable Compression:
Simply configure the following properties in application.properties
or application.yml
:
Using application.properties
:
server.compression.enabled=true
server.compression.mime-types=application/json,application/xml,text/html,text/plain
server.compression.min-response-size=1024
Using application.yml
server:
compression:
enabled: true
mime-types: application/json,application/xml,text/html,text/plain
min-response-size: 1024
49. Explain the concept of internationalization(i18n) in Spring Boot.
Internationalization (i18n) in Spring Boot refers to the process of designing and developing applications that can be easily adapted to different languages and locales.
In Spring Boot, internationalization is typically implemented using message sources. A message source is a repository of messages, where each message corresponds to a text string in the application. These messages are stored in external properties files, one for each supported locale.
Example:
Suppose you have a message properties file named messages_en.properties
with the following content:
message.language=Hello, {0}! This is english language.
In your Spring Boot application code, you can retrieve and interpolate this message as follows:
@Autowired
private MessageSource messageSource;
public String getMessage(String name, Locale locale) {
return messageSource.getMessage("message.language", new Object[]{name}, locale);
}
50. Difference between Spring Boot Data REST and Spring Boot REST.
Aspect | Spring Boot REST | Spring Boot Data REST |
---|---|---|
Definition | Manual creation of REST APIs using @RestController and HTTP methods (@GetMapping , etc.) | Automatically exposes JPA repositories as RESTful endpoints |
Control | Full control over URL structure, request/response format, business logic, etc. | Limited control – follows conventions and auto-generates endpoints based on entities and repositories |
Customization | Highly customizable | Customization is possible but requires more effort (event handlers, projections, etc.) |
Use Case | Suitable for complex business logic, custom endpoints, or fine-grained control | Suitable for rapid prototyping, admin tools, or simple CRUD APIs |
Annotations Used | @RestController , @RequestMapping , @Service , etc. | @RepositoryRestResource , @RestResource , etc. |
Dependency Required | No extra dependency, part of Spring Boot Starter Web | Requires spring-boot-starter-data-rest dependency |
Example URL | /api/users/1 (manually coded) | /users/1 (auto-generated by Spring Data REST) |
51. What is Spring Boot Data REST, and how does it simplify RESTful API development?
Spring Boot Data REST is a powerful feature of the Spring Boot framework that simplifies the development of RESTful APIs for interacting with your data model. It allows you to expose your Spring Data repositories as RESTful endpoints with minimal configuration, enabling CRUD (Create, Read, Update, Delete) operations on your domain entities over HTTP.
How Spring Boot Data REST Works?
When you create a repository interface (like JpaRepository
) and annotate it with @RepositoryRestResource
, Spring Boot Data REST auto-generates REST endpoints for that entity.
Example of Spring Boot Data REST
Entity Class
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
private String email;
}
Repository Interface
@RepositoryRestResource
public interface UserRepository extends JpaRepository<User, Long> {
}
This automatically exposes:
GET /users
GET /users/{id}
POST /users
PUT /users/{id}
DELETE /users/{id}
52. Explain the use of the @Repository annotation in Spring Boot.
@Repository
is used to define a class as part of the persistence layer. It allows Spring to scan and register it as a bean, apply exception translation, and integrate it with Spring Data access technologies like JPA or JDBC. It’s key for separating business logic from database logic. It is a specialized stereotype annotation in Spring used to indicate that the class provides database access operations (typically DAO or repository layer).
Purpose:
- Marks a class as a Spring-managed bean that handles data access logic.
- Enables automatic exception translation — Spring converts database-related exceptions (like
SQLException
) into Spring’s unifiedDataAccessException
. - Helps in applying Aspect-Oriented Programming (AOP) such as transaction management.
53. How can you enable Swagger (OpenAPI Specification) documentation for your RESTful APIs in a Spring Boot application?
Swagger (now known as OpenAPI) is a powerful tool that helps generate interactive API documentation and provides an easy way to test RESTful endpoints directly from a web interface.
It helps in Spring Boot by automatically generating API documentation and providing a web-based UI to test endpoints interactively. It improves developer experience, speeds up testing, and simplifies collaboration by showing available routes, parameters, and responses clearly. It also supports security configurations like JWT for testing protected APIs
To enable Swagger documentation in a Spring Boot application, you can use the Swagger UI and Swagger annotations to generate interactive API documentation.
To Use it, Add Dependency (using springdoc-openapi for latest support)
For Maven:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version> <!-- Use latest version -->
</dependency>
For Gradle:
dependencies {
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0'
}
Access Swagger UI
After starting the app, go to:
👉 http://localhost:8080/swagger-ui.html
or
👉 http://localhost:8080/swagger-ui/index.html
54. How Swagger helps with API documentation and testing in Spring Boot?
Swagger, now known as OpenAPI, is a powerful tool used in Spring Boot to generate interactive API documentation and provide an easy way to test REST endpoints.
Key Benefits of OpenAPI:
Acts as live, up-to-date documentation for external or internal consumers.
Automatic API Documentation:
- Swagger scans Spring Boot controllers and automatically generates documentation for all exposed REST endpoints.
- It lists all endpoints, request types, parameters, response formats, and status codes.
Interactive API Testing:
- Swagger UI provides a web interface where developers and testers can directly test APIs without using external tools like Postman or Curl.
Developer-Friendly Interface:
- Clear visual structure for APIs.
- Shows which parameters are required, their types, and descriptions.
Supports Security Integration:
- Can be configured to work with JWT, OAuth2, Basic Auth, etc., allowing secure API testing.
Enhances Collaboration:
- Makes it easier for frontend and backend teams to understand available APIs.
- Acts as live, up-to-date documentation for external or internal consumers.
55. Explain the purpose of the @Value annotation in Spring Boot.
The @Value
annotation in Spring Boot is used to inject external values from property files (application.properties
or application.yml
), environment variables, or system properties directly into Spring-managed components (e.g., services, controllers, or beans).
It helps achieve externalized configuration, which means avoiding hardcoding values in code promoting maintainability, flexibility, and easier environment-specific setups.
Spring Boot encourages externalizing configuration to separate files (e.g., application.properties
or application.yml
) instead of embedding it directly into the code. The @Value
annotation facilitates the injection of these externalized configuration values into Spring components.
Example:
@Value("${app.name}")
private String appName;
If application.properties
has:
app.name=InterviewExpert
Then appName
will be injected with the value "InterviewExpert"
at runtime.
In this example, the value of ${app.name}
is injected into the appName
field from the application.properties
or application.yml
file.
Where You Can Use @Value
:
- Class Fields
- Constructor Parameters
- Method Parameters
56. What is the purpose of the @ConfigurationProperties annotation?
The @ConfigurationProperties
annotation in Spring Boot is used to bind external configuration properties directly to Java objects. It provides a convenient way to map properties from configuration files (e.g., application.properties
or application.yml
) to fields of a POJO (Plain Old Java Object), allowing for type-safe and structured access to configuration values.
Example
1). Define Configuration POJO:
@Component
@ConfigurationProperties(prefix = "app")
public class AppConfig {
private String name;
private int age;
}
2). Bind Configuration Properties:
# application.yml
app:
name: "MyApp"
age: 1
3). Access Configuration Properties:
@Autowired
private AppConfig appConfig;
public void getValues() {
String appName = appConfig.getName();
int appAge = appConfig.getAge();
}
57. How can you perform unit testing in Spring Boot application using frameworks like JUnit and Mockito?
In a Spring Boot application, JUnit is commonly used for writing and executing unit tests, while Mockito is used for mocking dependencies. Unit testing aims to test individual classes or methods in isolation, without loading the full Spring application context. This results in faster and more reliable test execution.
Test classes are typically annotated with @ExtendWith(MockitoExtension.class)
to enable Mockito features such as @Mock
for creating mock objects and @InjectMocks
for injecting those mocks into the class under test. This setup allows the business logic to be tested independently of its dependencies.
Assertions provided by JUnit 5 or AssertJ are used to verify expected outcomes. In service-layer tests, for example, repositories are mocked and injected into service classes to ensure that the service logic behaves correctly without interacting with the actual database.
58. Explain the concept of application.properties in Spring Boot.
The application.properties
file in Spring Boot plays a crucial role in externalizing configuration from the application code. It allows developers to define various settings and preferences for a Spring Boot application in a simple, key-value format. This approach enables easy management of application behavior without changing the code, making your application adaptable to different environments.
Spring Boot allows for defining environment-specific properties (e.g., application-dev.properties
for development, application-prod.properties
for production) that override the default configurations in application.properties
when the corresponding profile is active.
Example
# Server configuration
server.port=8080
# Database configuration
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=dbusername
spring.datasource.password=dbpassword
59. What is the purpose of the Spring Boot Actuator health check?
The Spring Boot Actuator health check is a critical feature for monitoring and managing the health of a Spring Boot application. It provides a simple, yet comprehensive way to check the status of your application and its connected services.
Example
Accessing the health information typically involves making a GET request to the /actuator/health
endpoint. The response includes the overall health status and details of each health indicator:
{
"status": "UP",
"components": {
"db": {
"status": "UP",
"details": {
"database": "MySQL",
"validationQuery": "isValid()"
}
},
"diskSpace": {
"status": "UP",
"details": {
"total": 500000000,
"free": 250000000,
"threshold": 10000000
}
},
// Other health indicators...
}
}
60. How do you implement request logging and auditing in a Spring Boot application?
In a Spring Boot application, request logging and auditing can be implemented using a combination of Spring filters, interceptors, and aspects. A common approach involves creating a custom filter or interceptor to log incoming HTTP requests, including method, URI, headers, and body.
For auditing purposes, Spring Data JPA provides built-in annotations like @CreatedDate
, @CreatedBy
, @LastModifiedDate
, and @LastModifiedBy
using the AuditingEntityListener. Custom auditing (e.g., user activity logs) can be handled with AOP (Aspect-Oriented Programming) or in the service layer.
61. Explain the concept of parent POMs.
Parent POM:
The Spring Boot parent POM (Project Object Model) is a special Maven project that provides dependency management and default configurations for your Spring Boot applications. By inheriting from the Spring Boot parent POM, your project can leverage the pre-defined setup provided by Spring Boot, including plugin configurations, resource filtering settings, and more. This promotes consistency, reusability, and maintainability across multiple Maven projects.
In Spring Boot, the most commonly used parent POM is:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
</parent>
By declaring this, your project inherits the default configurations provided by Spring Boot.
Benefits of Using Spring Boot’s Parent POM
Feature | Description |
---|---|
✅ Dependency Management | No need to specify versions for Spring Boot starters and many common libs. |
✅ Plugin Configuration | Pre-configured Maven plugins (e.g., spring-boot-maven-plugin ). |
✅ Default Build Settings | Resource filtering, encoding, compiler settings, etc. |
✅ Version Consistency | Centralized management of versions reduces conflicts. |
✅ Override Flexibility | You can still override any inherited configuration locally in your POM. |
62. What is the purpose of the @EnableCaching annotation?
The @EnableCaching
annotation in Spring Framework is used to enable caching capabilities within a Spring application. It’s a declarative way to add cache support, optimizing performance by reducing the need to repeatedly compute or fetch data that has been previously retrieved.
You can use annotations like @Cacheable
, @CachePut
, and @CacheEvict
on methods to control how their results are cached.
@Cacheable
can be used to cache the method’s response.@CachePut
updates the cache with the method’s result.@CacheEvict
removes entries from the cache, either before or after the method execution.
63. Explain the use of the @Qualifier annotation in Spring Boot.
The @Qualifier
annotation in Spring Boot is used to resolve ambiguities when more than one bean of the same type is available in the Spring container. It helps specify which bean should be injected into a class when there are multiple candidates.
Purpose of @Qualifier:
- Disambiguation: When multiple beans of the same type exist,
@Qualifier
helps to distinguish between them, allowing developers to specify which bean should be autowired. - Fine-grained Control: It provides more control over dependency injection, ensuring that the correct bean is wired where it’s needed.
Example of @Qualifier:
Suppose you have two beans of the same type that are configured in your Spring application context.
@Configuration
public class AppConfig {
@Bean
public Vehicle car() {
return new Car();
}
@Bean
public Vehicle auto() {
return new Auto();
}
}
Inject with @Qualifier:
When injecting a bean of type Vehicle
, use the @Qualifier
annotation to specify which bean should be injected.
@Component
public class VehicleService {
private Vehicle vehicle;
@Autowired
public VehicleService(@Qualifier("car") Vehicle vehicle) {
this.vehicle = vehicle;
}
}
In this example, the VehicleService
class requires a Vehicle
bean. The @Qualifier
annotation with the value "car"
indicates that the car bean should be injected, resolving the ambiguity between car and auto
.
64. How can you handle asynchronous tasks in a Spring Boot application?
Handling asynchronous tasks in a Spring Boot application allows for non-blocking operations, where tasks can run in the background without holding up the main execution flow. This is particularly useful for operations that are time-consuming, such as sending emails, processing files, or making network calls.
Spring Boot simplifies async execution using:
- A configured
TaskExecutor
(thread pool) - The
@Async
annotation
Best Practices
@Async
only works on public methods and must be called from a different Spring-managed bean, not self-invoked.- Use
CompletableFuture
to track the result or handle exceptions. - For error handling, add
@AsyncExceptionHandler
or useCompletableFuture.exceptionally()
.
65. How can you implement asynchronous processing in a Spring Boot application?
In Spring Boot 3.x, asynchronous processing allows certain tasks to run in a non-blocking background thread, freeing up the main thread for better performance and responsiveness. It is particularly useful for long-running or IO-heavy operations like sending emails, making HTTP calls, or processing large files.
Spring Boot provides first-class support for asynchronous execution using:
@Async
annotation- A
TaskExecutor
bean (for thread pool management) @EnableAsync
annotation to activate async support
Steps to Implement Asynchronous Processing (Spring Boot 3.x+)
1. Enable Async Support
@Configuration
@EnableAsync
public class AsyncConfig {
}
This annotation enables Spring’s asynchronous method execution capability.
2. Define a Custom Thread Pool Executor (Optional but Recommended)
@Bean(name = "taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("Async-");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.initialize();
return executor;
}
This executor gives you better control over thread behavior (especially in production).
3. Create an Async Method Using @Async
@Service
public class NotificationService {
@Async("taskExecutor") // Optional if only one executor is defined
public void sendNotification(String email) {
try {
Thread.sleep(3000); // Simulate delay
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Email sent to: " + email);
}
}
4. Call the Async Method
@RestController
@RequestMapping("/api")
public class NotificationController {
private final NotificationService notificationService;
public NotificationController(NotificationService notificationService) {
this.notificationService = notificationService;
}
@GetMapping("/notify")
public String notifyUser() {
notificationService.sendNotification("[email protected]");
return "Notification triggered asynchronously";
}
}
Additional Notes (as per Spring Boot 3.x)
- Async methods must be
public
and called from outside their own bean (not self-invoked). - Async methods can return
void
,CompletableFuture<T>
,Future<T>
, orListenableFuture<T>
. - Exceptions in
@Async
methods should be handled usingCompletableFuture.exceptionally(...)
or by configuringAsyncUncaughtExceptionHandler
.
66. Explain the purpose of the @RestControllerAdvice annotation.
The @RestControllerAdvice
annotation in Spring Boot is used to handle exceptions across the whole application in a global, catch-all type of way. Specifically designed for REST APIs (i.e., with @RestController
). It’s a specialization of @ControllerAdvice
annotation that combines it with @ResponseBody
to offer a convenient approach to exception handling with RESTful APIs.
Centralized Exception Handling:
- Global Scope: It allows developers to define a global exception handling mechanism that applies to all controllers, making the code cleaner and more maintainable by avoiding repetitive local exception handlers.
- Automatic Response Body Conversion: Since it’s tailored for RESTful services,
@RestControllerAdvice
ensures that exceptions are automatically converted to JSON or XML responses, adhering to the REST API’s response format.
Example
Annotate a class with @RestControllerAdvice
to designate it as a global exception handler.
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<Object> handleResourceNotFoundException(ResourceNotFoundException ex) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), "Resource not found");
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
}
67. Difference between ControllerAdvice and RestControllerAdvice.
Feature | @ControllerAdvice | @RestControllerAdvice |
---|---|---|
Designed for | MVC Controllers | REST Controllers |
Automatically adds @ResponseBody | ❌ No | ✅ Yes |
Typical response format | View (HTML) or manually JSON | JSON/XML (RESTful response) |
Return value | View name / ModelAndView | Java object serialized to JSON/XML |
Used with | @Controller | @RestController |
When to Use What?
- Use
@ControllerAdvice
when you’re building a traditional web app with views (like JSP, Thymeleaf). - Use
@RestControllerAdvice
when you’re building a RESTful API and want to return JSON/XML consistently.
68. Explain the purpose of the @PathVariable annotation in Spring Boot.
The @PathVariable
annotation in Spring Boot is used within Spring MVC or Spring WebFlux to bind a method parameter to a URI template variable. It’s a key feature for building RESTful web services, allowing dynamic values to be passed through URLs.
@PathVariable
extracts values from the URI path itself. This is particularly useful for REST APIs where resource identifiers are part of the URL path.
Example
When defining request mappings in a controller, you can specify parts of the URL path as variables using curly braces {}
. The @PathVariable
annotation is then used to map these variables to method parameters.
@GetMapping("/users/{userId}")
public ResponseEntity<User> getUserById(@PathVariable Long userId) {
User user = userService.findById(userId);
return ResponseEntity.ok(user);
}
In this example, {userId}
in the URL path is mapped to the userId
method parameter, making the actual value of userId
in the request URL accessible within the method.
69. What is the purpose of the @Entity annotation in Spring Boot?
The @Entity
annotation in Spring Boot, originating from the Java Persistence API (JPA), is used to indicate that a class is an entity in the domain model. An entity represents a table stored in a database, and each instance of the entity corresponds to a row in the table. The primary purpose of the @Entity
annotation is to define the class as a JPA entity so that it can be mapped to a database table.
Example:
To use the @Entity
annotation, simply annotate the class with @Entity
and specify a primary key with @Id
:
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class User {
@Id
private Long id;
private String name;
// Getters and setters
}
In this example, the User
class is mapped to a User
table in the database, with id
, and <code>nam
e columns corresponding to the class’s fields.
70. How can you configure a connection pool in Spring Boot?
A connection pool is a cache of database connections maintained so that connections can be reused when future requests to the database are required. This improves performance and resource usage.
Step-by-Step: Configuring a Connection Pool in Spring Boot (HikariCP)
Add Database Dependencies
For example, for MySQL:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
Spring Boot Auto-Configuration
# DataSource Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
# HikariCP Settings (Connection Pool)
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.connection-timeout=20000
spring.datasource.hikari.pool-name=MyHikariCP
Using application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: secret
hikari:
maximum-pool-size: 10
minimum-idle: 5
idle-timeout: 30000
max-lifetime: 1800000
connection-timeout: 20000
pool-name: MyHikariCP
71. Explain the purpose of the @Async annotation in Spring Boot and how it enables asynchronous processing.
The @Async
annotation in Spring Boot is used to indicate that a method should be executed asynchronously, meaning it will run in a separate thread, allowing the caller thread to continue execution without waiting for the method to complete. This is particularly useful for improving application performance by offloading long-running or non-blocking tasks to the background.
When to Use:
- Sending emails or SMS
- Calling external REST APIs
- Processing files or images
- Long-running database operations
- Background data synchronization or cleanup tasks
72. What is the purpose of the Spring Boot Actuator info endpoint?
The info
endpoint provided by Spring Boot Actuator is used to expose custom application information such as:
- Application version
- Build information
- Custom metadata (like developer contact, company, or environment-specific settings)
This endpoint is helpful for:
- Displaying useful info for monitoring tools
- Providing metadata for operations/support teams
- Including details during health checks or CI/CD dashboard
73. How can you implement rate limiting and throttling in a Spring Boot application?
74. Explain the concept of Spring Boot Actuator tracing.
Spring Boot Actuator Tracing refers to the ability to track the flow of requests across your application, especially across microservices, using distributed tracing tools. It helps identify performance bottlenecks, latency, and trace failures across service boundaries.
75. What is the purpose of the @ResponseStatus annotation in Spring Boot?
The @ResponseStatus
annotation in Spring Boot is used to explicitly define the HTTP status code that should be returned from a controller method or an exception class. This helps in customizing the HTTP response without manually creating a ResponseEntity
.
@ResponseStatus can be applied to:
- Exception classes (to map exceptions to specific HTTP status codes)
- Controller methods (to define success responses)
Example of @ResponseStatus
You can annotate controller methods with @ResponseStatus
to indicate the HTTP status code that should be returned after the method execution.
@PostMapping("/items")
@ResponseStatus(HttpStatus.CREATED)
public Item addItem(@RequestBody Item item) {
return itemService.save(item);
}
When the addItem()
method successfully executes, the response will return HTTP 201 (Created) instead of the default 200 (OK).
76. How can you configure multiple data sources in a Spring Boot application?
Configuring multiple data sources in a Spring Boot application is common in scenarios where your app interacts with different databases or schemas. Spring Boot doesn’t auto-configure multiple data sources out of the box, so you need to define and configure each one manually.
Key Concepts:
1. Primary and Secondary Data Sources
- The primary data source is the main one used by default (annotated with
@Primary
). - The secondary (or more) data sources are additional databases you manually configure.
2. Separate Configuration for Each
Each data source requires:
- A separate
DataSource
bean - A
LocalContainerEntityManagerFactoryBean
for JPA - A
PlatformTransactionManager
- A package scan for entities and repositories
3. Property Binding
Each data source is configured using separate properties in application.properties
or application.yml
, such as:
spring.datasource...
secondary.datasource...
77. Can you explain JWT tokens in detail? What do they contain and how are they used in Spring Boot?
JWT is a compact, URL-safe token format used to securely transmit information between parties as a JSON object. It is digitally signed using either a secret (HMAC) or a public/private key pair (RSA or ECDSA).
Why Use JWT?
- Stateless authentication (no session storage needed)
- Easy to pass between services or in web/mobile apps
- Efficient for microservices and REST APIs
Structure of a JWT
A JWT token has three parts, separated by dots (.
):
<HEADER>.<PAYLOAD>.<SIGNATURE>
1. Header (base64 encoded)
Describes the token type and algorithm used.
{
"alg": "HS256",
"typ": "JWT"
}
2. Payload (base64 encoded)
Contains the claims — the information you want to share.
Example:
{
"sub": "user123",
"name": "John Doe",
"role": "ADMIN",
"iat": 1718943800,
"exp": 1718947400
}
3. Signature
Ensures the token has not been tampered with.
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
78. What is JWT Authentication? Explain its Token generation steps and flow.
JWT Authentication is a stateless authentication mechanism where a JSON Web Token (JWT) is used to verify the identity of a user. Instead of storing session data on the server, the server issues a signed token after verifying the user’s credentials. This token is sent with each subsequent request, allowing the server to authenticate the user without storing session information.
Token generation Flow Overview
[Login Request] → [Authenticate User] → [Generate JWT Token] → [Client Stores JWT]
Client Requests → [JWT in Authorization Header] → [Validate Token] → [Authorize Access]
79. What is the purpose of the Spring Boot Test framework, and how do you write integration tests with it?
The Spring Boot Test framework provides a set of testing tools and annotations designed to make it easy to write unit tests, integration tests, and end-to-end tests for Spring Boot applications.
To write integration tests in Spring Boot, use the @SpringBootTest
annotation to load the full application context. Combine it with @AutoConfigureMockMvc
to test your REST APIs using MockMvc
.
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
void shouldReturnUser() throws Exception {
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk());
}
}
This setup allows you to test controllers, services, and repositories together, just like in real application runs.
80. Explain the use of the @EnableScheduling annotation in Spring Boot.
The @EnableScheduling
annotation in Spring Boot is used to enable scheduled task execution. It tells Spring to look for methods annotated with @Scheduled
and run them based on a specified schedule (fixed rate, delay, or cron expression).
Example
@Configuration
@EnableScheduling
public class SchedulerConfig {
}
@Component
public class ReportScheduler {
@Scheduled(cron = "0 0 8 * * ?") // Every day at 8 AM
public void generateDailyReport() {
System.out.println("Generating report...");
}
}
@EnableScheduling and @Scheduled
Annotation | Purpose |
---|---|
@EnableScheduling | Enables Spring’s scheduling support |
@Scheduled | Defines the actual scheduled method |
81. How can you implement pagination and sorting in RESTful APIs using Spring Boot?
In Spring Boot, you can implement pagination and sorting in your REST APIs by using Spring Data JPA’s built-in support for Pageable
and Sort
parameters.
Steps to implement implement pagination and sorting
public interface UserRepository extends JpaRepository<User, Long> {
}
Accept Pageable
in Your Controller
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public Page<User> getAllUsers(Pageable pageable) {
return userRepository.findAll(pageable);
}
}
Make API Call with Pagination & Sorting Parameters
GET /api/users?page=0&size=5&sort=name,asc
page
– page number (0-based)size
– number of records per pagesort
– field and direction (e.g.,name,asc
orage,desc
)
82. What is the purpose of the Spring Boot Actuator loggers endpoint and how can you configure log levels?
The /actuator/loggers
endpoint in Spring Boot Actuator allows you to view and change the logging levels of your application at runtime without restarting the application.
Enable and Configure Log Levels
Enable Actuator Endpoints
In application.properties
or application.yml
:
management.endpoints.web.exposure.include=loggers
Set Default Log Levels
You can configure default log levels in application.properties
:
logging.level.root=INFO
logging.level.com.example.service=DEBUG
83. What is logback? How can we use it project?
Logback is a logging framework used in Java applications. It is the default logging implementation in Spring Boot and is intended as a successor to Log4j. It provides a fast, reliable, and flexible logging mechanism and supports powerful configuration options using XML or Groovy.
No extra dependencies are needed, Logback is already included by default in Spring Boot via spring-boot-starter
.
You can use it by creating a logback-spring.xml
file in src/main/resources
to customize log formats, levels, and output (console, file, etc.).
Example
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>
84. How do you handle API versioning in your Spring Boot application?
In Spring Boot, API versioning can be handled using several approaches. The most common and clean way is through URI versioning.
URI Versioning (Recommended)
@RestController
@RequestMapping("/api/v1/users")
public class UserControllerV1 {
@GetMapping
public String getUsersV1() {
return "User list from V1";
}
}
@RestController
@RequestMapping("/api/v2/users")
public class UserControllerV2 {
@GetMapping
public String getUsersV2() {
return "User list from V2";
}
}
85. What is a recoverable exception in Spring, and how do you typically handle it?
A recoverable exception in Spring is an exception that doesn’t require the application to stop and can be gracefully handled or retried to continue the flow. These are typically transient errors like:
- Temporary network failures
- Database connection timeouts
- Message broker (Kafka/RabbitMQ) unavailability
Hibernate & JPA Based Interview Question
86. Tell the difference between JPA and Hibernate.
JPA is a standard/specification, while Hibernate is a concrete implementation of that specification (with added features).
Core Difference:
- JPA is a specification (like an interface).
- Hibernate is an implementation (like a class that implements the interface and adds more).
JPA vs Hibernate – Explained with Example
1. JPA (Using Specification)
When using JPA, you write code using standard annotations like @Entity
, @Id
, @OneToMany
, etc.
You don’t directly use Hibernate classes — you’re writing to the JPA API.
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class User {
@Id
private Long id;
private String name;
}
public interface UserRepository extends JpaRepository<User, Long> {
}
You interact with the JPA interface like EntityManager
:
@Autowired
private EntityManager entityManager;
public void saveUser(User user) {
entityManager.persist(user);
}
You wrote JPA code – Spring Boot uses Hibernate underneath, but you’re not tied to Hibernate. You can switch to EclipseLink or another JPA provider.
2. Hibernate-Specific (Using Hibernate API)
Now, let’s say you bypass JPA and use Hibernate directly:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class HibernateUserDao {
private SessionFactory sessionFactory;
public void saveUser(User user) {
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user); // Hibernate-specific method
session.getTransaction().commit();
session.close();
}
}
SessionFactory
, Session
, and session.save()
are Hibernate-specific APIs.
This ties your code only to Hibernate, and you lose portability.
87. Tell me the some JPA annotations have you used in your project, and what are their purposes?
Some JPA Annotations I Have Used and Their Purposes:
Annotation | Purpose |
---|---|
@Entity | Marks the class as a JPA entity (maps to a database table). |
@Id | Specifies the primary key field of the entity. |
@GeneratedValue | Auto-generates the primary key (e.g., AUTO, IDENTITY, SEQUENCE). |
@Column | Maps a field to a specific column in the database (can define name, length, nullable, etc.). |
@Table | Specifies the table name if different from the class name. |
@OneToOne | Maps a one-to-one relationship between two entities. |
@OneToMany | Maps a one-to-many relationship (e.g., one user has many orders). |
@ManyToOne | Maps a many-to-one relationship (e.g., many orders belong to one user). |
@JoinColumn | Specifies the foreign key column for the relationship. |
@Transient | Tells JPA to ignore the field (not persisted in DB). |
@Lob | Used to store large data (e.g., byte arrays, large text). |
@Temporal | Specifies temporal types for java.util.Date fields (DATE, TIME, TIMESTAMP). |
More questions on Hibernate & JPA -> Hibernate & JPA Interview Questions for Freshers and Experienced (Mostly asked in MNCs)
REST API Design Based Spring Boot Interview Questions
88. After designing your APIs, what process do you follow to test them?
I follow a layered approach unit tests, integration tests, and manual/automated API testing — to ensure my APIs are reliable, secure, and handle edge cases well.
Here’s How I Test APIs:
- Unit Testing
- I write tests for controller, service, and repository layers using JUnit and Mockito.
- This helps validate the logic in isolation.
- Integration Testing
- I use
@SpringBootTest
with MockMvc to test end-to-end API flow. - I ensure that the API endpoints work correctly with the database and service layers.
- I use
- API Testing with Postman or Swagger
- I use Postman to manually test all endpoints (GET, POST, PUT, DELETE).
- I verify input validation, status codes, and responses.
- If Swagger is integrated, I test APIs directly from the UI.
- Negative & Edge Case Testing
- I test with invalid inputs, missing fields, and boundary values to ensure proper error handling.
- Authentication/Authorization Testing
- If JWT or OAuth2 is used, I test protected endpoints with and without valid tokens.
- Automation (Optional)
- For larger projects, I write REST-assured or Postman Collection tests for automation.
89. What are some best practices you follow while designing REST APIs in Spring Boot?
I focus on REST standards, clean URIs, proper validation, consistent responses, and secure, well-documented endpoints to build scalable and maintainable APIs.
Best Practices I Follow While Designing REST APIs in Spring Boot:
- Use Proper HTTP Methods
GET
for fetching,POST
for creating,PUT
for updating,DELETE
for deletion.
- Follow Resource Naming Conventions
- Use nouns and plural forms:
/api/users
,/api/orders/{id}
- Avoid verbs in URLs.
- Use nouns and plural forms:
- Use Consistent and Meaningful Status Codes
200 OK
,201 Created
,400 Bad Request
,404 Not Found
,500 Internal Server Error
, etc.
- Return Standardized JSON Responses
- Use a consistent response structure (with
status
,message
, anddata
).
- Use a consistent response structure (with
- Use DTOs (Data Transfer Objects)
- Never expose entities directly. Use DTOs for request/response to separate concerns.
- Validation with
@Valid
and@NotNull
- Ensure request payloads are validated before processing.
- Exception Handling with
@ControllerAdvice
- Centralized error handling for clean and meaningful error responses.
- Pagination & Sorting Support
- Use
Pageable
in endpoints that return large data sets.
- Use
- Versioning APIs
- Example:
/api/v1/users
to ensure backward compatibility.
- Example:
- Secure Endpoints
- Use JWT, OAuth2, or Spring Security to protect sensitive APIs.
- Use OpenAPI (Swagger)
- For auto-generated API documentation and easy testing.
90. What is the purpose of the HTTP 203 status code?
The HTTP 203 status code means: The request was successful, but the enclosed payload has been modified by a transforming proxy.
More questions on Rest API -> Spring Boot REST API Interview Questions for Freshers and Experienced
Micro Service Spring Boot interview question
91. Difference between the microservice and monolith architecture.
Monolithic Architecture is a single, tightly-coupled application where all components (UI, business logic, database) are packaged and deployed together. It’s simple to develop but hard to scale and maintain as it grows.
Microservices Architecture breaks the application into smaller, independent services that communicate over the network. Each service can be developed, deployed, and scaled individually, making it ideal for complex, large-scale systems.
92. What is Saga Design pattern?
The Saga Design Pattern is a microservices pattern used to manage distributed transactions across multiple services without using a global transaction manager. It ensures data consistency in distributed systems by breaking a transaction into a sequence of local transactions, each handled by a different service.
Types of Saga Patterns:
- Choreography (Event-driven):
- Services listen to events and react accordingly.
- No central coordinator.
- Lightweight and decoupled.
- Orchestration (Command-driven):
- A central orchestrator directs the saga by calling each service.
- Easier to monitor and control.
Example:
Order Service → Payment Service → Inventory Service
- If the inventory update fails, the Saga will trigger:
Inventory rollback → Payment refund → Order cancellation
More questions on Micro Service Spring Boot -> Real-time, project-based Micro Service Spring Boot Interview Questions
Docker, Kubernetes, and Kafka
93. What is Docker, and how do Docker images work in the context of application deployment?
Docker is an open-source platform that enables developers to build, package, and run applications in lightweight, portable containers. A Docker container includes the application code along with all its dependencies, libraries, and environment settings — ensuring it runs reliably across different environments.
What Is a Docker Image?
A Docker image is a read-only template that contains:
- The application code
- Runtime (e.g., Java, Node.js)
- Dependencies
- Environment variables
- Configuration files
It acts as a blueprint to create one or more containers.
94. What is Kafka, and why is it used in microservices or Spring Boot applications?
Apache Kafka is a distributed event streaming platform used for building real-time data pipelines and event-driven systems. It is designed to handle high-throughput, low-latency data transmission between components in a fault-tolerant and scalable manner.
Why Kafka Is Used in Microservices or Spring Boot Applications
Feature | Purpose |
---|---|
Decoupling Services | Kafka acts as a message broker, allowing services to communicate asynchronously without knowing about each other. |
High Throughput | Can handle millions of messages per second — ideal for large-scale apps. |
Fault Tolerance | Kafka replicates data across brokers, ensuring no message loss. |
Scalability | Easily handles increased load by adding brokers and partitions. |
Event-Driven Architecture | Enables event sourcing and CQRS in microservices. |
Durability | Messages are persisted on disk, making it reliable for audit logs or reprocessing. |
More questions on Docker, Kubernetes, and Kafka -> Most-asked Docker, Kubernetes, and Kafka interview questions for full stack developers
SQL & Database Based Interview Question
95. Different types of joins in SQL and when you would use each?
1. INNER JOIN
- Returns: Only the matching rows from both tables.
- Use When: You want only the records that exist in both tables.
Example: Get customers who have placed an order.
SELECT * FROM Customers
INNER JOIN Orders ON Customers.id = Orders.customer_id;
2. LEFT JOIN (or LEFT OUTER JOIN)
- Returns: All records from the left table, and matching records from the right table. If no match, returns NULLs.
- Use When: You want all data from the left table, even if there’s no match in the right table.
Example: List all customers, even those who haven’t placed an order.
SELECT * FROM Customers
LEFT JOIN Orders ON Customers.id = Orders.customer_id;
3. RIGHT JOIN (or RIGHT OUTER JOIN)
Returns: All records from the right table, and matching records from the left table. If no match, returns NULLs.
- Use When: You want all data from the right table, even if there’s no match in the left.
Example: List all orders, even if customer info is missing.
SELECT * FROM Orders
RIGHT JOIN Customers ON Customers.id = Orders.customer_id;
4. FULL JOIN (or FULL OUTER JOIN)
- Returns: All records from both tables. If there’s no match on either side, NULLs are used.
- Use When: You want everything from both tables, regardless of matches.
Example: Show all customers and all orders, even unmatched ones.
SELECT * FROM Customers
FULL OUTER JOIN Orders ON Customers.id = Orders.customer_id;
5. CROSS JOIN
Returns: Every combination of rows from both tables (Cartesian product).
- Use When: You want all possible combinations (used rarely and carefully).
Example: Match each product with every store for combinations.
SELECT * FROM Products
CROSS JOIN Stores;
96. What is limit and offset in SQL?
LIMIT
and OFFSET
are used in SQL to control the number of rows returned by a query, especially useful for pagination.
LIMIT
- Restricts the maximum number of rows returned.
- Commonly used to fetch a fixed number of results.
SELECT * FROM Products
LIMIT 5;
Returns only the first 5 rows.
OFFSET
- Skips a specified number of rows before starting to return rows.
- Often used with LIMIT to implement pagination.
SELECT * FROM Products
LIMIT 5 OFFSET 10;
📌 Skips the first 10 rows, then returns the next 5 rows (rows 11–15).
More questions on SQL -> Master These SQL Questions Before Your Next Interview – Freshers to Experts
Now, let’s move on to the interview clearing guide. Here are some tips to help you succeed in a Spring Boot interview:
- Review the Basics: Ensure you have a strong understanding of the fundamental concepts of Spring Boot, including dependency injection, annotations, and inversion of control.
- Hands-on Experience: Be prepared to discuss your experience working with Spring Boot. Showcase any relevant projects or assignments you have completed using the framework.
- Understand Spring Boot Features: Familiarize yourself with key Spring Boot features such as auto-configuration, Actuator, data access with Spring Data JPA, security, and caching. Be ready to explain how you have utilized these features in your projects.
- Demonstrate Problem-Solving Skills: Expect questions that require you to solve problems related to Spring Boot. Prepare yourself by practicing coding exercises and scenarios that involve troubleshooting and debugging.
- Dive into Documentation: Take the time to explore the official Spring Boot documentation. Understand the various configuration options, available annotations, and best practices recommended by the framework.
- Stay Up-to-Date: Keep yourself updated with the latest trends and advancements in Spring Boot. Stay informed about new releases, enhancements, and community-driven developments.
- Prepare for Common Interview Questions: Review commonly asked interview questions and practice your answers. This will help you articulate your thoughts effectively during the interview.
- Showcase your Practical Knowledge: Whenever possible, share examples from your previous projects where you have utilized Spring Boot effectively. Discuss the challenges you faced and how you overcame them.
- Be Confident and Professional: Approach the interview with confidence and maintain a professional demeanor throughout. Display your enthusiasm for Spring Boot and your eagerness to learn and grow as a developer.
- Ask Questions: At the end of the interview, don’t hesitate to ask questions about the company’s usage of Spring Boot, their development processes, or any other relevant topics. This demonstrates your interest in the role and your desire to understand the organization better.
Conclusion
We hope this curated list of Spring Boot interview questions has given you a clear idea of what to expect in real-world interviews especially if you have 4+ years of hands-on Java development experience.
Whether you’re targeting product-based companies, top MNCs, or startups, these questions cover everything from core Spring Boot concepts to advanced scenario-based problems. Practicing these will not only strengthen your fundamentals but also help you explain your answers with clarity and confidence.
If you found this blog helpful, please do the following:
✔️ Share it with your friends or colleagues preparing for interviews
✔️ Bookmark it for revision before your interview
✔️ Comment below if you want answers to any specific question or need a detailed explanation
✔️ Explore our other blogs on Java Coding Questions, Microservices Interview Preparation Using Spring Boot, and Java 8 interview preparation
🔔 Stay connected for more real-time coding problems and interview experiences!