0% found this document useful (0 votes)
11 views

007SpringBootInterviewQuestions PDF

Spring Boot important questions

Uploaded by

vijendrahomeacc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

007SpringBootInterviewQuestions PDF

Spring Boot important questions

Uploaded by

vijendrahomeacc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

1.

Describe the role of the @SpringBootApplication annotation in bootstrapping


a Spring Boot application.
2. Describe the role of the Spring Boot parent POM.
3. Explain the differences between Spring Boot's @ModelAttribute and
@RequestBody in request handling.
4. What is the purpose of Spring Boot's @Value annotation for accessing
application properties?
5. What is Spring Boot's support for CQRS (Command Query Responsibility
Segregation) architecture?
6. How do you implement content negotiation in a Spring Boot REST API for
different media types?
7. Describe the use of Spring Boot @RequestMapping and @GetMapping annotations
for URL mapping.
8. How do you configure Spring Boot to send email notifications using JavaMail
or SendGrid?
9. What is the purpose of Spring Boot @ControllerAdvice annotation, and when is
it used?
10. Explain the differences between Spring Boot's actuator endpoints like
/health and /info.
11. How do you implement asynchronous communication between microservices
using Spring Boot?
12. Describe Spring Boot's support for reactive programming with Project
Reactor.
13. How can you implement API rate limiting and throttling in a Spring Boot
REST API?
14. Explain the differences between Spring Boot's REST and SOAP web services.
15. How do you handle database transactions in Spring Boot, and what are the
different transaction isolation levels?
16. Describe the purpose of Spring Boot's @EventListener annotation for
handling application events.
17. Explain the use of Spring Boot @ConfigurationProperties and how to bind
configuration properties to Java objects.
18. Explain the use of Spring Boot's @EnableGlobalMethodSecurity for
method-level security in REST APIs.
19. What is the purpose of Spring Boot's @ConditionalOnMissingBean and
@ConditionalOnClass annotations?
20. What is the role of Spring Boot's @Data annotation from Project Lombok,
and how does it work?
21. How can you implement custom error handling and responses in a Spring
Boot REST API?
22. How can you configure Spring Boot to use a different templating engine
for emails (e.g., Thymeleaf)?
23. Explain the use of Spring Boot's @CacheConfig annotation for caching
configuration.
24. How do you handle long-running processes in Spring Boot applications?
25. Explain the concept of Spring Boot @RequestBody and @ResponseBody
annotations for REST APIs.
26. Explain the use of Spring Boot's @Async annotation for asynchronous
method execution
27. Describe the differences between Spring Boot's @Component, @Service, and
@Repository annotations.
28. Describe the use of Spring Boot's @Validated annotation for validation in
REST controllers.
29. Explain the role of Spring Boot @CrossOrigin annotation in handling CORS.
30. What is the purpose of Spring Boot's @Lazy annotation, and when should
you use it?
31. How can you implement API versioning in a Spring Boot application?
32. What is Spring Boot's support for OpenAPI and Swagger, and how do you
integrate it into your RESTful API?
33. How can you use Spring Boot @Conditional annotations to conditionally
configure beans?
34. Explain the concept of "fat jar" and "thin jar" in Spring Boot.
35. What is the role of Spring Boot @EnableAutoConfiguration annotation?
36. Describe the purpose of Spring Boot @Scheduled annotation.
37. Describe the use of the @Cacheable annotation for caching in Spring Boot.
38. Describe the use of Spring Boot's @Profile annotation for different
application environments.
39. How does Spring Boot's Environment handle property resolution and profile
activation?
40. How does Spring Boot handle external configuration files like
application.properties or application.yml?
41. What role does the spring-boot-starter-parent play in managing
dependencies and versions in Spring Boot projects?
42. Describe the process of classpath scanning for components and
configurations in Spring Boot.
43. How is the choice of embedded web server (e.g., Tomcat, Jetty, Undertow)
determined in Spring Boot?
44. What are the ApplicationRunner and CommandLineRunner interfaces used for
in Spring Boot?
45. Explain the handling of command-line arguments and their effect on
application behavior in Spring Boot.
46. How does Spring Boot initialize SpringApplicationRunListeners, and what
is their purpose in the startup process?
47. Describe the hierarchy and role of SpringApplication in Spring Boot's
internal architecture.
48. Explain the process of packaging Spring Boot applications as executable
JAR files.
49. How does Spring Boot manage the classpath for dependencies and external
resources?
50. How does Spring Boot's ApplicationContext hierarchy function in the
internal architecture?
51. How does Spring Boot manage dependency injection and bean creation for
various components and configurations in the application context?
52. Describe the internals of the
aog.springframework.boot.autoconfiguration.import (or spring.factories in
older versions of spring boot) file and how it influences
auto-configuration.
53. Explain the use of the SpringApplicationEvent and how it fits into the
application lifecycle.
54. How does Spring Boot manage shutdown events and the graceful stopping of
application context?
55. Explain the internal workings of Spring Boot's JPA and Hibernate support.
56. How does Spring Boot handle transaction management for data sources?
57. Explain the use of the Spring Boot Maven Plugin in building and running
applications.
58. What is the order of precedence for property sources in Spring Boot?
59. What is the purpose of the @PropertySource annotation, and how does it
influence property resolution in Spring Boot?
60. Describe the internal workings of Spring Boot's property resolution and
profile activation.
61. How are Spring Boot application properties loaded and processed during
startup?
62. How does Spring Boot handle dependency injection for various beans and
components?
63. Describe the purpose of Spring Boot's @Retryable and @Recover annotations
for handling retries in methods.
64. Describe the role of Spring Boot's embedded messaging brokers like
RabbitMQ or Apache Kafka.
=================================================================================
Describe the role of the @SpringBootApplication annotation in bootstrapping a
Spring Boot application.
The @SpringBootApplication annotation is a convenience annotation provided by
Spring Boot that combines three other annotations: @Configuration,
@EnableAutoConfiguration, and @ComponentScan.
It serves as a meta-annotation, allowing developers to declare a single
annotation instead of three separate ones.
Here's a breakdown of each of these annotations and their roles:
● @Configuration: This annotation indicates that the class annotated with it
declares one or more @Bean methods, and thus should be processed by the
Spring container to generate bean definitions and service requests for those
beans. In the context of @SpringBootApplication, it signifies that the
annotated class can be used as a configuration class for the Spring
application context.
● @EnableAutoConfiguration: This annotation enabled Spring Boot's
auto-configuration mechanism. Auto-configuration attempts to automatically
configure your Spring application based on the dependencies you have added
to the project, the classpath, and other factors. It saves developers from
having to explicitly configure many common features.
● @ComponentScan: This annotation tells Spring to scan the specified
package(s) and all of its sub-packages for components like @Component,
@Service, @Repository, and @Controller annotations. Spring then registers
these classes as beans in the application context, making them available for
dependency injection and other Spring features.
By combining these three annotations into @SpringBootApplication, developers can
bootstrap their Spring Boot application with minimal configuration.

