Spring Boot Interview Questions by Dheeraj Batane
1. What is Spring Boot, and how does it differ from the traditional Spring
Framework?
Spring Boot is an extension of the Spring Framework that simplifies the development of
stand-alone, production-ready applications with minimal configuration.
Differences:
Feature Spring Framework Spring Boot
Configuration Requires manual XML or Uses auto-configuration and
Java-based configuration convention over configuration
Dependency Management Requires adding Comes with pre-configured
dependencies manually dependencies via
spring-boot-starter
modules
Embedded Server Requires external web server Comes with an embedded
setup (Tomcat, Jetty) server (Tomcat, Jetty,
Undertow)
Microservices Support Not specifically designed for Designed for microservices
microservices architecture
Deployment Requires deploying WAR files Can create standalone JARs
in an external server with embedded servers
2. What is the purpose of @SpringBootApplication annotation?
@SpringBootApplication is a convenience annotation that combines three key annotations:
● @Configuration - Marks the class as a source of bean definitions.
● @EnableAutoConfiguration - Enables Spring Boot’s auto-configuration mechanism.
● @ComponentScan - Scans for components (beans, controllers, services) in the
package.
Example:
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}}
Purpose: It simplifies Spring Boot application setup by enabling auto-configuration and
component scanning.
3. Explain the concept of auto-configuration in Spring Boot.
Auto-configuration in Spring Boot automatically configures application settings based on the
dependencies present in the classpath.
● It eliminates the need for manual configuration.
● Uses @EnableAutoConfiguration (included in @SpringBootApplication).
● Reads META-INF/spring.factories for predefined configurations.
Example:
If spring-boot-starter-web is present, Spring Boot:
● Automatically configures an embedded Tomcat server.
● Registers DispatcherServlet, Jackson, etc.
● Configures default error handling.
4. What is the role of application.properties or application.yml in
Spring Boot?
These files are used for configuring application settings such as database connection, logging,
and server properties.
Example (application.properties)
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root
Example (application.yml)
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: root
● application.properties is key-value based, whereas application.yml is
hierarchical and more readable.
5. What are the advantages of Spring Boot over traditional Spring
applications?
1. Auto-configuration – Reduces boilerplate code.
2. Embedded server – No need to deploy on external servers.
3. Microservices-friendly – Simplifies REST API development.
4. Production-ready – Includes monitoring (Spring Boot Actuator).
5. Starter dependencies – Reduces dependency conflicts.
6. Spring Initializr – Simplifies project setup.
6. What is the difference between @Component, @Service, @Repository,
and @Controller in Spring Boot?
Example:
Annotation Purpose Used For
Generic Spring-managed
@Component bean Any Spring bean
@Service Business logic layer Service classes
@Repository Data access layer DAO/Repository classes
@Controller Handles HTTP requests MVC controllers
Combines @Controller and
@RestController @ResponseBody REST APIs
@Service
public class MyService { /* Business logic */ }
@Repository
public interface MyRepository extends JpaRepository<User, Long> { }
@Controller
public class MyController { /* Returns HTML views */ }
@RestController
public class MyRestController { /* Returns JSON responses */ }
7. How do you create a Spring Boot RESTful web service?
1. Add spring-boot-starter-web dependency.
2. Use @RestController and @RequestMapping.
3. Return JSON responses using @GetMapping, @PostMapping, etc.
Example:
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return new User(id, "John Doe", "[email protected]");
}
}
8. What is Spring Boot Actuator, and what are its uses?
Spring Boot Actuator provides production-ready features like monitoring and health checks.
Features:
● /actuator/health - Check application health.
● /actuator/info - Display application metadata.
● /actuator/metrics - Show runtime metrics.
To enable Actuator:
management.endpoints.web.exposure.include=*
9. What is the significance of @RestController and how is it different
from @Controller?
Example:
Feature @Controller @RestController
Handles REST API
Purpose Handles web requests requests
Return Type View (JSP, Thymeleaf) JSON or XML
Requires
@ResponseBody Yes No
@Controller
public class WebController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello World");
return "hello"; // Returns a view name
}
}
@RestController
public class ApiController {
@GetMapping("/api/hello")
public String hello() {
return "Hello, JSON"; // Returns JSON response
}
}
10. How do you handle exceptions in Spring Boot applications?
Method 1: Using @ExceptionHandler
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleUserNotFound(UserNotFoundException
ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
Method 2: Using @ControllerAdvice
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(Exception.class)
public String handleException(Model model, Exception ex) {
model.addAttribute("error", ex.getMessage());
return "error-page";
}
}
11. What is Spring Boot DevTools, and what benefits does it provide during
development?
Spring Boot DevTools is a module that enhances the development experience by enabling
automatic application restarts, live reloads, and other useful features.
Benefits:
1. Automatic Restart – Detects code changes and restarts the application.
2. Live Reload – Refreshes web pages automatically (requires a browser plugin).
3. Property Defaults – Disables template caching for Thymeleaf, Freemarker, etc.
4. Remote Debugging – Supports remote development using
spring.devtools.remote.secret.
To enable DevTools:
Add the dependency in pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
12. How do you use Spring Boot to connect to a database (e.g., MySQL or
PostgreSQL)?
1. Add the JDBC dependency:
<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>
2. Configure the database in application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
3. Create an Entity and Repository:
@Entity
public class User {
@Id @GeneratedValue
private Long id;
private String name;
private String email;
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> { }
13. Explain the difference between @Bean and @Component in Spring Boot.
Feature @Bean @Component
Used in Java configuration Used in component-scanned
Use Case classes classes
Defined In @Configuration classes Regular Java classes
Automatically managed by
Lifecycle Control Full lifecycle control Spring
Example Manually defined in a method Annotated on a class
Example: Using @Bean
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
Example: Using @Component
@Component
public class MyService { }
14. How do you configure logging in Spring Boot?
Spring Boot uses SLF4J with Logback as the default logging framework.
1. Set log levels in application.properties:
logging.level.root=INFO
logging.level.com.myapp=DEBUG
2. Custom logback.xml:
<configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>app.log</file>
<encoder><pattern>%d [%thread] %-5level %logger{36} -
%msg%n</pattern></encoder>
</appender>
<root level="info"><appender-ref ref="FILE"/></root>
</configuration>
3. Use logging in Java code:
private static final Logger logger =
LoggerFactory.getLogger(MyService.class);
logger.info("Application started successfully");
15. What are Spring Boot profiles, and how do you manage them for
different environments (dev, prod)?
Spring Boot profiles allow different configurations for different environments like development,
testing, and production.
1. Define environment-specific application-{profile}.properties:
○ application-dev.properties
○ application-prod.properties
2. Example configuration:
# application-dev.properties
spring.datasource.url=jdbc:mysql://localhost:3306/devdb
logging.level.root=DEBUG
# application-prod.properties
spring.datasource.url=jdbc:mysql://prod-db-host:3306/proddb
logging.level.root=ERROR
3. Activate profile in application.properties:
spring.profiles.active=dev
Or set via command-line:
java -jar myapp.jar --spring.profiles.active=prod
16. How do you implement security in a Spring Boot application?
1. Add the dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2. Create a Security Configuration:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http)
throws Exception {
http
.authorizeHttpRequests(auth ->
auth.anyRequest().authenticated())
.formLogin(Customizer.withDefaults());
return http.build();
}
}
3. Default username: user, password printed in console.
17. What is Spring Boot’s embedded server, and how does it work?
Spring Boot comes with embedded servers like Tomcat, Jetty, Undertow.
● The default is Tomcat (spring-boot-starter-web).
● Runs inside the application, no need to deploy WAR files.
● Change the server in pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
18. What is the use of @EnableAutoConfiguration in Spring Boot?
● Enables automatic configuration based on classpath dependencies.
● Internally part of @SpringBootApplication.
● Uses spring.factories to load configurations.
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class MyApplication { }
19. What is the difference between application.properties and
application.yml files?
Feature application.properties application.yml
Format Key-value pairs Hierarchical YAML
Readability Less readable More readable
server:\n port:
Example server.port=8081 8081
YAML is preferred for complex configurations.
20. What is Spring Boot's support for creating microservices?
Spring Boot simplifies microservices development with:
1. Spring Cloud – Provides tools for cloud-native apps.
2. Spring Boot Actuator – Adds monitoring endpoints.
3. Spring Config Server – Centralized configuration management.
4. Spring Cloud Eureka – Service discovery.
5. Spring Cloud Gateway – API gateway for microservices.
Example microservice:
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return new User(id, "John Doe");
}
}
21. How does Spring Boot handle dependency injection?
Spring Boot uses Spring’s Dependency Injection (DI) to manage object dependencies.
● Types of Dependency Injection:
1. Constructor Injection (Recommended)
2. Setter Injection
3. Field Injection (Not Recommended)
Example of Constructor Injection:
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
● Spring Boot automatically injects dependencies using @Autowired (though it’s optional
for constructors in Spring Boot 2+).
22. How do you test a Spring Boot application using @SpringBootTest?
● @SpringBootTest loads the entire application context for integration testing.
Example of Testing a REST API:
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testGetUser() throws Exception {
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John Doe"));
}
}
● For Unit Testing, use @MockBean to mock dependencies.
23. Explain the difference between @RequestMapping, @GetMapping,
@PostMapping, and other HTTP method annotations.
Annotation HTTP Method Usage
@RequestMapping Any (GET, POST, etc.) Generic mapping
@GetMapping GET Fetch data
@PostMapping POST Create a resource
@PutMapping PUT Update a resource
@DeleteMapping DELETE Delete a resource
Example:
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) { return new User(id, "John
Doe"); }
@PostMapping("/")
public User createUser(@RequestBody User user) { return user; }
}
24. What are Spring Boot’s default error handling mechanisms, and how
can they be customized?
● Spring Boot provides default error handling using BasicErrorController.
● Returns JSON responses like:
{
"timestamp": "2024-02-11T12:00:00.123+00:00",
"status": 404,
"error": "Not Found",
"message": "User not found",
"path": "/users/99"
}
Custom Error Handling using @ControllerAdvice:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleUserNotFound(UserNotFoundException
ex) {
return
ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
}
25. How do you perform batch processing in Spring Boot?
● Use Spring Batch for processing large volumes of data.
Steps:
1. Add Spring Batch dependency.
2. Create a Job configuration.
3. Define ItemReader, ItemProcessor, and ItemWriter.
Example:
@Configuration
@EnableBatchProcessing
public class BatchConfig {
@Bean
public Job processJob(JobBuilderFactory jobBuilderFactory, Step step) {
return jobBuilderFactory.get("processJob")
.incrementer(new RunIdIncrementer())
.start(step)
.build();
}
@Bean
public Step step(StepBuilderFactory stepBuilderFactory,
ItemReader<String> reader,
ItemProcessor<String, String> processor,
ItemWriter<String> writer) {
return stepBuilderFactory.get("step")
.<String, String>chunk(10)
.reader(reader)
.processor(processor)
.writer(writer)
.build();
}
}
26. What is Spring Data JPA, and how is it used in Spring Boot?
● Spring Data JPA simplifies database interactions by reducing boilerplate code.
Example:
Define an Entity:
@Entity
public class User {
@Id @GeneratedValue
private Long id;
private String name;
}
Create a Repository:
@Repository
public interface UserRepository extends JpaRepository<User, Long> { }
Use the Repository in a Service:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User createUser(User user) {
return userRepository.save(user);
}
}
27. How do you manage transaction handling in Spring Boot applications?
● Use @Transactional for atomicity.
● By default, Spring Boot uses JPA transaction management.
Example:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional
public void updateUser(Long id, String newName) {
User user = userRepository.findById(id).orElseThrow();
user.setName(newName);
}
}
28. What are the different ways to run a Spring Boot application?
Using Maven or Gradle:
1. Using IDE (Eclipse, IntelliJ) – Run the main() method.
2. Deploying to an external Tomcat server (WAR packaging).
29. Explain the Spring Boot logging mechanism with default loggers (e.g.,
Logback).
● Spring Boot uses SLF4J with Logback by default.
Logging Levels:
● TRACE, DEBUG, INFO, WARN, ERROR
Configuring logging in application.properties:
logging.level.root=INFO
logging.level.com.myapp=DEBUG
Using logs in Java:
private static final Logger logger =
LoggerFactory.getLogger(MyService.class);
logger.info("Application started");
30. How do you configure Spring Boot to send an email (e.g., using
JavaMailSender)?
1. Add JavaMail dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2. Configure application.properties:
spring.mail.host=smtp.gmail.com
spring.mail.port=587
[email protected]
spring.mail.password=your-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
3. Create an Email Service:
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
public void sendEmail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
}
}