Spring Boot Interview Questions and Answers

  1. Object Oriented Programming (OOPs) Interview Questions
  2. 50 Java Interview Questions + 30 Scenario Based Q&A
  3. Cracking the Code: 200 Interview Q&A for Software Developers
  4. Performance and Optimization Interview Questions
  5. Caching Interview Questions and Answers
  6. Error Handling and Debugging Interview Questions
  7. C Programming Language Interview Questions
  8. C++ Programming Interview Questions
  9. Spring Boot Interview Questions and Answers

Introduction

Spring Boot has become a go-to framework for developing robust, production-ready Java applications. Its simplicity, flexibility, and out-of-the-box features like embedded servers, easy configuration, and seamless integration with Spring make it ideal for modern web applications. In this article, we explore the most commonly asked Spring Boot interview questions, covering a wide range of topics such as validation, security, database migrations, messaging, and more, to help you prepare thoroughly for your next interview.

Interview Questions and Answers

1. What is Spring Boot?

Spring Boot is a framework that simplifies the development of Spring-based applications by providing default configurations, embedded servers, and auto-configuration to quickly get a Spring application running without manual configuration.

Spring Boot eliminates the need for extensive XML configurations and offers features like embedded Tomcat/Jetty servers, starter projects, Spring Initializer, and auto-configuration, making development and deployment much easier.

2. How does Spring Boot differ from Spring Framework?

Spring Boot builds on top of the Spring Framework, offering faster development, with reduced manual configurations and dependencies.

Spring Framework requires explicit configuration via XML or Java-based annotations. In contrast, Spring Boot offers auto-configuration, opinionated defaults, and starter dependencies to help you start developing right away without configuration overhead.

3. What is auto-configuration in Spring Boot?

Auto-configuration automatically configures your Spring application based on the libraries on the classpath, removing the need for developers to define beans manually.

Spring Boot inspects your classpath and environment variables and configures default settings. For example, if spring-webmvc is on the classpath, it automatically configures a DispatcherServlet.

4. What are Spring Boot Starters?

Starters are a set of convenient dependency descriptors in Maven or Gradle that you can include in your project.

Instead of listing each individual dependency, you can use starters like spring-boot-starter-web, which includes all the necessary dependencies to build a web application, like Spring MVC, Jackson, and Tomcat.

5. What is the Spring Boot Actuator?

Spring Boot Actuator provides production-ready features like monitoring, metrics, health checks, and auditing.

With endpoints like /actuator/health, /actuator/metrics, etc., you can monitor the application’s performance and health. Actuator also integrates with external monitoring tools.

6. What is the purpose of Spring Boot DevTools?

Spring Boot DevTools provides development-time features like hot-swapping, automatic restarts, and configurations to speed up development.

It helps developers by enabling automatic application restarts whenever files change, live reload of static resources, and easier debugging in development environments.

7. How does Spring Boot handle application properties?

Spring Boot reads configuration from properties or YAML files to configure various aspects of the application.

For instance, the application.properties file can be used to configure the port, logging levels, data sources, etc. Spring Boot will automatically pick up these configurations.

server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/mydb

8. How can you create a Spring Boot REST API?

You can create a REST API by using the @RestController and @RequestMapping annotations.

A simple REST controller might look like this:


@RestController
@RequestMapping("/api")
public class UserController {
  
  @GetMapping("/users")
  public List getUsers() {
    return userService.getAllUsers();
  }
}

This exposes a /api/users endpoint to return a list of users.

9. What is an embedded server in Spring Boot?

Spring Boot provides embedded servers like Tomcat, Jetty, or Undertow, allowing you to run web applications without deploying them in an external server.

Instead of packaging your application as a WAR and deploying it in a servlet container, Spring Boot allows packaging it as a JAR with an embedded server.

10. What is the difference between @Controller and @RestController?

@Controller is used to define a regular Spring MVC controller, while @RestController is a convenience annotation that combines @Controller and @ResponseBody.

@RestController directly returns the response in JSON or XML format, bypassing view rendering (like JSP or Thymeleaf). It’s ideal for RESTful APIs.

11. What is Spring Boot Initializer?

Spring Boot Initializer is a web tool to create Spring Boot projects quickly with predefined configurations.

You can go to Spring Initializer to select dependencies, specify the project structure (Maven/Gradle), and generate the project skeleton.

12. How to configure exception handling in Spring Boot?

You can handle exceptions globally using @ControllerAdvice and @ExceptionHandler.

