Spring Boot Interview Questions
Spring Boot Interview Questions
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:
Example:
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}}
Example:
If spring-boot-starter-web is present, 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
Example:
@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 */ }
Example:
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return new User(id, "John Doe", "john@example.com");
}
}
Spring Boot Actuator provides production-ready features like monitoring and health checks.
Features:
To enable Actuator:
management.endpoints.web.exposure.include=*
Example:
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
}
}
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleUserNotFound(UserNotFoundException
ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
@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)?
<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>
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
@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.
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
@Component
public class MyService { }
Spring Boot uses SLF4J with Logback as the default logging framework.
logging.level.root=INFO
logging.level.com.myapp=DEBUG
<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>
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.
# 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
spring.profiles.active=dev
Or set via command-line:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
@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();
}
}
17. What is Spring Boot’s embedded server, and how does it work?
Spring Boot comes with embedded servers like Tomcat, Jetty, Undertow.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class MyApplication { }
Example microservice:
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return new User(id, "John Doe");
}
}
Spring Boot uses Spring’s Dependency Injection (DI) to manage object dependencies.
@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+).
@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"));
}
}
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?
{
"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());
}
}
Steps:
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?
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);
}
}
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:
Logging Levels:
logging.level.root=INFO
logging.level.com.myapp=DEBUG
30. How do you configure Spring Boot to send an email (e.g., using
JavaMailSender)?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-email@gmail.com
spring.mail.password=your-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
@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);
}
}