Spring Boot Interview Questions
Master your Spring Boot interviews with frequently asked questions covering basics, OOP, data structures, Spring Boot, and real coding scenarios for freshers and experienced professionals.
Interview Questions for Freshers
1. What is Spring Boot?
Spring Boot is an open-source Java framework developed on top of the Spring Framework. It is used for simplifying the development of production-level applications. Spring Boot features auto-configuration, embedded servers (such as Tomcat), and starter dependencies.
Spring Boot allows developers to build standalone, scalable, and microservice-based applications. It removes the need for complex XML configurations and enables applications to be run using a main method.
In short, Spring Boot makes it easier and faster to build, configure, and deploy Spring-based Java applications.
2. What are the features of Spring Boot?
Spring Boot provides several powerful features that simplify Java application development and deployment.
Auto-Configuration: Automatically configures Spring application based on project dependencies.
Starter Dependencies: Provides pre-configured dependency sets like spring-boot-starter-web.
Embedded Servers: Includes embedded Tomcat, Jetty, or Undertow, so no external server setup is required.
Production-Ready Features: Provides monitoring and management through Actuator.
Minimal Configuration: Reduces XML configuration and promotes annotation-based setup.
3. What are the key components of Spring Boot?
Spring Boot consists of several core components that simplify development and configuration of Spring-based applications.
Spring Boot Starters: Predefined dependency descriptors that simplify Maven/Gradle configuration (e.g., spring-boot-starter-web, spring-boot-starter-data-jpa).
Auto-Configuration: Automatically configures beans based on classpath dependencies.
Spring Boot Actuator: Provides production-ready features like health checks, metrics, and monitoring.
Embedded Servers: Built-in servers such as Tomcat, Jetty, or Undertow.
Spring Boot CLI: Command-line tool to quickly create and run Spring applications.
4. Why do we prefer Spring Boot over the core Spring framework?
Spring Boot is preferred over the core Spring framework because it reduces configuration complexity and speeds up application development. While core Spring requires extensive XML configuration and manual setup, Spring Boot provides auto-configuration and starter dependencies.
It includes embedded servers (like Tomcat), eliminates boilerplate code, and allows applications to run as standalone JAR files. Spring Boot also provides production-ready features such as monitoring and health checks through Actuator.
In short, Spring Boot simplifies development, reduces setup time, and makes it easier to build and deploy modern Java applications compared to the core Spring framework.
5. What does the @SpringBootApplication annotation do internally?
The @SpringBootApplication annotation is a convenience annotation that combines three important Spring annotations to simplify configuration and startup of a Spring Boot application.
@Configuration: Marks the class as a source of bean definitions for the Spring context.
@EnableAutoConfiguration: Enables Spring Boot’s auto-configuration mechanism based on dependencies.
@ComponentScan: Scans the package and its sub-packages for Spring components like @Controller, @Service, and @Repository.
In summary, @SpringBootApplication bundles configuration, auto-configuration, and component scanning into a single annotation, making Spring Boot applications easier to set up and run.
6. What is Spring Initializr and how is it used?
Spring Initializr is a web-based tool that helps developers quickly generate a Spring Boot project with predefined configurations. It allows you to select project metadata such as project type (Maven or Gradle), Java version, Spring Boot version, and required dependencies.
To use it, you visit start.spring.io or access it through IDEs like IntelliJ or Eclipse, choose the required dependencies (e.g., Spring Web, Spring Data JPA), and download the generated project as a ZIP file. The project includes a ready-to-run structure with starter dependencies and configuration files.
In short, Spring Initializr simplifies project setup and reduces manual configuration when starting a new Spring Boot application.
7. What are Spring Boot starters (starter dependencies) and why are they used?
Spring Boot starters are pre-configured dependency packages that simplify Maven or Gradle configuration by bundling commonly used libraries together. Instead of adding multiple individual dependencies manually, you include a single starter dependency.
They are used to reduce boilerplate configuration, ensure compatibility between libraries, and speed up development. For example, spring-boot-starter-web includes Spring MVC, embedded Tomcat, and related dependencies needed to build web applications.
In short, Spring Boot starters make dependency management easier, cleaner, and more efficient.
8. What is the default port of the embedded Tomcat server in Spring Boot?
The default port of the embedded Tomcat server in Spring Boot is 8080.
You can change the default port by setting the server.port property in the application.properties or application.yml file.
1server.port=9090
29. How can you change the default port of the embedded server?
You can change the default port of the embedded server in Spring Boot by configuring the server.port property.
There are multiple ways to change the port:
Using application.properties file:
1server.port=9090
2Using application.yml file:
1server:
2 port: 9090
3You can also override the port using command-line arguments like --server.port=9090 when running the application.
10. How can you disable the default web server in a Spring Boot application?
You can disable the default embedded web server (such as Tomcat) in a Spring Boot application by changing the application type or excluding the web starter dependency.
Set the application type to NONE in application.properties:
1spring.main.web-application-type=none
2Alternatively, remove or exclude spring-boot-starter-web from your dependencies if you are building a non-web application.
This is commonly done for console applications, batch processing jobs, or microservices that do not require an HTTP server.
11. How do you disable a specific auto-configuration class in Spring Boot?
You can disable a specific auto-configuration class in Spring Boot using the exclude attribute of the @SpringBootApplication annotation or by configuring properties.
Method 1: Using @SpringBootApplication with exclude:
1@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
2public class DemoApplication {
3 public static void main(String[] args) {
4 SpringApplication.run(DemoApplication.class, args);
5 }
6}
7Method 2: Using application.properties:
1spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
2This is useful when you want to prevent Spring Boot from automatically configuring certain components, such as database configuration, when they are not needed.
12. What is the Spring Boot CLI and what are some commonly used CLI commands?
The Spring Boot CLI (Command Line Interface) is a tool that allows developers to quickly create, run, and test Spring Boot applications using Groovy scripts without requiring a full project setup.
It simplifies development by automatically handling dependency resolution and application configuration.
Commonly used CLI commands:
spring run app.groovy – Runs a Spring Boot Groovy application.
spring init – Generates a new Spring Boot project.
spring version – Displays the installed Spring Boot CLI version.
In short, the Spring Boot CLI helps developers rapidly prototype and execute Spring Boot applications from the command line.
13. How do you create a non-web application with Spring Boot?
Yes, you can create a non-web (console or batch) application using Spring Boot. Spring Boot supports standalone applications without starting an embedded web server.
To create a non-web application, you can remove the spring-boot-starter-web dependency and set the application type to NONE.
1spring.main.web-application-type=none
2You can then implement CommandLineRunner or ApplicationRunner to execute logic when the application starts.
1@SpringBootApplication
2public class DemoApplication implements CommandLineRunner {
3
4 public static void main(String[] args) {
5 SpringApplication.run(DemoApplication.class, args);
6 }
7
8 @Override
9 public void run(String... args) {
10 System.out.println("Console application running...");
11 }
12}
13This approach is commonly used for batch processing, scheduled jobs, or command-line tools.
14. What is Spring Initializr ?
Spring Initializr is a web-based tool and service that helps developers quickly bootstrap a Spring Boot project with minimal configuration. It generates a ready-to-use project structure with selected dependencies and build configuration.
It allows users to choose project metadata such as group ID, artifact ID, packaging type (JAR or WAR), Java version, and required dependencies. The generated project can be downloaded as a ZIP file or imported directly into IDEs like IntelliJ IDEA or Eclipse.
In short, Spring Initializr simplifies project setup by automatically generating a structured Spring Boot application with preconfigured dependencies.
15. How do you disable specific auto-configuration using @EnableAutoConfiguration?
You can disable specific auto-configuration classes in Spring Boot using the exclude attribute of the @EnableAutoConfiguration annotation.
This allows you to prevent certain configurations from being automatically applied when they are not needed.
1@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
2public class DemoApplication {
3 public static void main(String[] args) {
4 SpringApplication.run(DemoApplication.class, args);
5 }
6}
7This approach is commonly used when, for example, you do not want Spring Boot to auto-configure a DataSource or other infrastructure components.
16. How do you use @ConditionalOnMissingBean to make auto-configuration back off when a bean exists ?
@ConditionalOnMissingBean is used in Spring Boot auto-configuration classes to create a bean only if a specific bean is not already defined in the application context.
This ensures that auto-configuration “backs off” when the developer provides a custom bean implementation, allowing user-defined beans to override default configurations.
1@Configuration
2public class MyAutoConfiguration {
3
4 @Bean
5 @ConditionalOnMissingBean
6 public MyService myService() {
7 return new DefaultMyService();
8 }
9}
10If the application already defines a MyService bean, Spring Boot will skip creating the default one. This makes auto-configuration flexible and customizable.
17. How do you package Spring Boot web applications as JAR and WAR files ?
Spring Boot applications can be packaged as executable JAR files or traditional WAR files depending on deployment needs.
Packaging as JAR (default): Spring Boot packages applications as executable JARs with an embedded server (Tomcat/Jetty). This is ideal for standalone deployment.
1<packaging>jar</packaging>
2
3<build>
4 <plugins>
5 <plugin>
6 <groupId>org.springframework.boot</groupId>
7 <artifactId>spring-boot-maven-plugin</artifactId>
8 </plugin>
9 </plugins>
10</build>
11Packaging as WAR: Used when deploying to an external application server. You change packaging to WAR, mark the embedded server as provided, and extend SpringBootServletInitializer.
1<packaging>war</packaging>
2
3<dependency>
4 <groupId>org.springframework.boot</groupId>
5 <artifactId>spring-boot-starter-tomcat</artifactId>
6 <scope>provided</scope>
7</dependency>
81@SpringBootApplication
2public class DemoApplication extends SpringBootServletInitializer {
3
4 @Override
5 protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
6 return builder.sources(DemoApplication.class);
7 }
8
9 public static void main(String[] args) {
10 SpringApplication.run(DemoApplication.class, args);
11 }
12}
13In summary, JAR packaging is preferred for standalone microservices, while WAR packaging is used for deployment to external servlet containers.
18. What are the possible sources of external configuration in Spring Boot ?
Spring Boot supports multiple external configuration sources, allowing applications to be flexible and environment-specific without modifying code.
Application properties or YAML files (application.properties or application.yml).
Profile-specific configuration files (e.g., application-dev.properties).
Environment variables (e.g., SERVER_PORT=9090).
Command-line arguments (e.g., --server.port=9090).
Java system properties (-Dserver.port=9090).
Spring Boot follows a defined priority order for these configuration sources, allowing higher-precedence sources like command-line arguments to override default properties.
19. What does it mean that Spring Boot supports relaxed binding of properties ?
Relaxed binding in Spring Boot means that property names defined in configuration files can be mapped to Java bean fields using flexible naming conventions. Spring Boot automatically matches different naming styles to the same property.
For example, a property like server.port can be written in multiple formats such as server.port, server_port, SERVER_PORT, or serverPort, and Spring Boot will correctly bind it to a field named serverPort in a configuration class.
This feature improves flexibility and makes it easier to use environment variables, YAML, or properties files without strict naming rules.
20. What is Spring Boot DevTools used for?
Spring Boot DevTools is a development-time tool that enhances developer productivity by providing automatic restart, live reload, and other debugging features.
It automatically restarts the application when code changes are detected, reduces restart time using classloader optimizations, and supports LiveReload for automatic browser refresh when templates or static resources change.
In short, Spring Boot DevTools improves the development experience by enabling faster feedback and reducing manual restarts during application development.
21. Which is better for configuring a Spring Boot project — properties or YAML, and why?
Both application.properties and application.yml are fully supported in Spring Boot, and neither is technically superior — the choice depends on project preference and complexity.
Properties files are simpler and more familiar to many Java developers, making them easier to read for small configurations. YAML is more concise and better suited for hierarchical or complex configurations because it avoids repetitive keys and supports nested structures naturally.
In short, use properties for simple setups and YAML for cleaner representation of complex, structured configurations.
23. What basic annotations does Spring Boot provide?
Spring Boot provides several core annotations that simplify configuration and reduce boilerplate code.
@SpringBootApplication is the main annotation that combines configuration, auto-configuration, and component scanning.
Other commonly used annotations include EnableAutoConfiguration, ComponentScan, and Configuration for managing application setup and beans.
1@SpringBootApplication
2public class Application {
3 public static void main(String[] args) {
4 SpringApplication.run(Application.class, args);
5 }
6}24. How do you change the default port in Spring Boot? (multiple ways)
The default port in Spring Boot is 8080, but it can be changed using multiple approaches depending on the configuration method used.
One common way is by setting the property server.port in the application.properties file.
1server.port=9090It can also be configured in the application.yml file.
1server:
2 port: 9090Another way is by passing it as a command-line argument while running the application.
1java -jar app.jar --server.port=9090You can also set it programmatically using SpringApplication in the main class.
1SpringApplication app = new SpringApplication(Application.class);
2app.setDefaultProperties(Collections.singletonMap("server.port", "9090"));
3app.run(args);25. Which embedded servers does Spring Boot support, and how do you change the default?
Spring Boot supports multiple embedded servers that allow applications to run independently without deploying to an external server.
The most commonly supported embedded servers are Tomcat, Jetty, and Undertow. By default, Spring Boot uses Tomcat.
To change the default server, you need to exclude Tomcat from the dependency and include another server like Jetty or Undertow.
1<dependency>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-starter-web</artifactId>
4 <exclusions>
5 <exclusion>
6 <groupId>org.springframework.boot</groupId>
7 <artifactId>spring-boot-starter-tomcat</artifactId>
8 </exclusion>
9 </exclusions>
10</dependency>1<dependency>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-starter-jetty</artifactId>
4</dependency>Similarly, you can include Undertow by adding its starter dependency after excluding Tomcat.
Interview Questions for Experienced
1. What is Spring Boot dependency management and how do starters and the parent POM help?
Spring Boot dependency management refers to how Spring Boot automatically manages versions of libraries and dependencies required in a project, reducing the need for manual configuration.
The Spring Boot parent POM (spring-boot-starter-parent) provides a dependency management section that defines compatible versions of common libraries. This ensures all dependencies work together without version conflicts.
Starters are pre-configured dependency bundles (e.g., spring-boot-starter-web) that include all required libraries for a specific functionality, eliminating the need to add multiple dependencies manually.
Example (Parent POM):
1<parent>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-starter-parent</artifactId>
4 <version>3.x.x</version>
5</parent>
6Example (Using Starter Dependency):
1<dependency>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-starter-web</artifactId>
4</dependency>
5This single starter automatically includes dependencies like Spring MVC, Jackson (for JSON), and embedded Tomcat without explicitly adding them.
In short, the parent POM ensures consistent dependency versions, while starters simplify dependency inclusion and reduce configuration effort.
2. What does the @RestController annotation do in Spring Boot?
The @RestController annotation in Spring Boot is used to create RESTful web services. It combines @Controller and @ResponseBody, meaning that methods return data directly as JSON or XML instead of rendering a view.
When a request is handled, the return value is automatically converted into an HTTP response using message converters like Jackson.
Example:
1@RestController
2public class HelloController {
3
4 @GetMapping("/hello")
5 public String hello() {
6 return "Hello World";
7 }
8}
9In short, @RestController simplifies API development by returning data directly instead of view templates.
3. What is the difference between @Controller and @RestController?
Both @Controller and @RestController are used to handle HTTP requests in Spring Boot, but they differ in how responses are returned.
@Controller: Used for traditional web applications. It returns view names (like JSP/HTML pages). To return data, you must explicitly use @ResponseBody.
@RestController: Used for REST APIs. It automatically returns data (JSON/XML) and internally includes @ResponseBody.
Example:
1@Controller
2public class WebController {
3 @GetMapping("/home")
4 public String home() {
5 return "home"; // returns view name
6 }
7}
8
9@RestController
10public class ApiController {
11 @GetMapping("/api")
12 public String api() {
13 return "data"; // returns JSON/text
14 }
15}
16In short, @Controller is used for view-based MVC applications, while @RestController is used for REST APIs returning data directly.
4. What is the difference between @RequestMapping and @GetMapping annotations?
Both @RequestMapping and @GetMapping are used to map HTTP requests to handler methods in Spring Boot, but they differ in specificity.
@RequestMapping: A general-purpose annotation that can handle all HTTP methods (GET, POST, PUT, DELETE, etc.). You must specify the method explicitly using method = RequestMethod.GET.
@GetMapping: A specialized shortcut annotation for handling only HTTP GET requests. It is equivalent to @RequestMapping(method = RequestMethod.GET).
Example:
1@RequestMapping(value = "/home", method = RequestMethod.GET)
2public String home() {
3 return "home";
4}
5
6@GetMapping("/home")
7public String home2() {
8 return "home";
9}
10In short, @RequestMapping is more flexible and generic, while @GetMapping is simpler and specifically designed for GET requests.
5. What are Spring Profiles, and how do you use @Profile to activate different configurations?
Spring Profiles allow you to define different configurations for different environments such as development, testing, and production. They help manage environment-specific settings without changing the code.
The @Profile annotation is used to mark beans or configuration classes so they are only loaded when a specific profile is active.
Example:
1@Configuration
2@Profile("dev")
3public class DevConfig {
4 // Development-specific beans
5}
6
7@Configuration
8@Profile("prod")
9public class ProdConfig {
10 // Production-specific beans
11}
12You can activate a profile using properties, environment variables, or command-line arguments:
1spring.profiles.active=dev
2In short, Spring Profiles help manage environment-specific configurations, and @Profile controls which beans are loaded based on the active environment.
6. What are the differences between WAR packaging and using an embedded container (JAR) in Spring Boot?
Spring Boot applications can be packaged either as JAR files with embedded servers or as WAR files for deployment on external servers. The choice depends on deployment requirements.
JAR (Embedded Container): Includes an embedded server like Tomcat or Jetty. It runs as a standalone application using java -jar and is commonly used in microservices.
WAR (External Container): Does not include an embedded server. It is deployed to an external servlet container like Tomcat or JBoss and requires additional configuration.
Example:
1<packaging>jar</packaging> <!-- Standalone -->
2
3<packaging>war</packaging> <!-- External server -->
4In short, JAR is preferred for standalone, cloud-native applications, while WAR is used when deploying to traditional external servers.
7. What is Spring Boot Actuator, and what is it used for?
Spring Boot Actuator is a module that provides production-ready features to monitor and manage a Spring Boot application.
It exposes various built-in endpoints that give insights into application health, metrics, environment properties, and more.
Common endpoints include /actuator/health (application health), /actuator/metrics (performance metrics), and /actuator/env (environment details).
Example (Dependency):
1<dependency>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-starter-actuator</artifactId>
4</dependency>
5In short, Spring Boot Actuator helps monitor, manage, and maintain applications in production environments.
8. How do you enable Actuator endpoints in a Spring Boot application?
To enable Actuator endpoints in a Spring Boot application, you need to add the Actuator dependency and configure which endpoints should be exposed.
Step 1: Add the spring-boot-starter-actuator dependency.
1<dependency>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-starter-actuator</artifactId>
4</dependency>
5Step 2: Configure endpoints in application.properties.
1management.endpoints.web.exposure.include=*
2By default, only a few endpoints are exposed. Using include=* exposes all endpoints, but in production, you should limit this for security reasons.
Once configured, endpoints like /actuator/health and /actuator/metrics become accessible.
9. How can you list all the beans in a Spring Boot application?
You can list all beans in a Spring Boot application by accessing the ApplicationContext and retrieving all bean names.
Method 1: Using ApplicationContext in code:
1@SpringBootApplication
2public class DemoApplication implements CommandLineRunner {
3
4 @Autowired
5 private ApplicationContext context;
6
7 public static void main(String[] args) {
8 SpringApplication.run(DemoApplication.class, args);
9 }
10
11 @Override
12 public void run(String... args) {
13 String[] beanNames = context.getBeanDefinitionNames();
14 Arrays.sort(beanNames);
15 for (String beanName : beanNames) {
16 System.out.println(beanName);
17 }
18 }
19}
20Method 2: Using Actuator endpoint:
1management.endpoints.web.exposure.include=beans
2Then access /actuator/beans to view all registered beans.
10. How can you check environment properties in a Spring Boot app?
You can check environment properties in a Spring Boot application using the Environment interface or via Actuator endpoints.
Method 1: Using Environment in code:
1@Autowired
2private Environment env;
3
4public void printProperty() {
5 String port = env.getProperty("server.port");
6 System.out.println(port);
7}
8Method 2: Using Actuator endpoint:
1management.endpoints.web.exposure.include=env
2Then access /actuator/env to view all environment properties.
11. How do you enable debug-level logging in Spring Boot?
You can enable debug-level logging in Spring Boot using configuration files, command-line arguments, or properties.
Method 1: Using application.properties:
1logging.level.root=DEBUG
2Method 2: Using command-line argument:
1java -jar app.jar --debug
2Method 3: Using specific package-level logging:
1logging.level.com.example=DEBUG
2This helps in debugging by providing detailed logs about application behavior and configuration.
12. How do you write integration tests in Spring Boot?
Integration tests in Spring Boot are used to test the interaction between multiple components (controllers, services, repositories) together within the Spring context.
You typically use @SpringBootTest to load the full application context and @AutoConfigureMockMvc or TestRestTemplate to test endpoints.
Example:
1@SpringBootTest
2@AutoConfigureMockMvc
3public class UserControllerTest {
4
5 @Autowired
6 private MockMvc mockMvc;
7
8 @Test
9 public void testGetUsers() throws Exception {
10 mockMvc.perform(get("/users"))
11 .andExpect(status().isOk());
12 }
13}
14In short, integration testing in Spring Boot involves loading the application context and testing real interactions between components.
13. When would you use application.properties vs application.yml for configuration?
Both application.properties and application.yml are used for configuring Spring Boot applications, but they are preferred in different scenarios.
Use application.properties when configuration is simple and flat. It is easier to read for small projects and familiar to most Java developers.
Use application.yml when configuration is complex or hierarchical. YAML allows nesting, reducing repetition and improving readability for large configurations.
Example:
1server.port=8080
2spring.datasource.url=jdbc:mysql://localhost:3306/db
31server:
2 port: 8080
3spring:
4 datasource:
5 url: jdbc:mysql://localhost:3306/db
6In short, use application.properties for simple configurations and application.yml for cleaner and structured configurations in larger applications.
14. What is the default server port and how can it be changed in Spring Boot?
The default server port in Spring Boot is 8080.
You can change the port using different methods:
Using application.properties:
1server.port=9090
2Using application.yml:
1server:
2 port: 9090
3Using command-line argument:
1java -jar app.jar --server.port=9090
2Spring Boot also allows overriding using environment variables or Java system properties.
15. What is Dependency Injection in Spring, and what types does it support?
Dependency Injection (DI) in Spring is a design pattern where the Spring container automatically provides required dependencies (objects) to a class instead of the class creating them itself. This promotes loose coupling and easier testing.
Spring supports multiple types of dependency injection:
Constructor Injection: Dependencies are provided through the class constructor. It is the most recommended approach.
Setter Injection: Dependencies are set using setter methods.
Field Injection: Dependencies are injected directly into fields using annotations.
Example (Constructor Injection):
1@Service
2public class UserService {
3
4 private final UserRepository userRepository;
5
6 public UserService(UserRepository userRepository) {
7 this.userRepository = userRepository;
8 }
9}
10In short, Dependency Injection allows Spring to manage object creation and wiring, with constructor injection being the preferred method.
16. What is the difference between constructor injection and setter injection in Spring?
Both constructor injection and setter injection are ways to provide dependencies to a class in Spring, but they differ in how and when dependencies are assigned.
Constructor Injection: Dependencies are passed through the constructor at object creation time. It ensures required dependencies are always provided and makes the object immutable.
Setter Injection: Dependencies are provided through setter methods after object creation. It is useful for optional dependencies.
Example:
1// Constructor Injection
2@Service
3public class UserService {
4 private final UserRepository repo;
5
6 public UserService(UserRepository repo) {
7 this.repo = repo;
8 }
9}
10
11// Setter Injection
12@Service
13public class UserService2 {
14 private UserRepository repo;
15
16 @Autowired
17 public void setRepo(UserRepository repo) {
18 this.repo = repo;
19 }
20}
21In short, constructor injection is preferred for mandatory dependencies and better immutability, while setter injection is used for optional or changeable dependencies.
17. How can you exclude a specific auto-configuration when using @EnableAutoConfiguration or @SpringBootApplication?
You can exclude specific auto-configuration classes in Spring Boot using the exclude attribute in @EnableAutoConfiguration or @SpringBootApplication.
Method 1: Using @SpringBootApplication:
1@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
2public class DemoApplication {
3 public static void main(String[] args) {
4 SpringApplication.run(DemoApplication.class, args);
5 }
6}
7Method 2: Using @EnableAutoConfiguration:
1@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
2public class DemoApplication {
3}
4This is useful when you want to disable unwanted configurations like database setup when not required.
18. How do you register a custom auto-configuration in Spring Boot?
To register a custom auto-configuration in Spring Boot, you need to create a configuration class and register it so that Spring Boot can discover it automatically.
Step 1: Create a configuration class using @Configuration.
1@Configuration
2public class MyAutoConfiguration {
3
4 @Bean
5 public MyService myService() {
6 return new MyService();
7 }
8}
9Step 2: Register it in META-INF/spring.factories (for older versions) or META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports (Spring Boot 3+).
1org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
2com.example.MyAutoConfiguration
3Step 3: Optionally use conditions like @ConditionalOnClass or @ConditionalOnMissingBean to control when the configuration is applied.
In short, you create a configuration class, register it in Spring Boot’s auto-configuration mechanism, and optionally apply conditions to control its activation.
19. What is Spring Boot Actuator’s security model, and how do you expose sensitive endpoints safely?
Spring Boot Actuator’s security model is designed to protect sensitive endpoints (like health, metrics, and environment details) from unauthorized access while still allowing monitoring capabilities.
By default, only a limited set of endpoints (such as /actuator/health) are exposed, and others are disabled or secured.
To safely expose endpoints, you should:
Explicitly configure which endpoints are exposed using management.endpoints.web.exposure.include.
Use Spring Security to restrict access (authentication/authorization).
Avoid exposing sensitive endpoints like env or beans publicly.
Example:
1management.endpoints.web.exposure.include=health,info
2management.endpoint.health.show-details=when_authorized
3In short, Actuator endpoints should be carefully exposed and secured using configuration and authentication to prevent leaking sensitive application data.
20. How does Spring Boot integrate with containers and Kubernetes?
Spring Boot integrates seamlessly with containers and Kubernetes, making it ideal for cloud-native applications and microservices architectures.
With containers (like Docker), Spring Boot applications can be packaged as lightweight executable JAR files and run inside containers using simple Dockerfile configurations.
In Kubernetes, Spring Boot works well with features like service discovery, configuration management, and scaling. It supports readiness and liveness probes using Actuator endpoints such as /actuator/health.
Key integration features include externalized configuration (via environment variables and config maps), horizontal scaling, and seamless deployment in container orchestration environments.
Example (Dockerfile):
1FROM openjdk:17
2COPY target/app.jar app.jar
3ENTRYPOINT ["java","-jar","/app.jar"]
4In short, Spring Boot is designed for containerization and works naturally with Kubernetes for deployment, scaling, and management of modern applications.
Advance Spring Boot Interview Questions
1. How do you package and deploy a Spring Boot web application as an executable JAR or a WAR file (with embedded vs external container)?
Spring Boot applications can be packaged and deployed either as an executable JAR (with embedded server) or as a WAR file (for external servlet containers).
Executable JAR (Embedded Container):
Uses embedded servers like Tomcat, Jetty, or Undertow.
Configured with <packaging>jar</packaging>.
Run using java -jar app.jar.
1<packaging>jar</packaging>
2
3<dependency>
4 <groupId>org.springframework.boot</groupId>
5 <artifactId>spring-boot-starter-web</artifactId>
6</dependency>
7WAR (External Container):
Deployed to external servers like Tomcat or JBoss.
Configured with <packaging>war</packaging>.
Extend SpringBootServletInitializer.
1@SpringBootApplication
2public class DemoApplication extends SpringBootServletInitializer {
3
4 @Override
5 protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
6 return builder.sources(DemoApplication.class);
7 }
8}
9In short, JAR is used for standalone applications with embedded servers, while WAR is used when deploying to external application servers.
2. How do Spring Framework and Spring Boot differ?
The Spring Framework is a comprehensive framework for building Java applications, while Spring Boot is built on top of it to simplify development and reduce configuration.
Configuration: Spring requires manual configuration (XML/Java), whereas Spring Boot provides auto-configuration.
Setup Time: Spring takes more time to set up, while Spring Boot enables rapid development.
Server: Spring requires external servers, while Spring Boot includes embedded servers like Tomcat.
Dependency Management: Spring Boot uses starter dependencies to simplify dependency management.
In short, Spring Framework provides the core features, while Spring Boot simplifies and accelerates application development.
3. What does @SpringBootApplication include internally?
The @SpringBootApplication annotation is a convenience annotation that combines multiple important Spring annotations into one.
It internally includes:
@Configuration: Marks the class as a source of bean definitions.
@EnableAutoConfiguration: Enables automatic configuration based on dependencies.
@ComponentScan: Scans for Spring components like @Controller, @Service, and @Repository.
In short, @SpringBootApplication bundles configuration, auto-configuration, and component scanning into a single annotation for simplicity.
4. Explain the use of @RestController
The @RestController annotation in Spring Boot is used to build RESTful web services by handling HTTP requests and returning data directly in the response body.
It is a combination of @Controller and @ResponseBody, which means all methods automatically return JSON or XML instead of view templates.
It is mainly used for creating APIs where the response is data (e.g., JSON) rather than HTML pages.
Example:
1@RestController
2public class UserController {
3
4 @GetMapping("/users")
5 public List<String> getUsers() {
6 return List.of("Vishal", "Rahul");
7 }
8}
9In short, @RestController is used to create REST APIs that return data directly to the client.
5. Compare @Controller vs @RestController
Both @Controller and @RestController are used to handle web requests in Spring Boot, but they serve different purposes.
@Controller: Used for MVC applications. It returns view names (HTML/JSP). Requires @ResponseBody to return data.
@RestController: Used for REST APIs. It returns data (JSON/XML) directly and includes @ResponseBody by default.
Example:
1@Controller
2public class WebController {
3 @GetMapping("/home")
4 public String home() {
5 return "home"; // view name
6 }
7}
8
9@RestController
10public class ApiController {
11 @GetMapping("/api")
12 public String api() {
13 return "data"; // JSON/text response
14 }
15}
16In short, @Controller is for view-based applications, while @RestController is for REST APIs returning data directly.
6. Compare @RequestMapping vs @GetMapping.
Both @RequestMapping and @GetMapping are used to map HTTP requests to controller methods in Spring Boot, but they differ in flexibility and usage.
@RequestMapping: A generic annotation that can handle all HTTP methods (GET, POST, PUT, DELETE, etc.). Requires specifying method = RequestMethod.GET explicitly.
@GetMapping: A specialized shortcut for handling only HTTP GET requests. It is equivalent to @RequestMapping(method = RequestMethod.GET).
Example:
1@RequestMapping(value = "/home", method = RequestMethod.GET)
2public String home() {
3 return "home";
4}
5
6@GetMapping("/home")
7public String home2() {
8 return "home";
9}
10In short, @RequestMapping is more flexible and supports all HTTP methods, while @GetMapping is simpler and specifically designed for GET requests.
7. What is Spring Boot Actuator used for, and name some common endpoints?
Spring Boot Actuator is used to monitor, manage, and gather insights about a running Spring Boot application in production.
It provides built-in endpoints that expose information about application health, metrics, environment, and configuration.
Common Actuator endpoints include:
/actuator/health → Shows application health status.
/actuator/metrics → Displays application performance metrics.
/actuator/env → Shows environment properties.
/actuator/beans → Lists all Spring beans.
In short, Spring Boot Actuator helps in monitoring and managing applications using useful endpoints for diagnostics and health checks.
8. How is transaction management handled in Spring Boot?
Transaction management in Spring Boot is handled automatically using Spring’s declarative transaction management support, primarily through the @Transactional annotation.
When a method is annotated with @Transactional, Spring automatically starts a transaction before the method execution and commits it after successful completion. If an exception occurs, the transaction is rolled back.
Spring Boot auto-configures a transaction manager (like DataSourceTransactionManager or JpaTransactionManager) based on the dependencies present.
Example:
1@Service
2public class UserService {
3
4 @Transactional
5 public void createUser(User user) {
6 // database operations
7 }
8}
9In short, Spring Boot simplifies transaction management using @Transactional and automatic configuration of transaction managers.
9. What are some common memory leaks or performance issues in Spring Boot, and how do you diagnose them?
Spring Boot applications can face memory leaks and performance issues due to improper resource handling, inefficient queries, or misconfigurations.
Common issues include:
Memory leaks due to static collections or caches not being cleared.
Unclosed resources like database connections or streams.
N+1 query problems in ORM (e.g., Hibernate).
Excessive logging or large object creation.
You can diagnose these issues using:
Actuator endpoints like /actuator/metrics and /actuator/heapdump.
Profiling tools like VisualVM or JProfiler.
Logging and monitoring tools (e.g., Micrometer with Prometheus).
In short, performance issues arise from poor resource management or inefficient code, and they can be diagnosed using Actuator, profiling tools, and monitoring systems.
10. What is Spring Boot DevTools ?
Spring Boot DevTools is a development-time tool that improves developer productivity by enabling faster feedback during application development.
Key features include:
Automatic Restart: The application automatically restarts when code changes are detected. It uses two classloaders to speed up restart time.
LiveReload: Automatically refreshes the browser when static resources or templates are changed.
Disable Caching: Disables template caching (e.g., Thymeleaf, Freemarker) so changes are immediately visible.
Example (Dependency):
1<dependency>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-devtools</artifactId>
4</dependency>
5In short, Spring Boot DevTools enhances development by enabling automatic restart, live browser refresh, and disabling caching for faster iteration.
Related Articles
Next Js Interview Questions
Explore the most important Next.js interview questions including SSR, SSG, ISR, routing, performance optimization, and real-world implementation examples.
BackendPython Interview Questions
Master your Python interviews with frequently asked questions covering basics, OOP, data structures, Django, and real coding scenarios for freshers and experienced professionals.