Detailed Answer:


@ControllerAdvice
public class GlobalExceptionHandler {
  
  @ExceptionHandler(UserNotFoundException.class)
  public ResponseEntity handleUserNotFound(UserNotFoundException e) {
    return new ResponseEntity<>("User not found", HttpStatus.NOT_FOUND);
  }
}

This method globally handles exceptions like UserNotFoundException.

13. How do you connect Spring Boot to a database?

Spring Boot offers built-in support for database configurations using application.properties and @Entity classes.

Define the data source configuration in application.properties:


spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret

Then, create JPA entities and repositories.

14. Explain Spring Boot’s Profiles feature.

Profiles allow you to configure multiple environments (e.g., dev, test, prod) with different properties.

You can specify different application-{profile}.properties files for each environment and activate a profile using spring.profiles.active.


spring.profiles.active=dev

15. How can you run Spring Boot on a specific port?

By default, Spring Boot runs on port 8080, but you can customize this in the application.properties.

Detailed Answer:


server.port=9090

This configures Spring Boot to run on port 9090 instead.

16. What is Spring Boot’s actuator /info endpoint?

The /actuator/info endpoint provides general information about the running application.

You can customize this info by adding data in the application.properties file, which can be useful for displaying build or version information.


info.app.name=My Spring Boot Application

17. What are Spring Boot starters?

Starters are pre-defined sets of dependencies to include the necessary libraries for various functionalities.

spring-boot-starter-data-jpa includes Hibernate, Spring Data JPA, and relevant libraries, while spring-boot-starter-web includes Spring MVC, Jackson, and embedded Tomcat.

18. How do you implement security in Spring Boot?

Spring Boot integrates Spring Security for implementing authentication and authorization.

You can use spring-boot-starter-security and define security configurations using @EnableWebSecurity.

19. What is the Spring Boot CLI?

The Spring Boot CLI allows you to write Groovy scripts to quickly prototype Spring applications.

It allows developers to build Spring-based Java applications without the need for a full IDE.

20. How can you integrate Spring Boot with an external API?

You can use RestTemplate or WebClient to call external APIs.

For example, you can use RestTemplate to make HTTP calls to third-party services:


RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://api.example.com/data", String.class);

21. What are some common Spring Boot annotations?

  • @SpringBootApplication: Main annotation to start the Spring Boot application.
  • @EnableAutoConfiguration: Enables auto-configuration.
  • @RestController: Combines @Controller and @ResponseBody.

22. What is the use of @SpringBootApplication?

@SpringBootApplication is a combination of three annotations: @EnableAutoConfiguration, @ComponentScan, and @Configuration.

It serves as the entry point for Spring Boot applications and triggers the auto-configuration process.

23. How does Spring Boot implement pagination in a REST API?

Spring Data JPA provides Pageable and Sort interfaces to implement pagination and sorting.

Detailed Answer:


@GetMapping("/users")
public Page getUsers(Pageable pageable) {
    return userRepository.findAll(pageable);
}

This enables pagination in the REST API.

24. How do you enable scheduling in Spring Boot?

You can enable scheduling using the @EnableScheduling annotation and define tasks using @Scheduled.

Detailed Answer:


@Scheduled(fixedRate = 5000)
public void scheduleTask() {
    System.out.println("Task running every 5 seconds");
}

25. What is the use of the application.yml file?

application.yml is an alternative to application.properties that uses YAML syntax.

YAML is more human-readable and supports hierarchical data:


server:
  port: 8081
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb

26. How do you handle CORS in Spring Boot?

You can configure CORS globally or at the controller level using @CrossOrigin.

Detailed Answer:


@CrossOrigin(origins = "http://localhost:3000")
@GetMapping("/users")
public List getUsers() {
    return userService.getAllUsers();
}

This allows cross-origin requests from localhost:3000.

27. What is Spring Boot’s Dependency Injection mechanism?

Spring Boot uses Spring Framework’s Dependency Injection (DI) through annotations like @Autowired.

DI ensures that Spring manages object creation and lifecycle, injecting dependencies into classes via constructor, setter, or field injection.

28. How do you customize error messages in Spring Boot?

You can customize error handling by defining an error attribute in application.properties.

Additionally, you can use @ControllerAdvice for global error handling and custom responses for exceptions.

29. What are the different ways to deploy a Spring Boot application?

Spring Boot applications can be deployed:

  • As a JAR with an embedded server.
  • As a WAR file for deployment in traditional web servers.