Describe the role of the Spring Boot parent POM.


The Spring Boot parent POM is essentially a Maven POM file provided by the Spring
Boot framework. It serves as the parent for all Spring Boot projects and contains
common configurations and dependency management settings that are shared across
multiple Spring Boot applications. Developers can specify the Spring Boot parent
POM in their project's POM file, inheriting its configurations and dependencies.

Explain the differences between Spring Boot's @ModelAttribute and @RequestBody in


request handling.
Content negotiation in a Spring Boot REST API allows clients to request different
representations of a resource based on their preferences, such as JSON, XML, or
others. Spring Boot provides built-in support for content negotiation through the
use of the `produces` attribute in `@RequestMapping` annotations or through the
`produces` attribute in `@GetMapping`, `@PostMapping`, etc., annotations.

Here's how you can implement content negotiation in a Spring Boot REST API:

1. **Using `@RequestMapping` with `produces` attribute**:


java
@RestController
@RequestMapping("/api")
public class MyController {

@GetMapping(value = "/resource", produces =


MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Resource> getResourceAsJson() {
// Retrieve resource
return ResponseEntity.ok(resource);
}

@GetMapping(value = "/resource", produces =


MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Resource> getResourceAsXml() {
// Retrieve resource
return ResponseEntity.ok(resource);
}
}

2. **Using `@GetMapping`, `@PostMapping`, etc., with `produces` attribute**:


java
@RestController
@RequestMapping("/api")
public class MyController {

@GetMapping(value = "/resource", produces =


MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Resource> getResourceAsJson() {
// Retrieve resource
return ResponseEntity.ok(resource);
}

@GetMapping(value = "/resource", produces =


MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Resource> getResourceAsXml() {
// Retrieve resource
return ResponseEntity.ok(resource);
}
}

3. **Using ContentNegotiationManager**:

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer
configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.mediaType("json", MediaType.APPLICATION_JSON)
.mediaType("xml", MediaType.APPLICATION_XML);
}
}

4. **Using RequestMappingHandlerMapping**:
java
@RestController
@RequestMapping("/api")
public class MyController {

@Autowired
private RequestMappingHandlerMapping requestMappingHandlerMapping;

@GetMapping(value = "/resource")
public ResponseEntity<Resource> getResource(HttpServletRequest request)
throws Exception {
HandlerMethod handlerMethod = (HandlerMethod)
requestMappingHandlerMapping.getHandler(request).getHandler();
produces =
handlerMethod.getMethodAnnotation(RequestMapping.class).produces();
if (produces.contains(MediaType.APPLICATION_JSON_VALUE)) {
// Retrieve resource as JSON
} else if (produces.contains(MediaType.APPLICATION_XML_VALUE)) {
// Retrieve resource as XML
}
}
}

What is the purpose of Spring Boot's @Value annotation for accessing application
properties?

How do you implement content negotiation in a Spring Boot REST API for different
media types?

Describe the use of Spring Boot @RequestMapping and @GetMapping annotations for
URL mapping.

How do you configure Spring Boot to send email notifications using JavaMail or
SendGrid?
To configure Spring Boot to send email notifications using JavaMail or SendGrid,
you need to set up the necessary dependencies, configure the mail server
properties, and create a service or component to handle the email sending logic.
Here's a step-by-step guide:

1. **Add Dependencies**:
If you're using JavaMail, include the following dependencies in your
`pom.xml`:
```xml
<dependency>
<groupId>org.springframework.boot//groupId>
<artifactId>spring-boot-starter-mail//artifactId>
//dependency>
```
If you're using SendGrid, include the SendGrid dependency along with Spring
Boot Mail starter:
```xml
<dependency>
<groupId>org.springframework.boot//groupId>
<artifactId>spring-boot-starter-mail//artifactId>
//dependency>
<dependency>
<groupId>com.sendgrid//groupId>
<artifactId>sendgrid-java//artifactId>
<version>${sendgrid.version}//version>
//dependency>
```

2. **Configure Mail Server Properties**:


In your `application.properties` or `application.yml`, configure the
properties for your mail server. For JavaMail, it might look like this:
```properties
spring.mail.host=smtp.example.com
spring.mail.port=587
[email protected]
spring.mail.password=yourpassword
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
```
For SendGrid, you typically configure the SendGrid API key:
```properties
spring.mail.host=smtp.sendgrid.net
spring.mail.port=587
spring.mail.username=apikey
spring.mail.password=your-api-key
```

3. **Create Email Service**:


Create a service or component to handle the email sending logic. Below is an
example of a service using JavaMail:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class EmailService {

@Autowired
private JavaMailSender javaMailSender;

public void sendEmail(String to, String subject, String text) throws


MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text, true); // true indicates HTML format
javaMailSender.send(message);
}
}
```

4. **Use the Email Service**:


Inject the `EmailService` into your controller or other components where you
want to send emails, and call the `sendEmail` method with the recipient, subject,
and content.

That's it! Your Spring Boot application should now be configured to send email
notifications using either JavaMail or SendGrid. Make sure to handle exceptions
appropriately, especially when dealing with messaging exceptions in the email
service.

What is the purpose of Spring Boot @ControllerAdvice annotation, and when is it


used?

Explain the differences between Spring Boot's actuator endpoints like /health and
/info.
/actuator/auditevents
Exposes audit events information for the current application.

/actuator/beans
Displays a complete list of all the Spring beans in your application.

/actuator/caches
Exposes available caches.

/actuator/conditions
Shows the conditions that were evaluated on configuration and auto-configuration
classes and the reasons why they did or did not match.

/actuator/configprops
Displays a collated list of all @ConfigurationProperties.

/actuator/env
Exposes properties from Spring’s ConfigurableEnvironment.

/actuator/flyway
Shows any Flyway database migrations that have been applied.

/actuator/health
Shows application health information.
/actuator/httptrace
Displays HTTP trace information (by default, the last 100 HTTP request-response
exchanges).

/actuator/info
Displays arbitrary application info.

/actuator/integrationgraph
Shows the Spring Integration graph.

/actuator/loggers
Shows and modifies the configuration of loggers in the application.

/actuator/liquibase
Shows any Liquibase database migrations that have been applied.

/actuator/metrics
Shows ‘metrics’ information for the current application.

/actuator/mappings
Displays a collated list of all @RequestMapping paths.

/actuator/scheduledtasks
Displays the scheduled tasks in your application.

/actuator/sessions
Allows retrieval and deletion of user sessions from a Spring Session-backed
session store. Not available when using Spring Session’s support for reactive web
applications.

/actuator/shutdown
Let the application be gracefully shutdown.

/actuator/threaddump
Performs a thread dump.

Describe Spring Boot's support for reactive programming with Project Reactor.
Spring Boot provides extensive support for reactive programming with Project
Reactor, which is a reactive library for building non-blocking, asynchronous
applications on the JVM. Here's how Spring Boot leverages Project Reactor for
reactive programming:
1. WebFlux Framework: Spring Boot includes the WebFlux framework, which is a
reactive web framework built on top of Project Reactor. WebFlux provides
support for building reactive, non-blocking web applications using annotated
controllers and functional endpoints.
2. Reactive WebClient: Spring Boot includes a reactive WebClient that
integrates with Project Reactor. The WebClient allows you to make
non-blocking HTTP requests to external services and APIs. It supports
various HTTP clients, including WebClient.Builder and WebClient.create, for
making GET, POST, PUT, DELETE, and other types of requests.
3. Reactive Data Access: Spring Boot offers reactive support for data access
through Spring Data Reactive repositories. With reactive repositories, you
can perform asynchronous database operations using Project Reactor's Mono
and Flux types. Spring Data provides support for reactive database drivers,
such as R2DBC for relational databases and Spring Data MongoDB for MongoDB.
4. Reactive Configuration and Auto-Configuration: Spring Boot provides
auto-configuration support for reactive components, such as WebClient,
WebClient.Builder, and reactive data sources. It automatically configures
these components based on the dependencies and configuration properties in
the application context.

You might also like