Unit-05 Java
Unit-05 Java
Q4. What are the types of Dependency Injection in Spring? (Fully detailed with subtypes)
Dependency Injection (DI) is a fundamental concept in the Spring Framework. It allows the
Spring container to inject object dependencies at runtime instead of allowing the object
itself to create them. This promotes loose coupling, modularity, and easier testing of
components.
There are mainly two core types of Dependency Injection supported in Spring:
Q5. Compare Constructor Injection and Setter Injection in Spring with suitable example in
tabular format.
Below is a detailed comparison between Constructor Injection and Setter Injection,
explaining when and why each is used.
Visibility of All dependencies are visible in the Not visible unless explicitly reading
Dependencies constructor setter methods
Circular Dependency May cause issues if beans depend Better at resolving circular
Handling on each other dependencies
Easier to test due to clear Also testable, but might need more
Ease of Testing
constructor parameters setup
Default Usage in Often used with @Autowired on Often used with @Autowired on
Spring constructors setter methods
Q8. How does Aspect-Oriented Programming (AOP) work in Spring? Provide examples.
Aspect-Oriented Programming (AOP) is a technique in Spring that allows you to separate
common concerns like logging, security, transaction management, etc., from the core
business logic. These are known as cross-cutting concerns because they affect multiple parts
of an application.
Instead of repeating such logic in every class or method, AOP lets you write it once in a
separate unit called an Aspect, and apply it wherever needed.
Key terms in Spring AOP:
Aspect: The class where the cross-cutting logic is written.
Advice: The actual action taken (like logging before a method runs).
Pointcut: Expression that defines where the advice should be applied (e.g., methods
starting with “get”).
Join point: A specific point in program execution (like method execution) where
advice is applied.
Weaving: The process of applying advice to the target object’s methods.
Spring uses proxies internally to apply the aspects. These proxies wrap the original object
and allow Spring to run the aspect logic before, after, or around method execution.
Example use-cases:
Logging method execution time across all services.
Checking user roles before accessing certain features.
Managing transactions automatically in a service method.
AOP promotes separation of concerns, cleaner business logic, and reusability. With AOP,
business classes remain focused only on core logic while the reusable functionality (like
logging or security) is handled in a centralized aspect.
In summary, Spring AOP makes it possible to apply common functionality in a clean, modular
way, without polluting business logic with repeated code.
Q9. What are the advantages of using Spring for Dependency Injection and Inversion of
Control?
Spring’s implementation of Dependency Injection (DI) and Inversion of Control (IoC) brings
several important advantages that make development easier, cleaner, and more
maintainable.
Here are the major advantages:
1. Loose Coupling: Classes don’t need to create or manage their dependencies. Instead,
dependencies are provided externally by the container. This allows parts of the code
to change independently.
2. Better Testability: Since dependencies are injected, they can be easily mocked or
replaced in unit tests without modifying the actual class.
3. Reusability: Beans and components are written independently and can be reused in
different parts of the application or even in other projects.
4. Maintainability: With central configuration and minimal hardcoded logic, Spring
applications are easier to modify or extend.
5. Modular Code Design: Components can be developed separately and integrated
together using configuration, making the system scalable and adaptable.
6. Centralized Configuration: All beans and their dependencies are configured in one
place (XML, annotations, or Java config), making management simpler.
7. Lifecycle Management: Spring controls the entire lifecycle of beans—from creation,
initialization to destruction.
8. Less Boilerplate Code: You don’t need to write repetitive code to instantiate and wire
objects.
9. Flexibility in Injection: Spring supports multiple ways to inject dependencies—
constructor, setter, and field injection.
10. Easy Integration with Other Frameworks: Spring integrates well with JPA, Hibernate,
JMS, Struts, and many others—making it ideal for enterprise applications.
In conclusion, Spring DI and IoC together simplify application development by promoting
good software design principles like modularity, separation of concerns, and reusability.
Q10. What is the singleton scope in Spring? How is it different from other scopes?
In Spring, the singleton scope means that only one instance of a bean is created by the
container, and that same instance is returned every time the bean is requested. It is the
default scope in Spring, and it applies to all beans unless another scope is specified.
Key Features of Singleton Scope:
The bean is created once per container.
Every request for that bean returns the same shared instance.
It is ideal for stateless services or utility components that do not hold user-specific
data.
It saves memory and improves performance since it avoids creating multiple objects.
How it is different from other scopes:
1. Prototype Scope: A new instance of the bean is created each time it is requested
from the container. It is useful for beans that maintain state or require fresh
instances.
2. Request Scope: One instance per HTTP request. It is used in web applications where
each request should get a separate bean instance.
3. Session Scope: One instance per user session. It is used for storing user-specific data
during a session in a web application.
4. Application Scope: One shared instance for the entire web application context.
Similar to singleton but specific to web apps.
5. Websocket Scope: One instance per WebSocket session. This is used in applications
with real-time communication.
In summary, the singleton scope ensures only one instance exists, which makes it suitable
for shared and stateless components. It differs from other scopes based on lifecycle,
visibility, and number of instances created per request/session/container.
Q11. What are different types of main scopes in Spring? Explain each one.
In Spring Framework, the term scope refers to the lifecycle and visibility of a bean within the
application context. The scope decides how many times a bean will be created and in what
context it will be available. Spring provides multiple scopes, some for general use and some
specific to web applications.
The most commonly used and default scope is singleton, in which a single instance of a bean
is created and shared across the entire Spring container. Every request for this bean returns
the same shared instance. It is ideal for stateless services like configuration classes or logging
services. Being the default, if no scope is specified, singleton is assumed.
The prototype scope creates a new bean instance every time it is requested from the
container. Unlike singleton, the Spring container does not manage the complete lifecycle of
prototype beans after handing them over. This is best suited for stateful beans, such as data
entry forms, where each user or component might need a separate copy.
Request scope is specific to web applications. In this scope, a new bean instance is created
for each HTTP request. It is alive only during that request. This is helpful in scenarios where
form data or request-specific user details are required to be handled without sharing state
across multiple requests.
Session scope is also web-specific. A bean with session scope lives throughout an HTTP
session. A separate instance is created and maintained for each user session. It is useful for
storing user-specific data like login information, shopping cart, or temporary preferences.
Application scope defines a single bean instance per web application. It is similar to
singleton but is tied to the lifecycle of the servlet context in web applications. This scope is
suitable when we want to share global data or configuration across all users and sessions
within a web application.
Lastly, the WebSocket scope is used in real-time web applications and creates one bean
instance per WebSocket session. It ensures that each live connection over WebSocket
protocol maintains its own instance of a bean, which is essential in real-time communication
like chat apps or live dashboards.
Each of these scopes has its use depending on whether the application is a standard Java
app or a web app. Choosing the correct scope ensures proper memory management, data
consistency, and application performance.
Q12. What is the prototype scope in Spring? When would we use it?
In Spring Framework, the prototype scope is one of the bean scopes that defines the
lifecycle of a bean such that a new instance is created every time the bean is requested
from the Spring container. This is different from the default singleton scope, which returns
the same shared instance each time.
When a bean is defined with prototype scope, Spring creates a new object of that bean
whenever it is fetched, either through dependency injection or via a method like getBean().
This means that each consumer gets a unique and independent copy of the bean, rather
than sharing a single instance.
The prototype scope is especially useful when dealing with stateful objects—that is, objects
which hold data that varies from instance to instance. For example, in scenarios where each
user’s form submission needs its own object, or when you want to maintain unique data in
each instance of a class, prototype scope is the right choice.
An important point to understand about prototype scope is that the Spring container is only
responsible for creating and initializing the bean. After that, it does not manage the full
lifecycle, which means it doesn’t call the destroy method or perform any cleanup. This
makes it necessary for the developer to manage the cleanup manually, if needed.
In web applications, prototype scope can be used for request-specific beans that should not
retain any shared state between users. In desktop or multithreaded applications, it allows
each thread or operation to work with its own fresh object, ensuring thread safety and data
integrity.
In summary, prototype scope in Spring is ideal when we need a new and separate instance
of a bean every time it's requested, especially for stateful components where sharing an
object between users or operations is not desired.
Q13. What is the session scope in Spring? How is it different from other scopes?
In Spring Framework, the session scope is one of the web-specific bean scopes. When a
bean is defined with session scope, Spring creates a separate instance of that bean for each
HTTP session. This means that every user who interacts with the application gets their own
unique instance of the bean, and that instance remains active until the session expires or is
invalidated.
This scope is very useful when you need to store user-specific data across multiple HTTP
requests. For example, a user’s shopping cart, login details, or personal preferences can be
stored in session-scoped beans, allowing persistence across several actions during the
session.
The session scope differs from other scopes in the following ways. Unlike singleton, which
provides only one shared instance for all users, session scope gives a separate instance to
each user. It also differs from request scope, which provides a new instance for each HTTP
request but doesn't retain data beyond a single interaction. Compared to prototype, session
beans are still managed by the container for the full session duration, while prototype beans
are not managed after creation. And unlike application scope, which gives one shared
instance per application, session scope is per user session.
In short, session scope is ideal for maintaining user-specific state or information during the
user’s active session in web applications.
Q14. How does the application scope work in Spring? In what scenarios would we use it?
The application scope in Spring is a web-specific bean scope that provides a single shared
instance of a bean for the entire web application. When a bean is defined with application
scope, the Spring container creates one instance of the bean, and this instance is shared
across all users, requests, and sessions for the lifetime of the web application.
This scope is similar in behavior to the singleton scope, but it is specifically tied to the
ServletContext of a web application. The bean lives as long as the application is running and
is destroyed when the application context shuts down.
Application scope is useful when you have global data or shared resources that need to be
accessed by all users, such as application-level configuration settings, feature flags, or data
that should be cached and reused throughout the application. For example, if you have a list
of countries or categories that all users access frequently, storing it in an application-scoped
bean can improve performance and reduce repeated processing.
Unlike request or session scopes that provide isolated instances per request or user,
application scope provides one consistent instance, which makes it ideal for shared, read-
only data. However, developers should be cautious not to store user-specific or mutable data
in application-scoped beans, as it can lead to concurrency issues.
In summary, application scope is best suited for data or components that are globally
needed and do not vary per user or per request.
Q15. Explain the request scope in Spring. How is it related to web applications?
In Spring, the request scope is a web-specific scope in which a new bean instance is created
for each HTTP request. The bean exists only during the life of that single request and is
discarded once the response is sent back to the client.
This scope is useful in scenarios where you need a bean to carry request-specific data, such
as form submissions, temporary inputs, or user selections. Since each HTTP request is
isolated, the bean does not retain any state between requests, ensuring that user data does
not accidentally leak between users or pages.
The request scope is tightly integrated with the web layer of Spring applications and is often
used in controllers or view-resolving components that need to work with data specific to a
single request. It also helps to avoid thread safety issues, since each thread (representing a
request) gets its own separate bean instance.
Compared to other scopes, request scope is more short-lived than session or application
scopes. It differs from singleton in that it does not share the same instance globally. It also
contrasts with prototype scope because while both produce new instances, the request-
scoped bean is still managed and destroyed by the container after the request ends, while
prototype beans are not managed after creation.
In conclusion, request scope is ideal for handling temporary, request-bound data in web
applications, and it ensures clean separation and memory efficiency for each individual
request.
Q17. How does Spring support WebSocket communication? Explain the relevant
components.
Spring supports WebSocket communication through the Spring WebSocket module, which
provides an easy and powerful way to build real-time applications. It includes both low-level
WebSocket API integration and high-level messaging support using STOMP (Simple Text
Oriented Messaging Protocol).
Key components used in Spring WebSocket communication include:
1. @EnableWebSocketMessageBroker: This annotation is used in configuration classes
to enable WebSocket message handling backed by a message broker.
2. @MessageMapping: Similar to @RequestMapping in controllers, this annotation is
used to define methods that handle messages sent from clients.
3. @SendTo: This is used to define the destination topic where the response message
should be sent after processing a client message.
4. SimpMessagingTemplate: This helper class allows sending messages from the server
to specific clients or topics.
5. Message Broker: Spring integrates an in-memory or external broker (like RabbitMQ)
to handle routing of messages between clients and server endpoints.
6. STOMP Protocol: A higher-level messaging protocol over WebSocket used for
defining messaging semantics like subscribe, send, and receive, making the
development easier and more structured.
7. Client Library: On the client side, Spring typically uses SockJS and STOMP.js libraries
to establish WebSocket connections and handle messages.
This architecture allows Spring applications to support broadcasting messages to many
clients, sending targeted updates to specific users, and enabling interactive applications like
live dashboards, chat rooms, and real-time alerts. The developer doesn’t have to handle the
low-level connection logic directly; Spring abstracts it and makes it easy to use.
Q19. Explain the concept of annotations in Spring. How are they used in bean
configuration?
In Spring, annotations are metadata tags that provide configuration information directly in
the code. Annotations eliminate the need for extensive XML-based configuration and allow
for more concise, readable, and maintainable code. They are a core part of annotation-
based configuration in Spring.
Annotations are used to define beans, inject dependencies, handle component scanning,
and configure aspects like transactions or request mappings. Some of the commonly used
annotations in Spring for bean configuration include:
@Component: Marks a class as a Spring-managed component (bean).
@Service: Specialization of @Component used for service layer classes.
@Repository: Used for DAO or repository classes, providing exception translation.
@Controller: Marks a controller class in Spring MVC.
@Configuration: Indicates a configuration class that defines beans.
@Bean: Declares a method that returns a bean to be managed by Spring.
@Autowired: Automatically injects the required dependencies.
@Qualifier: Helps resolve ambiguity when multiple beans of the same type exist.
When using annotations, Spring uses component scanning to automatically detect and
register beans in the application context. This reduces the need for writing long XML files
and brings the configuration closer to the actual business logic.
In summary, annotations provide a declarative, cleaner way to configure and manage beans
in Spring applications, improving productivity and reducing configuration overhead.
Q20. Can we call a Java class with annotations as a POJO class or not?
Yes, we can still call a Java class with annotations a POJO (Plain Old Java Object), even if it
contains annotations. The term POJO refers to a simple Java object that is not bound by any
special restriction and does not extend any predefined class or implement any specific
interface.
Annotations are metadata—they do not change the nature of the class or force it to follow a
specific contract. A class with annotations like @Component, @Service, or @Entity is still a
POJO in structure because:
It uses normal fields and methods.
It does not require extending framework-specific base classes.
It can still be used independently of the framework if needed.
Spring promotes the use of annotated POJOs to keep the code simple, testable, and
framework-independent. The annotations simply provide configuration or behavioral
instructions to the Spring container.
Therefore, even though annotations enhance the class with additional capabilities, the class
remains a POJO in its basic form.
Q21. What is a bean in Spring? How can the bean lifecycle be controlled in Spring?
In Spring, a bean refers to an object that is managed by the Spring IoC (Inversion of Control)
container. Beans are the backbone of a Spring application and are defined either through
XML configuration, Java-based configuration classes, or annotations. Any class that is
instantiated, assembled, and managed by Spring is considered a bean.
Spring is responsible for the complete lifecycle of a bean—from creation to destruction. This
lifecycle involves several stages including instantiation, dependency injection, initialization,
and destruction. Spring allows developers to customize various phases of this lifecycle using
configuration or lifecycle callback methods.
The bean lifecycle in Spring generally follows these steps:
1. Instantiation: The container creates an instance of the bean.
2. Populate Properties: Dependencies are injected.
3. BeanNameAware / BeanFactoryAware: If implemented, these interfaces allow the
bean to be aware of its name or the factory.
4. PostConstruct: A method annotated with @PostConstruct (or defined in XML) runs
after properties are set.
5. InitializingBean Interface: If the bean implements this interface, its
afterPropertiesSet() method is called.
6. Custom init-method: Defined in XML or Java config and executed after dependency
injection.
7. Ready for Use: The bean is now available for use by the application.
8. PreDestroy / DisposableBean: Before the container is shut down, Spring calls a
method annotated with @PreDestroy or the destroy() method of the DisposableBean
interface.
9. Custom destroy-method: Additional cleanup logic if defined by the developer.
Spring provides many hooks and interfaces to control this lifecycle, such as @PostConstruct,
@PreDestroy, InitializingBean, DisposableBean, and custom initialization or destruction
methods. Developers can choose the method that best fits their coding style or
configuration approach.
Q22. What are the different types of lifecycle callbacks in Spring? Explain each one.
Spring offers several lifecycle callback mechanisms that allow developers to insert logic at
specific points during a bean’s life—especially during initialization and destruction. These
callbacks ensure that a bean is properly prepared before use and cleaned up after use.
Here are the main types of lifecycle callbacks in Spring:
1. @PostConstruct: This is an annotation from javax.annotation used to define a
method that should be run after the bean has been fully initialized and dependencies
injected. It is commonly used to perform setup tasks like initializing connections,
loading default values, etc.
2. InitializingBean Interface: If a bean class implements the InitializingBean interface,
Spring will automatically call its afterPropertiesSet() method after the bean’s
properties have been set. This is an alternative to using @PostConstruct.
3. init-method Attribute: In XML or Java configuration, you can define a method to be
called after initialization using the init-method attribute. This provides a way to
customize setup logic without using annotations or interfaces.
4. @PreDestroy: This annotation marks a method that should be called just before the
bean is removed from the container or the container shuts down. It’s used for
releasing resources like file handles, database connections, etc.
5. DisposableBean Interface: A bean that implements the DisposableBean interface will
have its destroy() method called during shutdown, allowing cleanup operations.
6. destroy-method Attribute: Just like init-method, Spring allows specifying a destroy-
method in configuration to define a custom cleanup method.
All these lifecycle callback mechanisms serve different preferences. Whether you want to
use annotations, interfaces, or configuration-based approaches, Spring provides flexibility.
These callbacks help in making beans reliable, efficient, and resource-conscious throughout
their lifecycle.
Q23. What are the different bean configuration styles in Spring? Provide examples (only
where asked).
Spring supports several styles for defining and configuring beans, giving developers the
flexibility to choose the style that best suits the application’s needs. The major bean
configuration styles are:
1. XML-Based Configuration: In this traditional style, beans and their dependencies are
defined in an external XML file. It uses <bean> tags to define classes and their
properties. Although more verbose, it keeps configuration separate from the source
code.
2. Annotation-Based Configuration: This style uses Java annotations like @Component,
@Service, @Autowired, etc., directly in the code. Component scanning is enabled
using @ComponentScan, and Spring automatically detects and registers annotated
beans. This reduces the need for XML configuration.
3. Java-Based Configuration (Using @Configuration): In this modern approach, beans
are defined in a Java class using @Configuration and @Bean annotations. This
combines the clarity of code with the power of external configuration. It allows for
full type safety and easier refactoring using IDE support.
Each of these styles has its benefits. XML-based configuration is good for externalizing setup
logic, annotation-based configuration reduces clutter and improves readability, while Java-
based configuration offers full flexibility in coding while avoiding XML.
Q24. How does Spring handle bean initialization and destruction during its lifecycle?
Spring handles bean initialization and destruction through a well-defined lifecycle
mechanism. When the Spring container starts up, it reads the bean definitions from the
configuration, creates the beans, injects their dependencies, and calls the necessary
initialization methods. When the application context is closed or the application shuts down,
Spring performs destruction callbacks.
During initialization, after a bean is instantiated and its properties are set, Spring performs
the following steps:
It checks for and calls any method annotated with @PostConstruct.
If the bean implements the InitializingBean interface, it calls the afterPropertiesSet()
method.
If an init-method is configured in XML or Java, it is called as well.
During destruction, when the application context is shutting down:
Spring calls methods annotated with @PreDestroy to allow cleanup.
If the bean implements DisposableBean, it calls the destroy() method.
If a destroy-method is specified, that method is also executed.
This flexible handling of initialization and destruction ensures that developers can perform
setup and cleanup tasks reliably, while also giving options to choose between annotations,
interfaces, or configuration for controlling lifecycle events.
Q25. How does dependency management help in Spring Boot build system?
In Spring Boot, dependency management is handled in a simplified and intelligent way using
a mechanism called “Starters” and the underlying Spring Boot dependency management
plugin in the build system. This helps manage transitive dependencies (dependencies of
dependencies) and ensures that compatible versions of libraries are used together.
Spring Boot provides pre-defined starter POMs (in Maven) or starter dependencies (in
Gradle) such as spring-boot-starter-web, spring-boot-starter-data-jpa, etc. These starters
include all the commonly required libraries for a specific functionality, so the developer
doesn’t have to manually list each dependency or worry about version conflicts.
Spring Boot also uses the Spring Boot BOM (Bill of Materials) to lock down versions. This
means when you use any dependency from the Spring Boot ecosystem, its version is
automatically managed by the framework, ensuring compatibility. This eliminates guesswork
and reduces maintenance.
Additionally, the dependency management system in Spring Boot makes the build files
cleaner, reduces redundancy, and prevents version mismatch errors. It is also easy to
override versions if needed while still benefiting from the default management provided by
Spring Boot.
In summary, Spring Boot’s dependency management simplifies the build process, avoids
conflicts, and saves time by managing versions intelligently and consistently across the entire
project.
Q26. How is the code structured in a Spring Boot application?
A Spring Boot application follows a well-organized and layered structure that helps
developers separate concerns and maintain clarity in their code. The structure is convention-
based, meaning Spring Boot expects the source code to be placed in specific packages so it
can perform component scanning effectively.
The core structure of a Spring Boot project typically includes the following packages:
1. com.example.projectname (Base Package): This is the main package containing the
application class annotated with @SpringBootApplication. This annotation enables
component scanning, auto-configuration, and configuration management.
2. controller Package: Contains all the REST controllers that handle HTTP requests and
map them to appropriate service methods. Classes here are typically annotated with
@RestController.
3. service Package: Contains the service layer which handles business logic. These
classes are annotated with @Service.
4. repository Package: Contains DAO (Data Access Objects) or repository interfaces
annotated with @Repository. It typically extends Spring Data JPA interfaces like
JpaRepository.
5. model or entity Package: Contains POJOs or entity classes representing database
tables. These classes are annotated with @Entity.
6. config Package: Contains custom configuration classes annotated with
@Configuration, used for setting up beans or additional settings.
7. exception Package (Optional): Contains custom exceptions and error-handling logic.
Spring Boot encourages keeping the main application class in the root package so it can scan
all sub-packages automatically. This layered structure helps maintain a clean separation of
concerns and makes the application scalable, testable, and easier to navigate.
Q29. What do we understand by RESTful web services? In Spring Boot, what are its
advantages?
RESTful web services are web-based APIs built using REST (Representational State Transfer)
principles. They allow clients and servers to communicate using standard HTTP methods like
GET, POST, PUT, and DELETE. RESTful services are stateless, meaning each request from the
client must contain all necessary information to process the request.
In Spring Boot, building RESTful web services is straightforward using the @RestController,
@RequestMapping, and other related annotations. The framework handles content
negotiation, JSON serialization, dependency injection, and more without requiring
boilerplate code.
The advantages of building RESTful services with Spring Boot include:
1. Rapid Development: With auto-configuration and starter dependencies, setting up
REST APIs is fast and requires minimal setup.
2. Clear Annotations: Spring provides intuitive annotations like @GetMapping,
@PostMapping, @PutMapping, etc., which make code easier to understand.
3. Automatic JSON Conversion: Spring Boot automatically converts Java objects to
JSON using Jackson.
4. Error Handling: Built-in exception handling and support for custom
@ControllerAdvice help provide meaningful responses.
5. Easy Testing: REST APIs in Spring Boot can be easily tested using tools like Postman,
Curl, and Spring’s own testing support.
6. Integration Friendly: REST services can be consumed by any client that understands
HTTP, including web apps, mobile apps, or other APIs.
7. Scalability and Maintainability: Modular code structure and Spring’s dependency
injection make it easier to scale and maintain large REST APIs.
In summary, RESTful web services enable modern, platform-independent communication
over the web, and Spring Boot simplifies their creation and management with its robust
ecosystem and conventions.
@PutMapping("/{id}")
public String updateUser(@PathVariable int id, @RequestBody User user) {
// logic to update user
return "User with ID " + id + " updated successfully.";
}
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable int id) {
// logic to delete user
return "User with ID " + id + " deleted successfully.";
}
}
In this example, PUT /users/1 will update the user with ID 1, and DELETE /users/1 will delete
that user. This demonstrates how simple it is to build RESTful endpoints using Spring Boot’s
annotation-based style. You can test these endpoints using tools like Postman or Curl.
Q32. What is a REST controller?
In Spring Boot, a REST controller is a special type of controller that is used to develop
RESTful web services. It is a class annotated with @RestController, which is a combination of
@Controller and @ResponseBody. This means that the methods inside the class return data
directly as the HTTP response body, typically in JSON or XML format, rather than resolving to
a view.
REST controllers are part of the Spring Web module and are designed to handle HTTP
requests such as GET, POST, PUT, and DELETE. The methods inside a REST controller use
annotations like @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping to
map specific HTTP methods and URL paths.
The main difference between a regular controller (@Controller) and a REST controller
(@RestController) is that the latter returns serialized objects instead of HTML pages. This
makes @RestController ideal for developing APIs that will be consumed by front-end
applications, mobile apps, or other backend systems.
In short, a REST controller in Spring Boot is a powerful and convenient way to build APIs
using clear and concise annotations, reducing boilerplate and enabling rapid development of
web services.
Q33. Define the terms Request Body, Path Variable, and Request Parameter.
In the context of Spring Boot and RESTful APIs, Request Body, Path Variable, and Request
Parameter are mechanisms used to pass data from the client to the server in different parts
of an HTTP request.
Request Body refers to the part of the HTTP request that contains data sent by the client,
typically in JSON or XML format. In Spring, it is captured using the @RequestBody
annotation. This is commonly used in POST or PUT requests to send structured data like user
information or form inputs.
Path Variable is a dynamic part of the URL that represents a specific resource. It is used to
pass values within the URI path, and in Spring, it is captured using the @PathVariable
annotation. For example, in /users/5, the number 5 can be accessed as a path variable to
retrieve or update the user with ID 5.
Request Parameter refers to the key-value pairs passed in the URL query string (after ?).
These are typically used to filter or search data and are captured in Spring using the
@RequestParam annotation. For example, /users?name=John has a request parameter
name with the value John.
Each of these mechanisms is suited for specific use cases. Path variables are used to identify
resources, request bodies are used to send structured data, and request parameters are
used for filtering or optional inputs.
Q34. What is Request Mapping?
In Spring Boot, Request Mapping refers to the mechanism of mapping HTTP requests to
handler methods inside controller classes. This is done using the @RequestMapping
annotation or its specialized variants like @GetMapping, @PostMapping, @PutMapping,
and @DeleteMapping.
The @RequestMapping annotation can be used at both the class level and method level. At
the class level, it defines the base path for all methods inside that controller. At the method
level, it specifies the exact HTTP path and optionally the HTTP method (GET, POST, etc.) that
the method should respond to.
For example:
java
CopyEdit
@RequestMapping("/users")
public class UserController {
Q35. Explain GET, POST, PUT, DELETE APIs in the context of Spring Boot.
In Spring Boot, RESTful APIs follow standard HTTP methods such as GET, POST, PUT, and
DELETE, each serving a specific purpose in the context of managing resources.
GET is used to retrieve data from the server. It does not modify the resource and is safe and
idempotent. In Spring, it is mapped using @GetMapping. For example, GET /users fetches all
users, and GET /users/1 fetches a specific user by ID.
POST is used to create a new resource. It sends data to the server, usually in the request
body. It is mapped in Spring using @PostMapping. For example, POST /users with a user
object in the body creates a new user in the system.
PUT is used to update an existing resource. It replaces the entire resource or updates
specific fields. It is mapped using @PutMapping. For example, PUT /users/1 with updated
user data will update the user with ID 1.
DELETE is used to remove a resource from the server. It is mapped using @DeleteMapping.
For example, DELETE /users/1 will delete the user with ID 1 from the database.
Spring Boot makes handling these methods easy through clearly named annotations. Each of
these methods follows REST principles and is used to build CRUD operations in web services.
Q36. Explain the role of templates and view resolvers in Spring Boot web applications.
In Spring Boot web applications, templates and view resolvers play a critical role in
rendering HTML pages and delivering dynamic content to the user. They are part of the
presentation layer in MVC (Model-View-Controller) architecture.
Templates are the HTML files embedded with placeholders or expressions that are filled
dynamically with data from the controller. Spring Boot supports popular templating engines
like Thymeleaf, FreeMarker, and Mustache, with Thymeleaf being the most commonly used.
These templates are usually stored in the resources/templates directory. They allow you to
combine HTML with expressions like ${user.name} to render dynamic data on web pages.
View Resolvers are Spring components that map the view name returned by the controller
to an actual template file. When a controller method returns a view name like "home", the
view resolver looks for a file named home.html in the templates directory. Spring Boot
automatically configures a default view resolver when you use a supported template engine,
so you don’t need to configure it manually.
The process typically works like this: a controller handles the request, adds data to the
model, and returns a view name. The view resolver finds the corresponding template file,
renders it using the data in the model, and returns the final HTML to the browser.
In summary, templates define the structure of the output web page, while view resolvers
help locate and render these templates, ensuring that dynamic data is displayed to users
efficiently.
Q37. How can you use Spring Boot to build web applications?
Spring Boot simplifies the process of building web applications by providing an embedded
server, auto-configuration, and opinionated defaults that reduce setup and boilerplate code.
With Spring Boot, you can create web applications quickly, whether it's a simple static site, a
dynamic web app using templates, or a full RESTful API.
To build a web application using Spring Boot, you typically start by generating a project with
the Spring Web dependency using Spring Initializr. This dependency includes all the
necessary libraries for building a web application, including Spring MVC, Jackson for JSON
support, and an embedded Tomcat server.
Next, you define controllers using annotations like @Controller or @RestController to
handle incoming HTTP requests. For dynamic pages, you can use template engines like
Thymeleaf and create HTML templates in the src/main/resources/templates folder. For REST
APIs, you can return JSON responses directly from controller methods.
Spring Boot also supports form submissions, session management, validation, and file
uploads out-of-the-box. It provides auto-configuration for common use cases like error
handling, logging, and message conversion.
The project structure follows a clean MVC pattern with clearly separated layers for models,
views, and controllers. You can use @Service and @Repository layers to manage business
logic and database interactions, respectively.
Finally, by simply running the main application class (annotated with
@SpringBootApplication), the embedded server starts, and your application becomes
available on the default port (usually 8080). This makes deployment and testing much easier.
In conclusion, Spring Boot allows developers to build robust, scalable, and maintainable web
applications with minimal configuration and maximum flexibility, making it a popular choice
for both beginners and experienced developers.