30. Scenario: How do you handle circular dependencies in Spring Boot?

If two beans depend on each other, Spring Boot throws a BeanCurrentlyInCreationException. You can resolve this by using @Lazy on one of the dependencies.

Detailed Answer:


@Service
public class ServiceA {
    @Autowired
    @Lazy
    private ServiceB serviceB;
}

@Service
public class ServiceB {
    @Autowired
    private ServiceA serviceA;
}

31. How do you implement caching in Spring Boot?

Spring Boot provides caching support via @EnableCaching and annotations like @Cacheable, @CachePut, and @CacheEvict.

To enable caching, you first add @EnableCaching to your main application class:


@SpringBootApplication
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Use @Cacheable to cache the result of a method:


@Service
public class UserService {

    @Cacheable("users")
    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
}

In this example, the getUserById method caches the user object in a cache named users.

32. How do you configure multiple data sources in Spring Boot?

Spring Boot allows you to configure multiple data sources by defining separate DataSource beans.

In application.properties, configure the multiple data sources:


spring.datasource.primary.url=jdbc:mysql://localhost:3306/primary_db
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/secondary_db

Define two DataSource beans in your configuration class:


@Configuration
public class DataSourceConfig {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
}

33. What are interceptors in Spring Boot, and how do you use them?

Interceptors allow you to pre-process and post-process HTTP requests in Spring MVC applications.

You can create an interceptor by implementing HandlerInterceptor and overriding methods like preHandle, postHandle, and afterCompletion.


public class RequestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // Code executed before the controller
        System.out.println("Pre Handle method called");
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // Code executed after the request completes
        System.out.println("Request completed");
    }
}

To register the interceptor, configure it in a WebMvcConfigurer class:


@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RequestInterceptor());
    }
}

34. How do you implement file upload in Spring Boot?

Spring Boot allows file uploads using MultipartFile.

First, enable file uploading by setting spring.servlet.multipart.enabled=true in your application.properties.

Then, in your controller, you can accept MultipartFile as a parameter:


@RestController
@RequestMapping("/file")
public class FileUploadController {

    @PostMapping("/upload")
    public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("File is empty", HttpStatus.BAD_REQUEST);
        }
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get("uploads/" + file.getOriginalFilename());
            Files.write(path, bytes);
            return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK);
        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

35. How do you implement WebSockets in Spring Boot?

Spring Boot provides WebSocket support using @EnableWebSocket and WebSocket handlers.

First, you need to add the necessary dependencies like spring-boot-starter-websocket.

Create a WebSocket handler:


@Component
public class MyWebSocketHandler extends TextWebSocketHandler {

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.out.println("Received: " + payload);
        session.sendMessage(new TextMessage("Hello Client!"));
    }
}

Then, configure the WebSocket handler:


@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new MyWebSocketHandler(), "/ws");
    }
}

36. What is a Spring Boot filter, and how do you implement one?

Filters allow you to intercept HTTP requests before they reach the controller.

Create a class that implements Filter and override the doFilter method:


@Component
public class RequestLoggingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        System.out.println("Incoming request: " + req.getRequestURI());
        chain.doFilter(request, response);
    }
}

You can register the filter by adding the @Component annotation or manually via a configuration class.

37. How do you implement transaction management in Spring Boot?

Spring Boot provides declarative transaction management using the @Transactional annotation.

You can annotate your service layer methods with @Transactional to ensure that the method is executed within a transaction context:


@Service
public class UserService {

    @Transactional
    public void createUser(User user) {
        userRepository.save(user);
        // Additional operations within the same transaction
    }
}

If any exception occurs within the method, the transaction is automatically rolled back.

38. What is Spring Boot’s spring-boot-devtools, and how does it help in development?

spring-boot-devtools is a module that provides developer-friendly features like automatic restart and live reload.

By adding spring-boot-devtools as a dependency, the application will automatically restart when files are changed. This reduces the need to manually restart the application during development.

39. How do you customize the Spring Boot banner?

You can customize the Spring Boot startup banner by creating a banner.txt file in the src/main/resources directory.

For example, create a banner.txt file with the following ASCII art:


  _____   _       _       ____              
 |  __ \ (_)     | |     |  _ \             
 | |__) | _ _ __ | |_   _| |_) | _____  __  
 |  ___/ | | '_ \| | | | |  _ < / _ \ \/ /  
 |_|     |_|_| |_|_|\__, |____/ \___/_/\_\  
                   __/ |                   
                  |___/                    
                 

