Next-Gen App & Browser
Testing Cloud
Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles
Master 40+ Spring Boot interview questions, from basics to advanced, to boost your Java, microservices, and application development skills.
OVERVIEW
Spring Boot has been the cornerstone for Java applications for years, making it a top choice among developers. As a child framework under the Spring umbrella, Spring Boot simplifies Java application development by reducing repetitive code and configuration. By following the principle of “convention over configuration,” it streamlines the setup process, allowing developers to focus more on business logic and automate the infrastructure process.
If you're developing Java applications with Spring Boot or a fresher aiming to showcase your expertise, you must review these Spring Boot interview questions. Covering topics from basic concepts to advanced techniques, they help you prepare confidently and demonstrate your skills effectively.
Note : We have compiled all Spring Boot Interview Questions for you in a template format. Check it out now!
The fresher-level questions focus on Spring Boot's core concepts, making them ideal for those new to the framework or anyone wanting to revisit the basics.
These Spring Boot interview questions cover key topics like Spring Boot key features, the role of the @SpringBootApplication annotation, configuration, and more. Mastering these fundamentals is key to understanding how Spring Boot operates.
This is one of the most commonly asked questions in Spring Boot interview questions. Spring Boot is one of the Java frameworks designed to create production-quality, stand-alone Spring-based applications. It's widely used for building microservices and RESTful web services, making it a top choice for Java development. Spring Boot was created to simplify the setup process by eliminating the need for manual configuration, allowing developers to focus on building their applications.
Spring Boot has its own specific features that distinguish it from its umbrella framework, Spring. It offers several capabilities to speed up and simplify the setup and configuration process.
Here are a few of Spring Boot's main attributes:
Spring Boot is one of the sub-frameworks within Spring that is specifically used for creating RESTful applications that provide multiple embedded and monitoring components that further reduce the complexity of the application. This improves the durability of the application and makes it more secure.
Understanding these differences is essential, as they are commonly asked in Spring Boot interview questions and help you grasp the framework's core benefits and real-world applications.
Aspects | Spring | Spring Boot |
---|---|---|
Purpose | Comprehensive framework for Java applications | Streamlined framework for creating Spring-based applications |
Complexity | Moderate | Minimal |
Configuration | Manual | Auto-configurable |
Deployment | Requires external server | Comes with an embedded server |
Features | Dependency Injection, AOP | Opinionated Defaults |
Use Case | Enterprise-level Java applications | Rapid application development for microservices |
Integration | It can be integrated with Spring Boot | Stand-alone framework |
Learning Curve | Relatively steep | Moderate |
@PathVariable helps extract values from the URI path in Spring Boot, whereas @RequestParam is used to extract query parameters from the URL. Understanding these differences is crucial for developers, as they are commonly asked in Spring Boot interview questions when mapping client requests to controller methods in Spring Boot applications.
Aspects | @RequestParam | @PathVariable |
---|---|---|
Usage | Query parameters | Path variables |
Mapping | Request parameters with matching names | Maps to URI template variables |
Position | It can be placed anywhere in the method parameter list | Must be placed directly in the method parameter |
Required | Optional | Required |
Binding | Optional binding to a default value if not present | Binds directly to the URI template variable |
URL Encoding | Required for special characters in parameter values | Automatically decoded |
Example | @RequestParam(“employeeName”) String employeeName; | @PathVariable(“id”) int id; |
Spring Boot uses a utility called Spring Boot Starter to simplify dependency management. These starters are collections of useful dependency descriptors that you can include in your application. For example, to use Spring Data JPA, simply add the Spring Boot-starter-data-jpa dependency, and it will automatically include all the required dependencies.
Additionally, Maven or Gradle manages these dependencies, and Spring Boot ensures compatibility by maintaining the versions of supported dependencies. This helps eliminate version conflicts and reduces the need for manual version management. Understanding how Spring Boot handles dependencies is a key topic and often appears in most interview questions.
In simple terms, @RestController is used when you want to build a web service that sends data directly to a client, like a web browser or an app. This annotation combines two things: it marks the class as one that will handle web requests, and it tells Spring to return data from methods in this class directly to the client.
The data is automatically converted into formats like JSON or XML, making it easier to develop APIs without manually handling data conversion. Since @RestController is essential for building APIs, it is a common topic to appear in most of the Spring Boot interview questions.
In Spring Boot, the application.properties or application.yml file is used for configuring the application. These files allow you to set various properties and settings, such as server port, database connection details, and custom application settings. By placing this configuration in a centralized file, you can easily manage and change them without modifying the code.
The application.yml file uses YAML format, which is more readable for nested configurations, while application.properties is a simple key-value pair format.
Example of application.properties:
# Server configuration
server.port=8080
# Database configuration
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=password
# JPA (Java Persistence API) settings
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
Both files serve the same purpose and are loaded by Spring Boot at runtime to configure the application’s behavior. Since configuration management is a crucial topic in Spring Boot, having an understanding of these files for a developer is essential, making it the most frequent question to appear in most of the Spring Boot interview questions.
Spring Boot streamlines database integration through automated configuration and libraries. Here is a quick guide to the key concepts:
Example: Add this to either your pom.xml or your build.gradle:
Maven:
<groupId>org.springframework.boot</groupId>
<artifactId>Spring Boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
Gradle:
implementation 'org.springframework.boot:Spring Boot-starter-data-jpa'
implementation 'mysql:mysql-connector-java'
Configure the following database connectivity properties in your application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/yourdbname
spring.datasource.username=yourusername
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
Since database configuration is a critical aspect of Spring Boot development, it frequently appears in Spring Boot interview questions, making it essential for candidates to understand.
Note : Streamline configuration, optimize performance, and build robust applications effortlessly. Try LambdaTest Now!
Spring Boot Actuator is a rich collection of features that contain a set of tools that offer insights into a Spring Boot application's internal workings. It becomes simpler for developers to watch activity, identify problems, and make sure the application is operating as intended by assisting with monitoring and managing their applications in production using the features of the Actuator.
Purpose of Spring Boot Actuator
The main purpose of Actuator is to give you a detailed view of your application’s health, metrics, and environment without requiring you to manually implement these features. It automatically exposes various endpoints that provide valuable information and operational control over your application.
Key Features of Spring Boot Actuator:
The actuator automatically exposes several endpoints, each providing different types of information or control over the application:
Since Actuator plays a crucial role in application observability, these endpoints can be secured, and you can choose which ones to expose based on your needs. They are useful in both development and production environments. It is often discussed in Spring Boot interview questions, making it important for developers to understand how to configure and use it effectively.
The @SpringBootTest annotation in Spring Boot is used for integration testing by loading the entire application context, similar to how the application runs in production. It ensures that all components, such as the service layer, repository layer, and controller, work together correctly. Understanding the @SpringBootTest usage is crucial for developers, and it is often highlighted in Spring Boot interview questions,
When to use it:
Imagine you are working on a Spring Boot application and want to ensure that your service layer and repository layer function correctly. You wouldn’t typically use it for simple unit tests, as it would be excessive for testing a single method. However, for integration tests—where different parts of your application interact—it is ideal. It’s like saying, “Okay, let’s fire up the whole application and see how these pieces work together.”
A microservice is a small, independent service that performs a specific function within a large application. This architecture makes it easier to define and maintain each service, and it can be developed and managed independently.
This concept is frequently asked in most Spring Boot interview questions, as developers must understand microservice architecture. Spring Boot is a framework that simplifies the creation of microservices in Java.
It offers several features to support microservices:
Spring Boot is a stand-alone framework that comes with an embedded server, eliminating the need to install and configure any external server. This reduces complexity by allowing you to avoid deploying your application to an external server, as the server is packaged within the application itself. This makes the deployment and management process easier.
Here are some key points about embedded servers in Spring Boot:
The Spring Boot interview questions discussed above are essential for any fresher, as they establish a foundational understanding of key concepts and practices in Spring Boot development. Grasping these fundamentals is crucial for building a solid skill set and excelling in interviews.
As you progress, you will encounter intermediate-level Spring Boot interview questions that will enhance your knowledge and expertise. This progression will enable you to tackle more complex topics and scenarios, helping you advance your skills in Spring Boot development.
The intermediate-level Spring Boot interview questions delve deeper into Spring Boot's fundamental features, testing your understanding of topics such as dependency injection, RESTful services, security, and data management. These questions are designed for developers with some hands-on experience and aim to evaluate your practical understanding and ability to apply these principles in real-world scenarios.
In Spring Boot, writing unit tests is a must to make sure all the parts of your program function as intended. Unit tests concentrate on testing distinct components of your program separately, which aids in the early detection of defects and acts as a safety precaution while reworking code.
This is how you go about it:
It sets up a test context that mimics the real application context but isolates it from the components you want to test. This makes it easier to test Spring-managed beans without having to load the entire application.
However, for unit tests, you will usually rely more on @Mock (from Mockito) and @InjectMocks to create and inject mock dependencies, keeping the test focused on the unit of code you’re testing.
For example, if you’re testing a service that depends on a repository, you would mock the repository so that it returns predefined data instead of hitting a real database. This ensures that your test remains fast and reliable.
Consider the following example: Let's assume we need to test the following method within the class DiscountService:
public class DiscountService {
public double calculateDiscount(String membershipLevel, double purchaseAmount) {
switch (membershipLevel.toLowerCase()) {
case "gold":
return purchaseAmount * 0.20; // 20% discount
case "silver":
return purchaseAmount * 0.10; // 10% discount
case "bronze":
return purchaseAmount * 0.05; // 5% discount
default:
return 0.0; // No discount
}
}
}
The DiscountServiceTest.java would look something similar to:
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class DiscountServiceTest {
private final DiscountService discountService = new DiscountService();
@Test
public void testGoldMemberDiscount() {
double discount = discountService.calculateDiscount("gold", 100.0);
assertEquals(20.0, discount, "Gold members should get a 20% discount");
}
@Test
public void testSilverMemberDiscount() {
double discount = discountService.calculateDiscount("silver", 100.0);
assertEquals(10.0, discount, "Silver members should get a 10% discount");
}
@Test
public void testBronzeMemberDiscount() {
double discount = discountService.calculateDiscount("bronze", 100.0);
assertEquals(5.0, discount, "Bronze members should get a 5% discount");
}
@Test
public void testNoDiscountForOtherLevels() {
double discount = discountService.calculateDiscount("platinum", 100.0);
assertEquals(0.0, discount, "Non-standard membership levels should get no discount");
}
}
Writing clean, effective unit tests is essential for maintaining high code quality, and this is often a key point highlighted in Spring Boot interviews for development roles.
Creating a simple RESTful web service with Spring Boot is straightforward. Here’s a step-by-step guide:
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.atomic.AtomicLong;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
Creating a simple RESTful web service with Spring Boot is essential for developers, as it demonstrates the core concepts of building RESTful web services. It's also often asked in most Spring Boot interview questions.
A Spring Boot starter is a convenient way to integrate a collection of useful dependencies into your application. It provides a curated set of interdependent dependencies, making it easier to build Spring-based projects.
Here are some key points about Spring Boot starters:
Here are some of the widely used Spring Boot starters:
To use a starter dependency in your project, you need to include it in your pom.xml (for Maven) or build.gradle (for Gradle).
Maven, add the following to your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>Spring Boot-starter-web</artifactId>
</dependency>
Gradle, add the following to your build.gradle:
implementation 'org.springframework.boot:Spring Boot-starter-web'
OR
api('org.springframework.boot:Spring Boot-starter-web')
You must use the correct version of dependencies according to your project requirements, as version conflicts can cause issues in your codebase, especially depending on the version of Java you're using. This is a core concept in Spring Boot, as it simplifies dependency management and promotes best practices, and it is often covered in most Spring Boot interview questions.
The @SpringBootApplication annotation is an important annotation in a Spring Boot application, which is used by the compiler to identify the main class in your project. During runtime, this annotation helps in jumping directly to the main class and executing it.
It combines the following three annotations into one:
Here is a basic example:
package com.org.lambdaTest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Reservation {
public static void main(String[] arguments) { // main class
SpringApplication.run(Reservation.class, args); // this informs your spring application which class needs to run initially
}
}
By using @SpringBootApplication, you simplify your configuration by combining three annotations into one, allowing you to use their default attributes. This setup initiates the Spring Boot application and automatically starts the necessary configuration, making it a core concept in Spring Boot, often highlighted in most Spring Boot interview questions.
In Spring, the @Component, @Service, and @Repository annotations are used to define classes that Spring should manage as beans. These annotations are commonly highlighted in most of the Spring Boot interview questions because each one has a specific purpose, though they all serve the general role of marking classes for Spring to handle.
When to Use It: You might use @Component when you’ve got a class that’s part of your application’s core functionality but doesn’t quite fit into the “service” or “repository” categories. For instance, if you have a class that handles some internal processing or utility functions, @Component is a good fit. A real-time example would be to use this annotation for any middle-ware processing.
When to Use It: You’ll use @Service for classes that perform core operations, like processing data, handling transactions, or coordinating actions between different parts of your application.
When to Use It: You’ll want to use @Repository in classes that deal directly with data—whether you’re retrieving it from a database, saving it, or updating it. If your class is focused on managing how data is accessed and stored, @Repository is the way to go.
Implementing security in a Spring Boot application typically involves using Spring Security, a powerful and customizable authentication and access control framework. Here’s a general approach:
Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>Spring Boot-starter-security</artifactId>
</dependency>
Gradle:
implementation 'org.springframework.boot:Spring Boot-starter-security'
This configuration allows you to:
Imagine starting a new project with Spring Boot. While using Spring, you would need to manually declare all configurations, but with Spring Boot, instead of manually configuring each component, the heavy lifting for you.
Here's how it works:
Example:
@SpringBootApplication
public class EmployeeReservation {
public static void main(String[] args) {
SpringApplication.run(Employee.class, args);
}
}
This approach to autoconfiguration in Spring Boot eliminates a lot of repetitive setups, allowing you to focus on building the functionality of your application. It's a concept that is frequently highlighted in most of the Spring Boot interview questions to understand Spring Boot's ease of use and configuration management.
Custom starters in Spring Boot are essentially pre-packaged sets of dependencies and configurations that simplify the setup for specific functionalities. They help developers avoid repetitive configuration tasks and quickly get started with their projects.
Here’s a step-by-step guide to creating your own custom starter:
@Configuration
@ConditionalOnClass(EmployeeUtil.class)
public class EmployeeServiceAutoConfiguration {
@Bean
public EmployeeServiceDepartment formatEmployeeServiceDepartment() {
return new EmployeeServiceDepartment();
}
}
@ConfigurationProperties(prefix = "generic")
public class GenericProperties {
private String propertyType;
// getters and setters
}
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.MyCustomAutoConfiguration
This process of creating custom starters is often highlighted in most of the Spring Boot interview questions as it helps streamline the application's configuration.
Spring Boot is built on the Spring framework, which simplifies the development of new Spring applications. It follows a layered architecture, with each layer having a specific responsibility and communicating directly with adjacent layers.
Layers of Spring Boot
How It All Works Together
When you start a Spring Boot application, it begins with the main method, which invokes SpringApplication.run(). This method bootstraps the application, starting the Spring context and auto-configuring beans based on the dependencies you have included.
The above internal architecture of Spring Boot ensures a smooth, streamlined application setup, focusing on simplicity and convention over configuration. This architecture is fundamental in Spring Boot, and it has often been highlighted in most of the Spring Boot interview questions as it helps in developing modern applications.
Optimizing performance in a Spring Boot application can be quite rewarding. Several strategies can help your application run more efficiently.
Here are some practical tips:
Spring Boot offers several ways to externalize configuration, making it easier to manage different environments.
Here are some of the key steps:
@Value("${unit.property}")
private int id;
@ConfigurationProperties(prefix = "id")
public class EmployeeProperties {
private String description;
// getters and setters
}
@Autowired
private Environment env;
public void printUnitDescriptionProperty() {
System.out.println(env.getProperty("unit.description"));
}
By following these key methods, you can significantly enhance the performance of your Spring Boot application, ensuring it runs efficiently and smoothly, even as it scales. This topic is often a central focus in many Spring Boot interview questions, as it demonstrates an understanding of optimizing applications for better performance.
OAuth2 is one of the most important Spring Boot components that is used to manage the flow between clients and one or more HTTP services.
Let's comply with the following steps to implement the same:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
spring.security.oauth2.client.registration.google.client-id=your-client-id
spring.security.oauth2.client.registration.google.client-secret=your-client-secret
spring.security.oauth2.client.registration.google.scope=profile, email
spring.security.oauth2.client.provider.google.authorization-uri=https://accounts.google.com/o/oauth2/auth
spring.security.oauth2.client.provider.google.token-uri=https://oauth2.googleapis.com/token
spring.security.oauth2.client.provider.google.user-info-uri=https://www.googleapis.com/oauth2/v3/userinfo
spring.security.oauth2.client.provider.google.user-name-attribute=sub
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/login**").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login();
}
}
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
@Controller
public class MainController {
@GetMapping("/")
public String index(Model model, OAuth2AuthenticationToken authentication) {
if (authentication != null) {
model.addAttribute("name", authentication.getPrincipal().getAttributes().get("username"));
}
return "index";
}
}
<!DOCTYPE >
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Testing OAuth2 Login</title>
</head>
<body>
<h1>Welcome to OAuth2 Testing component!</h1>
<div th:if="${example}">
<p>Hello, <span th:text="${example}"></span>!</p>
</div>
<div th:if="${example == null}">
<a href="/oauth2/authorization/google">Login with Google</a>
</div>
</body>
</html>
This is a common topic in Spring Boot and has frequently appeared in Spring Boot interview questions. It's essential for developers to understand how to integrate OAuth2 with Spring Security for user authentication. By following these steps, your Spring Boot application will successfully integrate OAuth2 login, allowing users to authenticate via Google (or another provider if desired).
One of the most important components to implement after you have implemented your application is security. You need to implement security to protect your application and data from unauthorized access. Following are the steps that can be followed to secure your REST APIs using Spring Security:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
// Getters and setters
}
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>());
}
}
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class ApiController {
Address employeeAddress = new Address("Chennai");
@GetMapping("/companyPolicy")
public String getCompanyPolicy() {
return "Following are the company's policy";
}
@GetMapping("/employeeAddress")
public Address getEmployeeAddress() {
System.out.println("Employee’s address is as follows: ");
return employeeAddress;
}
}
By following the above steps, you can easily secure your REST APIs in Spring Boot using Spring Security. This process is often highlighted in most of the Spring Boot interview questions as it helps ensure that unauthorized users cannot access your sensitive data. The integration of JWT or other forms of token-based authentication can further strengthen your API security.
One of the most important components to implement after you have implemented your application is security. You need to implement security to protect your application and data from unauthorized access. Following are the steps that can be followed to secure your REST APIs using Spring Security:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>Spring Boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.springframework.data.jpa.repository.JpaRepository;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
// Getters and setters
}
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>());
}
}
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/employee")
public class EmployeeController {
String employeePolicy = "This is the employeePolicy";
Address address = new Address("New Delhi");
@GetMapping("/employeePolicy")
public String getEmployeePolicy() {
return employeePolicy;
}
@GetMapping("/employeeAddress")
public Address getEmployeeAddress() {
System.out.println("This is a private endpoint:");
return address;
}
}
Setting up CI/CD integration with Spring Boot helps manage code, automate deployment pipelines, manage dependencies, and secure applications in CI/CD scenarios. It is one of the most important topics in Spring Boot and is often asked in most interview questions.
Once you are done with creating your application, your next step should be to implement tests that would test your application at a granular level and the entire application. Following are some of the standard practices that can be followed:
Example:
@SpringBootTest
public class EmployeeIntegrationTest {
@Autowired
private EmployeeAddress getEmployeeAddress;
@Test
public void testEmployeeAddress() {
// Test logic here
}
}
Example:
@MockBean
private EmployeeRepository employeeRepository;
spring:
datasource:
url: jdbc:h2:mem:testdb
driverClassName: org.h2.Driver
username: sa
password: password
Example:
@TestConfiguration
public class TestConfig {
@Bean
public EmployeeService getEmployeeAddress() {
return new EmployeeAddressImpl();
}
}
Example:
@SpringBootTest
@Transactional
public class EmployeeDataInsertionTest {
// Test methods
}
Note: Use profiles to separate test configurations from production configurations.
Example:
@Test
@DirtiesContext
public void testDateConversion() {
// Test logic
}
Example:
@Autowired
private MockMvc mockMvc;
@Test
public void testGetCustomerDepartment() throws Exception {
mockMvc.perform(get("/api/customer/department"))
.andExpect(status().isOk())
.andExpect(content().string("Human Resources"));
}
The following best practices can help ensure that your integration tests in Spring Boot are effective and maintainable. These practices are commonly asked in most of the Spring Boot interview questions, as they highlight essential testing strategies for building reliable applications.
These experienced-level Spring Boot interview questions focus on advanced topics such as performance optimization, microservices architecture, security best practices, and testing strategies.
Here, questions are designed for developers with significant experience, enabling them to demonstrate their deep understanding and ability to solve complex challenges in Spring Boot applications.
Mocking dependencies in Spring Boot is the core topic, and it is often covered in most Spring Boot interview questions. It is a great way for developers to isolate the components being tested and ensure that tests are reliable and fast.
Here are some practical steps and tips to help you get started:
Example:
@SpringBootTest
public class MyServiceTest {
@MockBean
private MyRepository myRepository;
@Autowired
private MyService myService;
@Test
public void testServiceMethod() {
// Define behavior for the mock
when(myRepository.findById(1L)).thenReturn(Optional.of(new MyEntity()));
// Call the service method
MyEntity result = myService.findById(1L);
// Verify the result
assertNotNull(result);
}
}
Example:
@ExtendWith(MockitoExtension.class)
public class MyServiceTest {
@Mock
private MyRepository myRepository;
@InjectMocks
private MyService myService;
@Test
public void testServiceMethod() {
// Define behavior for the mock
when(myRepository.findById(1L)).thenReturn(Optional.of(new MyEntity()));
// Call the service method
MyEntity result = myService.findById(1L);
// Verify the result
assertNotNull(result);
}
}
Example:
@SpringBootTest
public class MyServiceTest {
@SpyBean
private MyService myService;
@MockBean
private MyRepository myRepository;
@Test
public void testServiceMethod() {
// Define behavior for the mock
when(myRepository.findById(1L)).thenReturn(Optional.of(new MyEntity()));
// Call the service method
MyEntity result = myService.findById(1L);
// Verify the result
assertNotNull(result);
verify(myService).findById(1L);
}
}
Example:
@ExtendWith(MockitoExtension.class)
public class MyServiceTest {
@Mock
private MyRepository myRepository;
@InjectMocks
private MyService myService;
@Test
public void testServiceMethod() {
// Define behavior for the mock
when(myRepository.findById(1L)).thenReturn(Optional.of(new MyEntity()));
// Call the service method
MyEntity result = myService.findById(1L);
// Verify the result
assertNotNull(result);
}
}
Effectively designing Spring Boot microservices is a crucial topic, and it is often highlighted in most interview questions. A well-structured microservices architecture ensures scalability, maintainability, and efficient communication.
Below are the steps on how to design and deploy a Spring Boot microservices :
Example: The user management service may use a relational database, while the product catalog service may use NoSQL.
Example:
spring:
cloud:
config:
uri: http://config-server:8888
Example:
@EnableEurekaClient
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Example:
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
Deploying Spring Boot Microservices:
Example:
FROM openjdk:11-jre-slim
COPY target/my-service.jar my-service.jar
ENTRYPOINT ["java", "-jar", "my-service.jar"]
Example:
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-service
spec:
replicas: 3
selector:
matchLabels:
app: my-service
template:
metadata:
labels:
app: my-service
spec:
containers:
- name: my-service
image: my-service:latest
ports:
- containerPort: 8080
Example:
name: CI/CD Pipeline
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 11
uses: actions/setup-java@v1
with:
java-version: 11
- name: Build with Maven
run: mvn clean install
- name: Build Docker image
run: docker build -t my-service:latest .
- name: Push Docker image
run: docker push my-service:latest
Below is a short description of how Spring Cloud is related to Spring Boot:
When deployed on cloud platforms like AWS, Azure, or Google Cloud, Spring Cloud enables seamless scaling, load balancing, and resilience, making it easier to manage and optimize microservices-based architectures.
As cloud-native applications scale, ensuring their reliability and performance across diverse environments becomes crucial. This is where the LambdaTest cloud-based testing platform enhances Spring Cloud applications by providing a scalable and efficient testing infrastructure.
By leveraging LambdaTest, teams can validate their Spring Cloud applications through both manual and automated Spring testing across 3000+ browser and OS combinations. This helps detect compatibility issues early, ensuring smooth operation in real-world distributed environments.
With LambdaTest, developers can:
By integrating Spring Cloud with LambdaTest online testing cloud, teams can achieve faster releases, greater test coverage, and improved application resilience, making it an indispensable combination for modern cloud-native development. Understanding Spring Cloud is crucial for developers working with microservices and cloud-native applications, making it a common topic in Spring Boot interview questions.
Below is the use of Eureka and Ribbon in detail as understanding these concepts is essential as they frequently appear in Spring Boot interview questions, especially when discussing microservices and service discovery.
How They Work Together
When you combine Eureka and Ribbon, you get a dynamic and resilient system. Here’s a simplified flow:
Distributed tracing is generally used for monitoring and troubleshooting in a microservices architecture.
Here’s how you can handle distributed tracing in Spring Boot microservices:
Key Components
Steps to Implement Distributed Tracing
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
spring.zipkin.base-url=http://localhost:9411
spring.sleuth.sampler.probability=1.0
docker run -d -p 9411:9411 openzipkin/zipkin
Example Flow: Imagine you have three microservices: Service A, Service B, and Service C. A request starts at Service A, which calls Service B, and then Service B calls Service C. With distributed tracing:
Benefits:
Understanding distributed tracing is a valuable topic in Spring Boot, and it’s often asked in most of the Spring Boot interview questions, as it helps explain how to diagnose latency issues and improve microservices performance.
Communication between services is an important part of microservice architecture. Here are some examples used to ensure efficient and reliable communication between services:
The choice of communication model depends on the specific needs of the application. Asynchronous communication is efficient but can lead to tight coupling and potential bottlenecks.
Synchronous communication, on the other hand, provides better isolation and flexibility but is more complex to implement. Inter-service communication is a crucial aspect of Spring Boot interview questions, as it determines how microservices interact while ensuring scalability and fault tolerance.
The following procedures can be used to construct the Spring Boot application once the environment setup is complete:
Prereq:
Once you are ready with the environment setup, you must follow the steps to create the Spring Boot application:
Method-1:
Method-2:
Example:
package com.org.lambdaTest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Reservation {
public static void main(String[] arguments) { // main class
SpringApplication.run(Reservation.class, args); // this informs your spring application which class needs to run initially
}
}
Example:
package com.org.lib.lambdaTest;
iimport org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController // informs the compiler that this is a controller
public class Employer {
@GetMapping("/getAllEmployers") // informs the compiler of the uri
public String hello() {
return "Here is a list of all Emlpoyers";
}
}
This step-by-step approach above is a common topic in Spring Boot, and it is one of the most commonly asked Spring Boot interview questions, as the understanding of setting up and running a Spring Boot application efficiently.
Handling transactions in any application is the most crucial part that ensures data consistency and integrity, especially in applications that involve multiple database operations and confidential information.
Here’s a straightforward guide on how to manage transactions effectively:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>Spring Boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
@SpringBootApplication
@EnableTransactionManagement
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional
public void createUser(User user) {
userRepository.save(user);
// Additional operations can be added here
}
}
Key Features of @Transactional:
Sample Example: Consider a service where you have user registration. The service stores information about users and sends them emails. If the user fails to save, the email should not be sent and vice versa. By using @Transactional, you can ensure that both operations are part of the same transaction:
@Service
public class RegisterService {
@Autowired
private UserService userService;
@Autowired
EmailService Private EmailService.
@Transactions
public void registerUser(User user) {
userService.createUser(user);
emailService.sendWelcomeEmail(user);
}
}
In this example, if createUser or sendWelcomeEmail fails, all transactions are rolled back, and data consistency is guaranteed.
One of the most integral components of the Spring Data family is the Spring Data JPA, having the responsibility of making it easy for data management and access to it.
JPA Databases are usually used while working with any of the source applications as it adds an abstraction layer on top of JAP.
Follow the below steps:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>Spring Boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
spring.datasource.url=jdbc:mysql://localhost:3306/yourdatabase
spring.datasource.username=yourusername
spring.datasource.password=yourpassword
spring.jpa.hibernate.ddl-auto=update
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and setters
}
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByName(String name);
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getAllUsers() {
return userRepository.findAll();
}
public User saveUser(User user) {
return userRepository.save(user);
}
}
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> getAllUsers() {
return userService.getAllUsers();
}
@PostMapping
public User createUser(@RequestBody User user) {
return userService.saveUser(user);
}
}
Merits of Spring Data JPA:
Caching is usually used to improve the performance of your application (which is basically the reads and writes that constantly happen to and from your DB).
Let's see the steps required for implementing a caching system for your application:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>Spring Boot-starter-cache</artifactId>
</dependency>
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class CacheConfig {
// Additional configuration if needed
}
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("items");
}
}
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class ItemService {
@Cacheable("items")
public Item getItemById(Long id) {
// Method implementation
}
}
Here’s an example for using EhCache:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>Spring Boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
And in your configuration class:
import org.springframework.cache.CacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
@Configuration
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
net.sf.ehcache.CacheManager cacheManager = new net.sf.ehcache.CacheManager(new ClassPathResource("ehcache.xml").getInputStream());
return new EhCacheCacheManager(cacheManager);
}
}
Maintaining and updating the database schema for your application requires database migration. There are various techniques in Spring Boot that you may apply to efficiently manage database migrations.
Let's see some of the most popular ones:
Steps to use Flyway:
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
Steps to use Liquibase:
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
Steps to use Manual SQL Scripts:
Steps to use JPA Schema Generation:
Choosing the Right Strategy:
Below are the steps on how you deploy a Spring Boot application across various cloud platforms:
Deploying to AWS
Install Java using the command:
sudo yum install java-17-openjdk
mvn clean package
scp -i your-key.pem target/your-application.jar ec2-user@your-ec2-ip:/home/ec2-user/
java -jar your-application.jar
Deploying to Azure
az webapp deploy --resource-group yourResourceGroup --name yourAppName --src-path target/your-application.jar
Deploying to Google Cloud
gcloud init
runtime: java17
entrypoint: java -jar your-application.jar
gcloud app deploy
General Tips:
Spring Boot Admin, as the name says, is an Admin tool that is primarily responsible for managing and keeping an eye on Spring Boot applications.
Let's look at the steps for setting up Spring Boot Admin:
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>Spring Boot-admin-starter-server</artifactId>
<version>3.1.5</version>
</dependency>
@SpringBootApplication
@EnableAdminServer
public class SpringBootAdminServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootAdminServerApplication.class, args);
}
}
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>Spring Boot-admin-starter-client</artifactId>
<version>3.1.5</version>
</dependency>
spring.boot.admin.client.url=http://localhost:8080
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>Spring Boot-admin-server-ui</artifactId>
<version>1.5.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>Spring Boot-starter-security</artifactId>
<version>3.1.5</version>
</dependency>
Once your Spring Boot application is live, you need a couple of tools to support post-production monitoring and issues.
This can be done via a myriad of approaches, one of them being:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>Spring Boot-starter-actuator</artifactId>
</dependency>
management.endpoints.web.exposure.include=health,info,metrics
management.endpoint.health.show-details=always
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
management.metrics.export.prometheus.enabled=true
management.endpoints.web.exposure.include=prometheus
There are various alternatives available to you in Spring Boot for logging, each having advantages of its own.
The primary logging systems that you can utilize are listed below:
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>Spring Boot-starter-log4j2</artifactId>
</dependency>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
handlers= java.util.logging.ConsoleHandler
.level= INFO
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Employee {
String Name;
private static final Logger logger = LoggerFactory.getLogger(MyClass.class);
public String getEmployeeName() {
logger.info("Sending Employee Name");
return this.name;
}
}
Example:
logging.level.org.springframework=DEBUG
logging.level.com.yourpackage=TRACE
Let's check out the steps that would be required for troubleshooting issues:
logging.level.org.springframework=DEBUG
logging.level.com.yourpackage=TRACE
IntelliJ IDEA:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>Spring Boot-starter-actuator</artifactId>
</dependency>
management.endpoints.web.exposure.include=health,info,metrics
management.endpoint.health.show-details=always
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>Spring Boot-devtools</artifactId>
<optional>true</optional>
</dependency>
Spring Boot has indeed been a game-changing technology, making the development of robust Java applications seamless. This set of Spring Boot interview questions covers both basic and advanced concepts, helping me gain a deeper understanding of its capabilities. From effortless autoconfiguration to the convenience of embedded servers, Spring Boot empowers developers to build efficient and scalable solutions with minimal setup overhead.
Answering these questions has reinforced my knowledge and highlighted areas for improvement. This framework strikes the perfect balance between simplicity and flexibility, making it indispensable for modern application development. The learning experience has been both insightful and rewarding, leaving me better equipped to leverage Spring Boot in real-world projects.
Note : We have compiled all Spring Boot Interview Questions for you in a template format. Check it out now!
Did you find this page helpful?