Spring Boot will display this custom banner on startup.

40. How do you perform unit testing of Spring Boot applications?

Spring Boot provides support for unit testing with annotations like @SpringBootTest and @MockBean.

To test a Spring Boot application, you can use @SpringBootTest to load the entire application context:


@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @MockBean
    private UserRepository userRepository;

    @Test
    public void testGetUserById() {
        User user = new User(1L, "John");
        Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(user));

        User result = userService.getUserById(1L);
        assertEquals("John", result.getName());
    }
}

@MockBean is used to mock the repository, and the service layer is tested independently.

41. How do you handle validation in Spring Boot using annotations?

Spring Boot provides out-of-the-box validation support through Hibernate Validator and JSR-303/JSR-380 annotations.

You can use annotations like @NotNull, @Size, @Email, and @Pattern to validate request body fields in DTOs. First, ensure that you have the spring-boot-starter-validation dependency.

Define a DTO with validation annotations:


public class UserDto {

    @NotNull(message = "Name cannot be null")
    @Size(min = 2, message = "Name should have at least 2 characters")
    private String name;

    @Email(message = "Email should be valid")
    private String email;

    // Getters and Setters
}

In your controller, use the @Valid annotation to trigger validation:


@RestController
@RequestMapping("/users")
public class UserController {

    @PostMapping
    public ResponseEntity createUser(@Valid @RequestBody UserDto userDto, BindingResult result) {
        if (result.hasErrors()) {
            return new ResponseEntity<>(result.getAllErrors().toString(), HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>("User created", HttpStatus.OK);
    }
}

42. How do you implement custom validation in Spring Boot?

You can implement custom validation by creating your own annotation and validator.

Detailed Answer:

Define a custom annotation:


@Documented
@Constraint(validatedBy = AgeValidator.class)
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidAge {
    String message() default "Invalid age";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Implement the ConstraintValidator interface:


public class AgeValidator implements ConstraintValidator<ValidAge, Integer> {

    @Override
    public boolean isValid(Integer age, ConstraintValidatorContext context) {
        return age != null && age > 18 && age < 65;
    }
}

Use the custom annotation in your DTO:


public class EmployeeDto {

    @ValidAge
    private Integer age;

    // Getters and Setters
}

Now, the ValidAge annotation can be applied to fields where age validation is needed.

43. How do you secure a Spring Boot application using OAuth2?

Spring Boot integrates with Spring Security and OAuth2 to secure applications by configuring an OAuth2 authorization server or resource server.

First, add the necessary dependency for OAuth2:


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

Then, configure the application.yml for OAuth2 login:


spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: YOUR_GOOGLE_CLIENT_ID
            client-secret: YOUR_GOOGLE_CLIENT_SECRET
            scope: profile, email

Now, secure your endpoints by adding security configuration:


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .oauth2Login();
    }
}

44. How do you handle asynchronous processing in Spring Boot?

Spring Boot supports asynchronous processing using the @Async annotation.

Enable asynchronous support by adding @EnableAsync in your main application class:


@SpringBootApplication
@EnableAsync
public class AsyncApplication {
    public static void main(String[] args) {
        SpringApplication.run(AsyncApplication.class, args);
    }
}

Define an asynchronous method using @Async:


@Service
public class EmailService {

    @Async
    public void sendEmail(String to, String message) {
        // Simulate a long-running task
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Email sent to " + to);
    }
}

Now, when the sendEmail method is called, it will execute in a separate thread.

45. How do you implement internationalization (i18n) in Spring Boot?

Spring Boot provides built-in support for internationalization (i18n) using message bundles.

Detailed Answer:

Create message properties files in the src/main/resources directory for each locale:

  • messages.properties (default)
  • messages_fr.properties (French)

Configure LocaleResolver and message source:


@Configuration
public class InternationalizationConfig {

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.US);
        return slr;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }
}

Use @Autowired MessageSource to access localized messages:


@RestController
public class WelcomeController {

    @Autowired
    private MessageSource messageSource;

    @GetMapping("/welcome")
    public String welcome(@RequestHeader(name = "Accept-Language", required = false) Locale locale) {
        return messageSource.getMessage("welcome.message", null, locale);
    }
}

Now, you can change the language by passing a lang parameter, e.g., /welcome?lang=fr.

46. How do you implement scheduled tasks in Spring Boot?

Spring Boot supports scheduling of tasks using the @Scheduled annotation.

Enable scheduling in the main application class using @EnableScheduling:


@SpringBootApplication
@EnableScheduling
public class ScheduleApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScheduleApplication.class, args);
    }
}

Define a method to be scheduled:


@Service
public class TaskSchedulerService {

    @Scheduled(fixedRate = 5000)
    public void scheduleFixedRateTask() {
        System.out.println("Task executed every 5 seconds");
    }

    @Scheduled(cron = "0 0 12 * * ?")
    public void scheduleTaskUsingCronExpression() {
        System.out.println("Task executed every day at noon");
    }
}

The first method runs every 5 seconds, and the second one runs every day at 12 PM.

47. How do you handle exceptions globally in Spring Boot?

You can handle exceptions globally using @ControllerAdvice and @ExceptionHandler.

Create a global exception handler by annotating a class with @ControllerAdvice:


@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity handleUserNotFoundException(UserNotFoundException ex) {
        return new ResponseEntity<>("User not found", HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity handleGenericException(Exception ex) {
        return new ResponseEntity<>("An error occurred", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

This allows you to handle specific exceptions (like UserNotFoundException) and generic ones across your application.

48. How do you expose REST API documentation using Swagger in Spring Boot?

Swagger is used to automatically generate REST API documentation.

Detailed Answer:

Add Swagger dependencies to pom.xml:


<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.5.9</version>
</dependency>

 Access the API documentation UI by visiting /swagger-ui.html. You can also customize the API documentation in application.properties:


springdoc.api-docs.path=/api-docs

Swagger will automatically generate a UI where you can test your REST API.

49. How do you configure a custom port in Spring Boot?

You can configure the application to run on a custom port using the application.properties file.

Set the server.port property in application.properties:


server.port=9090

This configures the Spring Boot application to run on port 9090 instead of the default 8080.

50. How do you create a custom starter in Spring Boot?

A custom Spring Boot starter is a module that provides auto-configuration and dependencies for a specific feature.

Detailed Answer:

  • Create a Maven project for your starter and include dependencies needed by the starter.
  • Implement @Configuration classes for auto-configuration.
  • Create META-INF/spring.factories to register the auto-configuration class:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.starter.MyAutoConfiguration
  • Package and publish the starter.

This way, users can include your custom starter just by adding a dependency in their pom.xml.

51. How do you monitor a Spring Boot application using Actuator?

Spring Boot Actuator provides production-ready features to help you monitor and manage applications, including health checks, metrics, and environment info.

Detailed Answer: To enable Actuator, add the following dependency:


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

You can configure which Actuator endpoints are exposed via application.properties:


management.endpoints.web.exposure.include=health,info,metrics
management.endpoint.health.show-details=always

Access the health endpoint by visiting:


http://localhost:8080/actuator/health

Actuator endpoints provide useful monitoring data like application health, metrics, environment, etc.

52. How do you implement circuit breaker patterns in Spring Boot?

The circuit breaker pattern can be implemented using the Resilience4j library in Spring Boot.

Detailed Answer: Add the necessary Resilience4j dependency:


<dependency>
    <groupId>io.github.resilience4j</groupId>
    <artifactId>resilience4j-spring-boot2</artifactId>
    <version>1.7.1</version>
</dependency>

Then, enable circuit breakers in your service:


@Service
public class ExternalService {

    @CircuitBreaker(name = "externalService", fallbackMethod = "fallback")
    public String callExternalService() {
        // Simulate external service call
        if (new Random().nextInt(10) < 7) {
            throw new RuntimeException("Service unavailable");
        }
        return "Success";
    }

    public String fallback(Throwable t) {
        return "Fallback: External service is down!";
    }
}

In this example, if the callExternalService method fails, the circuit breaker triggers the fallback method to handle the failure gracefully.

53. How do you use Spring Cloud Config for externalized configuration in Spring Boot?

Spring Cloud Config provides server and client-side support for externalized configuration in distributed systems.

Detailed Answer:

Create a Spring Cloud Config Server by adding the following dependency:


<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>

In your Config Server application, enable it using @EnableConfigServer:


@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}

Store your configuration in a Git repository (e.g., application.yml), and configure the config server to use that repository:


spring.cloud.config.server.git.uri=https://github.com/your-repo/config-repo

In your Spring Boot client applications, configure the bootstrap.properties file to point to the config server:


spring.application.name=my-app
spring.cloud.config.uri=http://localhost:8888

The client applications will fetch configuration from the centralized config server.

54. How do you handle file download in Spring Boot?

Spring Boot makes it easy to handle file downloads using ResponseEntity and InputStreamResource.

Detailed Answer: You can implement file download functionality in your controller:


@RestController
@RequestMapping("/files")
public class FileDownloadController {

    @GetMapping("/download")
    public ResponseEntity downloadFile() throws IOException {
        File file = new File("sample.txt");
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
                .contentType(MediaType.TEXT_PLAIN)
                .contentLength(file.length())
                .body(resource);
    }
}

This code allows users to download a sample.txt file when they hit the /files/download endpoint.

55. What is Flyway, and how do you use it in Spring Boot for database migrations?

Flyway is a database versioning tool that allows you to manage schema changes in a structured and version-controlled manner.

Detailed Answer: Add the Flyway dependency:


<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-core</artifactId>
</dependency>

Create migration scripts in the db/migration folder under src/main/resources with the naming convention V1__Description.sql, V2__Another_Description.sql, etc.

Example of a migration script (V1__create_user_table.sql):


CREATE TABLE users (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL
);

Flyway will automatically execute these scripts when your application starts.

56. How do you load application properties from different environments in Spring Boot?

Spring Boot supports environment-specific configurations using application-{profile}.properties files.

Detailed Answer: Create environment-specific property files like application-dev.properties and application-prod.properties for different environments.

In application.properties, specify the active profile:


spring.profiles.active=dev

Alternatively, you can set the active profile via command line:


java -jar myapp.jar --spring.profiles.active=prod

Each profile-specific property file can contain different configurations for that environment.

57. What is Spring Boot DevTools, and how does it improve development?

Spring Boot DevTools provides features like automatic restarts, live reload, and configurations that simplify the development process.

Detailed Answer: Add the following dependency to your pom.xml:


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

Key Features:

  • Automatic Restart: The application automatically restarts whenever you make changes to class files or configuration.
  • LiveReload: Refreshes your browser automatically after changes to static resources like HTML, CSS, or JS.

DevTools is a powerful productivity booster during development.

58. How do you integrate RabbitMQ with Spring Boot?

RabbitMQ is a messaging broker, and Spring Boot simplifies its integration using spring-boot-starter-amqp.

Detailed Answer: Add the following dependency:


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

Configure RabbitMQ in application.properties:


spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

Create a simple listener for a RabbitMQ queue:


@Component
public class RabbitMQListener {

    @RabbitListener(queues = "my-queue")
    public void listen(String message) {
        System.out.println("Received message: " + message);
    }
}

Publish messages to the RabbitMQ queue:


@Autowired
private RabbitTemplate rabbitTemplate;

public void sendMessage(String message) {
    rabbitTemplate.convertAndSend("my-queue", message);
}

59. How do you configure logging in Spring Boot?

Spring Boot uses Logback as its default logging framework and can be configured through application.properties or logback-spring.xml.

Detailed Answer: To configure logging levels in application.properties:


logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
logging.file.name=logs/app.log

Alternatively, for more advanced configuration, you can use a logback-spring.xml file:


<configuration>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>logs/app.log</file>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="DEBUG">
        <appender-ref ref="FILE" />
    </root>
</configuration>

This configuration directs logs to a file app.log with detailed patterns and output formats.

60. How do you implement pagination and sorting in Spring Boot with Spring Data JPA?

Spring Data JPA provides built-in support for pagination and sorting using Pageable and Sort.

Detailed Answer: In your repository interface, extend PagingAndSortingRepository:


public interface UserRepository extends PagingAndSortingRepository<User, Long> {

    Page<User> findByLastName(String lastName, Pageable pageable);
}

In your service layer, you can request paginated data:


public Page getUsers(int page, int size, String sortBy) {
    Pageable pageable = PageRequest.of(page, size, Sort.by(sortBy));
    return userRepository.findAll(pageable);
}

To handle pagination in your controller:


@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public Page getUsers(@RequestParam int page, @RequestParam int size, @RequestParam String sortBy) {
        return userService.getUsers(page, size, sortBy);
    }
}

This allows you to implement efficient data retrieval with pagination and sorting capabilities.

Conclusion

Mastering Spring Boot requires a solid understanding of its core features, as well as practical knowledge of real-world use cases like handling security, database operations, and asynchronous tasks. By exploring these frequently asked interview questions, you not only sharpen your Spring Boot skills but also gain insights into how to effectively solve common problems in application development. Use this guide to confidently approach Spring Boot interviews and build high-quality Java applications.



Leave a Reply

Your email address will not be published. Required fields are marked *

*