Object Oriented Programming With Java Unit 5
Object Oriented Programming With Java Unit 5
Unit-5
Section-A
4. What are the different types of Bean scopes in Spring? Explain any two. 2
Answer: In Spring, bean scopes define the lifecycle of beans within the application
context. There are primarily six bean scopes: Singleton, Prototype, Request, Session,
Application, and WebSocket. Two commonly used scopes are Singleton and Prototype.
1. Singleton:
This is the default scope in Spring.
Only one instance of the bean is created per Spring IoC container.
All requests for that bean will return the same instance.
Suitable for stateless beans or when sharing a single instance across multiple
components is acceptable.
2. Prototype:
A new bean instance is created every time the bean is requested from the
container.
Each request for the bean results in a fresh instance.
Ideal for stateful beans where maintaining separate state for each user or
component is necessary.
11. What is the difference between Singleton and Prototype bean scope in Spring? 2
Answer: The core difference between Singleton and Prototype bean scopes in Spring
lies in the number of instances created and their lifecycle management within the
Spring IoC container.
Singleton Scope:
Instance Creation:
Only one single instance of a bean defined with singleton scope is created per Spring
IoC container. This is the default scope for Spring beans.
Instance Sharing:
All subsequent requests for that bean will receive the exact same instance.
Lifecycle:
The singleton bean is initialized when the Spring container starts (or upon its first
request, depending on configuration) and remains in memory throughout the
application's lifetime until the container is shut down. Spring manages its entire
lifecycle, including initialization and destruction callbacks.
Use Case:
Ideal for stateless services, utility classes, or shared resources where only one
instance is needed across the entire application and can be safely shared by multiple
threads.
Prototype Scope:
Instance Creation:
A new instance of a bean defined with prototype scope is created every time it is
requested from the Spring container.
Instance Sharing:
Each request yields a distinct, independent instance.
Lifecycle:
Spring initializes the prototype bean upon request and performs any configured
initialization callbacks (like @PostConstruct). However, Spring does not manage the
complete lifecycle of prototype beans after creation. It does not track or destroy
them, meaning destruction callbacks (like @PreDestroy) are generally not invoked
by Spring for prototype-scoped beans.
Use Case:
Suitable for stateful beans where each consumer requires its own independent
instance, or when thread-safety concerns necessitate separate instances for each
operation.
12. What is Spring Boot and how is it different from the Spring Framework? 2
Answer: Spring Boot is an extension of the Spring Framework designed to simplify
the development of Spring-based applications. While Spring provides a foundational
framework for building Java applications, Spring Boot focuses on streamlining the
setup, configuration, and deployment processes, often with sensible defaults and
pre-configured components.
Spring Framework:
Provides a comprehensive set of tools and features for building enterprise-
level Java applications.
Offers dependency injection, aspect-oriented programming, data access, web
development, and more.
Requires explicit configuration of components and dependencies, often
through XML or annotations.
Flexibility is a key strength, allowing developers to tailor the framework to
specific project needs.
Spring Boot:
Built on top of the Spring Framework.
Aims to simplify development by providing sensible defaults and auto-
configuration.
Reduces boilerplate code and configuration, making it easier and faster to get
started.
Includes embedded servers (like Tomcat or Jetty), eliminating the need for
separate application server setup.
Simplifies dependency management with starter projects that include
common dependencies.
Offers features like auto-configuration, which automatically configures
components based on dependencies in the classpath.
Provides tools for monitoring and managing applications (Actuator)
15. Explain the use of @RequestParam and @PathVariable in RESTful Web Services. 2
Answer: In RESTful web services, @PathVariable and @RequestParam are used to
extract data from the incoming HTTP request, but they target different parts of the
URL. @PathVariable extracts values from the URI path itself,
while @RequestParam extracts values from the query parameters (the part after
the ? in the URL).
@PathVariable:
Purpose: Used to map parts of the URL path to method parameters.
Usage: When the resource identifier is part of the URL structure itself. For
example, in /users/{id}, @PathVariable("id") would extract the value
of id from the URL.
@RequestParam:
Purpose: Used to map query parameters to method parameters.
Usage: When you have optional parameters or want to filter data. For
example, in /products?
category=shoes&color=blue, @RequestParam("category") would extract the
value shoes and @RequestParam("color") would extract the value blue.
Section-B
Ques. Long Answer Type Questions Marks
No.
1. Explain Dependency Injection in Spring with suitable examples. Differentiate 7
between constructor and setter injection.
Answer: Dependency Injection (DI) in Spring is a core concept of the Inversion of
Control (IoC) principle, where the Spring IoC container manages the creation and
wiring of objects (beans) and their dependencies. Instead of objects creating their
own dependencies, they declare them, and the container "injects" them at
runtime. This promotes loose coupling, improved testability, and easier
maintenance.
Example of Dependency Injection in Spring:
Consider a UserService that depends on a UserRepository.
// UserRepository interface and implementation
public interface UserRepository {
void saveUser(String username);
}
3. Discuss various types of Bean scopes provided by Spring. Explain each with real- 7
world use cases.
Answer: Spring provides several bean scopes to manage the lifecycle and visibility
of beans within the application context. These scopes determine how many instances
of a bean are created and when they are available. The primary scopes are Singleton
(default), Prototype, Request, Session, Application, and WebSocket.
Here's a breakdown of each scope with real-world examples:
1. Singleton:
Behavior:
Only one instance of the bean is created per Spring container, and this single
instance is shared across the entire application.
Use Case:
Ideal for stateless services, utility classes, or components where sharing a single
instance doesn't lead to issues like data inconsistency. For example, a Logger class
or a UserAuthenticationService that handles authentication logic without
maintaining user-specific state.
Example:
A UserService bean configured with singleton scope. When multiple parts of the
application need to interact with user data, they will all use the same instance of
the UserService.
Benefits:
Reduces object creation overhead and conserves resources.
2. Prototype:
Behavior:
A new bean instance is created every time the bean is requested from the container.
Use Case:
Suitable for stateful beans that maintain their own data or when independent
instances are required for each use. For example, a shopping cart, a form bean, or a
data transfer object (DTO) that needs to be unique for each request.
Example:
A ShoppingCart bean configured with prototype scope. Each user accessing the
application will have their own independent ShoppingCart instance.
Benefits:
Ensures isolation and avoids unintended side effects when multiple parts of the
application need to interact with the bean.
3. Request:
Behavior: A new bean instance is created for each HTTP request.
Use Case: Designed for web applications, this scope is useful for handling
request-specific data like user preferences or data associated with a specific
form submission. It's not available with the regular Spring IoC containers.
Example: A RequestData bean configured with request scope, storing data
related to the current HTTP request.
Benefits: Enables request-specific data management within the application.
4. Session:
Behavior: A new bean instance is created for each HTTP session.
Use Case: Suitable for storing data related to a user's session, such as user
preferences or shopping cart items. It's also only available in web-aware
Spring ApplicationContext implementations.
Example: A UserPreferences bean configured with session scope, holding
user-specific settings.
Benefits: Simplifies session management in web applications.
5. Application:
Behavior:
A single bean instance is created for the entire lifecycle of the web application.
Use Case:
Useful for components that need to maintain state at the application level, such as a
global counter or an application-wide configuration object.
Example:
An ApplicationCounter bean configured with application scope, tracking the number
of active users in the application.
Benefits:
Enables management of application-wide data and resources.
6. WebSocket:
Behavior:
A new bean instance is created for each WebSocket session.
Use Case:
Used in WebSocket-based applications for managing user-specific state related to
the WebSocket connection. The instance is active throughout the entire WebSocket
session.
Example:
A WebSocketHandler bean that holds the WebSocket session and related data for a
specific user during a chat application.
Benefits:
Facilitates stateful WebSocket interactions and user-specific data management.
4. Write a detailed note on the lifecycle of a Spring Bean. How can we customize 7
initialization and destruction?
Answer: The lifecycle of a Spring Bean encompasses the stages a bean goes through
from its creation by the Spring IoC container to its eventual destruction. This process is
managed by Spring and allows for controlled initialization and cleanup.
Stages of the Spring Bean Lifecycle:
Instantiation:
The Spring container creates an instance of the bean, typically by invoking its
constructor.
Population of Properties:
Dependencies are injected into the bean, either through constructor injection or setter
injection, and its properties are set.
Aware Interfaces:
If the bean implements any "aware" interfaces
(e.g., BeanNameAware, BeanFactoryAware, ApplicationContextAware), the
corresponding callback methods are invoked by Spring to provide the bean with access
to specific container infrastructure objects.
BeanPostProcessors (Pre-Initialization):
BeanPostProcessor implementations can perform custom logic before the bean's
initialization callbacks are invoked.
Initialization:
The bean's initialization methods are called. This stage allows for custom setup logic
after properties are set and before the bean is ready for use.
BeanPostProcessors (Post-Initialization):
BeanPostProcessor implementations can perform custom logic after the bean's
initialization callbacks are invoked.
Ready for Use:
The fully initialized bean is now available in the Spring container and can be used by
other beans or components.
Destruction:
When the application context is shut down or the bean is no longer needed, Spring
invokes destruction callbacks for cleanup.
Customizing Initialization and Destruction:
Spring provides several mechanisms to customize initialization and destruction logic:
InitializingBean and DisposableBean Interfaces:
o Implement InitializingBean and override the afterPropertiesSet() method
for initialization logic.
o Implement DisposableBean and override the destroy() method for
destruction logic.
public class MyBean implements InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
// Initialization logic
}
@Override
public void destroy() throws Exception {
// Destruction logic
}
}
@PostConstruct and @PreDestroy Annotations:
oAnnotate a method with @PostConstruct for initialization.
oAnnotate a method with @PreDestroy for destruction.
public class MyBean {
@PostConstruct
public void init() {
// Initialization logic
}
@PreDestroy
public void cleanup() {
// Destruction logic
}
}
Custom init-method and destroy-method (XML Configuration):
o Specify init-method and destroy-method attributes in
the <bean> definition in XML configuration.
<bean id="myBean" class="com.example.MyBean" init-method="init" destroy-
method="cleanup"/>
@Bean Annotation with initMethod and destroyMethod (Java Configuration):
o When defining a bean using @Bean in a @Configuration class,
specify initMethod and destroyMethod attributes.
@Configuration
public class AppConfig {
@Bean(initMethod = "init", destroyMethod = "cleanup")
public MyBean myBean() {
return new MyBean();
}
}
5. Describe the different bean configuration styles in Spring (XML-based, Annotation- 7
based, and JavaConfig). Provide examples for each.
Answer: In the Spring Framework, beans can be configured in three main styles:
1. XML-Based Configuration
2. Annotation-Based Configuration
3. Java-Based Configuration (JavaConfig)
Each approach has its own use cases, and they can even be mixed in a project.
XML-Based Configuration
🔹 Description:
Bean definitions and dependencies are declared in an external XML configuration
file.
Example:
Bean Class:
java
CopyEdit
public class Car {
private Engine engine;
Annotation-Based Configuration
🔹 Description:
Uses annotations to define beans and their dependencies. Requires component
scanning.
Example:
Engine.java:
java
CopyEdit
@Component
public class Engine {
public String getType() {
return "Diesel Engine";
}
}
Car.java:
java
CopyEdit
@Component
public class Car {
private final Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
@Bean
public Engine engine() {
return new Engine();
}
@Bean
public Car car() {
return new Car(engine());
}
}
Main.java:
java
CopyEdit
ApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
Car car = context.getBean(Car.class);
car.drive();
6. Explain Autowiring in Spring. Discuss the different types of autowiring modes with 7
examples.
Answer: Autowiring in Spring is a mechanism for automatically resolving and
injecting dependencies between beans within the Spring application context. This
feature simplifies configuration by reducing the need for explicit dependency
declarations in XML or Java configuration.
Different Types of Autowiring Modes:
no (Default):
This is the default mode, where no autowiring is
performed. Dependencies must be explicitly configured
using <property> or <constructor-arg> in XML, or manually injected
in Java configuration.
byName:
Spring attempts to match a property's name in a bean with
the id or name of another bean in the container. If a bean with a
matching name is found, it is injected.
Example: If TextEditor has a SpellChecker property
named spellChecker, Spring will look for a bean
with id="spellChecker".
7. What is AOP (Aspect-Oriented Programming)? Explain key AOP concepts like Join 7
Point, Advice, Pointcut, Aspect with an example.
Answer: Aspect-Oriented Programming (AOP) is a programming paradigm that
enhances modularity by separating cross-cutting concerns, like logging, security,
and transaction management, from the core business logic of an application. AOP
allows these concerns to be modularized into reusable units called aspects, which
can be applied to specific points in the code (join points) without modifying the
original code.
Key AOP Concepts:
Join Point:
A specific point in the execution of a program where an aspect can be
applied. Examples include method execution, exception handling, or field access. In
Spring AOP, join points are typically method executions.
Advice:
The code that implements the cross-cutting concern. It defines what actions to take
at a join point. Examples of advice types include:
Before: Executes before the join point.
After: Executes after the join point, regardless of outcome.
AfterReturning: Executes after the join point only if the method
completes successfully.
AfterThrowing: Executes if the method throws an exception.
Around: Executes both before and after the join point, allowing for
full control over the join point's execution.
Pointcut:
A predicate or expression that matches a set of join points. It determines where the
advice should be applied. For example, a pointcut might specify that an advice
should be applied to all methods in a certain class or to all methods starting with a
specific prefix.
Aspect:
A modular unit that encapsulates a cross-cutting concern, including pointcuts and
advice. It defines what actions to take (advice) and where to take them (pointcut).
Example:
Let's say you want to log the execution time of all methods in a UserService class.
1. 1. Aspect:
You would create an aspect (e.g., LoggingAspect) to handle this logging
functionality.
2. 2. Pointcut:
You would define a pointcut that selects all methods within the UserService class
(e.g., execution(* com.example.UserService.*(..))).
3. 3. Advice:
You would write an around advice that captures the start time before the method
execution, executes the method, captures the end time, calculates the execution time,
and logs the information.
8. What are the advantages of using Spring Boot? Explain the internal architecture and 7
key components of a Spring Boot application.
Answer: Spring Boot simplifies Java application development by reducing
boilerplate code and configuration, enabling faster development and easier
deployment. Its core architecture revolves around auto-configuration, embedded
servers, and starter dependencies, facilitating the creation of standalone, production-
ready applications.
Advantages of Spring Boot:
Reduced Boilerplate Code:
Spring Boot minimizes the amount of manual configuration and repetitive code
required, allowing developers to focus on business logic.
Auto-configuration:
It automatically configures Spring components based on classpath dependencies,
simplifying setup and reducing configuration overhead.
Standalone Applications:
Spring Boot enables the creation of self-contained applications that can be run
directly using the java -jar command, eliminating the need for external application
servers.
Embedded Servers:
It includes embedded servers like Tomcat, Jetty, or Undertow, further simplifying
deployment and allowing for easy testing.
Starter Dependencies:
Spring Boot provides “starter” POMs that include pre-configured dependencies for
common web development tasks, streamlining project setup.
Production-Ready Features:
It offers built-in features like health checks, metrics, and externalized configuration,
making it easier to deploy and manage applications in production.
Easier Testing:
Spring Boot facilitates testing with features like embedded servers and testing
frameworks, allowing for rapid development and testing cycles.
Internal Architecture and Key Components:
Spring Boot applications typically follow a layered architecture, although it's
flexible and can be adapted to different needs.
Client Layer: Handles user interactions, often through web browsers or
other applications.
Presentation Layer (Controller): Receives requests from the client,
processes them, and returns responses. This layer often interacts with the
business layer to fulfill requests.
Business Layer (Service): Contains the core business logic and rules of the
application.
Data Access Layer (Repository): Manages interactions with the database,
often using frameworks like Spring Data JPA.
Model Layer (Entity): Represents the data structures used within the
application.
Database Layer: Stores and manages the application's data.
Key Components:
Spring Boot Starters:
Pre-packaged sets of dependencies that simplify the setup of common application
features.
Spring Boot Auto-configuration:
Automatically configures Spring components based on the dependencies available
on the classpath.
Spring Boot CLI:
A command-line interface for developing and deploying Spring Boot applications.
Spring Boot Actuator:
Provides features for monitoring and managing applications in production, such as
health checks and metrics.
9. Discuss the structure of a typical Spring Boot application. What is the role of the 7
main class with @SpringBootApplication annotation?
Answer: A typical Spring Boot application is structured with a main class annotated
with @SpringBootApplication, which serves as the entry point and orchestrates the
application's initialization and execution. This annotation combines three core
functionalities: @Configuration, @EnableAutoConfiguration,
and @ComponentScan.
Key Components and Structure:
Main Class:
The class containing the main() method, annotated with @SpringBootApplication, is
the starting point of the application. It's responsible for bootstrapping the Spring
context and launching the embedded web server.
Configuration (@Configuration):
This annotation indicates that a class declares one or more bean definitions (objects
managed by the Spring IoC container).
Auto-Configuration (@EnableAutoConfiguration):
This feature enables Spring Boot to automatically configure various components
based on the dependencies present in the classpath. For example, if a database driver
is present, it might automatically configure a connection pool.
Component Scanning (@ComponentScan):
This feature enables Spring to scan the classpath for classes annotated with
stereotypes like @Component, @Service, @Repository, and @Controller, and
register them as beans.
Application Layers:
While not mandatory, a typical Spring Boot application is often structured into
layers, such as:
Presentation Layer: Handles incoming requests, authentication, and
response formatting (e.g., REST controllers).
Business Layer: Contains the core business logic and validation
rules.
Persistence Layer: Interacts with the database (e.g., using Spring
Data JPA).
application.properties or application.yml:
These files are used to configure various aspects of the application, such as database
connections, server settings, and logging levels.
Role of @SpringBootApplication:
The @SpringBootApplication annotation significantly simplifies Spring Boot
development. It streamlines the application's setup by combining the functionality
of @Configuration, @EnableAutoConfiguration, and @ComponentScan.
Configuration: It declares the class as a source of bean definitions.
Auto-Configuration: It enables Spring Boot's auto-configuration
mechanism, automatically configuring components based on the classpath
and other settings.
Component Scanning: It triggers Spring to scan the application's base
package for components (e.g., controllers, services, repositories).
10. Explain the concept of Spring Boot starters and build systems like Maven and 7
Gradle. How do they simplify dependency management?
Answer: Spring Boot starters and build systems like Maven and Gradle are integral
to simplifying dependency management in Java development, particularly within the
Spring ecosystem.
Spring Boot Starters:
Spring Boot starters are a set of convenient dependency descriptors that bundle
together related libraries and their transitive dependencies. They offer a "one-stop
shop" for common functionalities, eliminating the need to manually declare
individual dependencies and manage version compatibility. For example, spring-
boot-starter-web provides all necessary dependencies for building web applications,
including Spring MVC, embedded Tomcat, and Jackson for JSON processing. This
significantly reduces boilerplate and configuration effort.
Build Systems (Maven and Gradle):
Maven and Gradle are powerful build automation tools for Java projects. They
manage the entire build lifecycle, including compiling code, running tests,
packaging applications, and, crucially, managing dependencies.
Dependency Management:
Both Maven and Gradle leverage repositories (like Maven Central) to download and
manage project dependencies. They handle transitive dependencies automatically,
meaning if your project depends on library A, and library A depends on library B,
the build system will automatically include library B.
Centralized Versioning:
They allow for centralized declaration of dependency versions, promoting
consistency across a project and its modules.
Dependency Resolution:
They resolve conflicts that may arise when different libraries require different
versions of the same transitive dependency, typically by favoring the highest version
or allowing explicit overrides.
Caching:
They cache downloaded dependencies locally, speeding up subsequent builds.
How they simplify dependency management:
Reduced Configuration:
Starters abstract away the complexity of declaring multiple individual dependencies,
while build systems automate the download and resolution process.
Version Compatibility:
Starters ensure a compatible set of library versions, and build systems handle
version conflicts, minimizing runtime issues.
Consistency and Reproducibility:
Centralized dependency management in build systems ensures consistent builds
across different environments and developers.
Automated Dependency Resolution:
Transitive dependencies are automatically managed, reducing manual effort and
potential errors.
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Executing CommandLineRunner with arguments:");
for (String arg : args) {
System.out.println(arg);
}
}
}
ApplicationRunner:
o This interface provides a run(ApplicationArguments args) method.
o It receives ApplicationArguments, which offers more structured
access to command-line arguments, including distinguishing between
option and non-option arguments.
o It is preferred when more sophisticated parsing or handling of
command-line arguments is required.
Example Usage:
Java
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Executing ApplicationRunner.");
System.out.println("Non-option arguments: " + args.getNonOptionArgs());
System.out.println("Option arguments: " + args.getOptionNames());
}
}
Both CommandLineRunner and ApplicationRunner can be used to perform
initialization tasks, and multiple runner beans can be defined within the same
application context. Their execution order can be controlled using
the Ordered interface or the @Order annotation.
12. How does Spring Boot handle logging? What is the role of Logback and how can 7
you configure it in Spring Boot?
Answer: Spring Boot handles logging by leveraging the Commons Logging API
internally, but it's designed to be flexible and allow you to choose your underlying
logging implementation. By default, it uses Logback when available, providing pre-
configured settings for console and file output. You can configure Logback using
XML or Groovy files (logback.xml, logback-spring.xml, logback.groovy, or
logback-spring.groovy) placed on the classpath, allowing you to customize logging
levels, appenders, and output formats.
Logback's Role:
Logback is a logging framework for Java that's designed to be a successor to Log4j,
offering improvements in performance and flexibility. It's the default logging
implementation in Spring Boot when available.
Configuring Logback in Spring Boot:
1. 1. Dependency:
If you're using Spring Boot starters (like spring-boot-starter-web), Logback is
included transitively, so you don't need to add a separate dependency.
2. 2. Configuration Files:
Spring Boot looks for specific configuration files on the classpath: logback-
spring.xml, logback.xml, logback-spring.groovy, or logback.groovy.
3. 3. Customization:
You can customize Logback through these configuration files to:
Set Logging Levels: Control the verbosity of logs (e.g., DEBUG,
INFO, WARN, ERROR).
Define Appenders: Specify where logs are output (e.g., console, file,
rolling file).
Format Log Output: Customize the appearance of log messages
with patterns that include timestamps, levels, class names, etc.
Implement Rolling File Appenders: Configure how log files are
rotated based on size, time, or other criteria.
4. 4. Overriding Default Configuration:
If you include a Logback configuration file, Spring Boot will use it to override its
default settings.
Example Configuration:
Code
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg
%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
This example defines a console appender and sets the root logger level to INFO,
meaning it will log messages at the INFO level and above (WARN, ERROR). You
can modify this to include a rolling file appender, change the log level for specific
packages, or customize the output format.
13. Explain how to build a RESTful web service using Spring Boot. Include the use of 7
@RestController, @RequestMapping, and HTTP methods.
Answer: Building a RESTful web service with Spring Boot primarily involves
creating controllers to handle HTTP requests and define API endpoints.
1. Project Setup:
Create a new Spring Boot project using Spring Initializr (start.spring.io).
Add the "Spring Web" dependency to enable web-related functionalities.
2. Creating a REST Controller:
Create a Java class to serve as your REST controller.
Annotate the class with @RestController. This annotation
combines @Controller and @ResponseBody, signifying that the class
handles incoming HTTP requests and its methods' return values should be
directly written to the HTTP response body (e.g., as JSON or XML).
3. Defining API Endpoints and Handling HTTP Methods:
@RequestMapping: This annotation maps HTTP requests to specific handler
methods or classes. It can be used at the class level to define a base URI path
for all endpoints within that controller, or at the method level to define
specific endpoint paths.
Java
@RestController
@RequestMapping("/api/products") // Base path for all product-related endpoints
public class ProductController {
// ...
}
HTTP Method-Specific Annotations: Spring Boot provides specialized
annotations for common HTTP methods, which are shortcuts
for @RequestMapping with a specific method attribute:
o @GetMapping: Handles HTTP GET requests. Used for retrieving
resources.
Java
@GetMapping // Maps to GET /api/products
public List<Product> getAllProducts() {
// ... return a list of products
}
@RestController
@RequestMapping("/api/items")
public class ItemController {
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
private String major;
import com.example.studentapi.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}
3. Student Service:
The service layer encapsulates business logic and interacts with the repository.
Java
package com.example.studentapi.service;
import com.example.studentapi.model.Student;
import com.example.studentapi.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
import com.example.studentapi.model.Student;
import com.example.studentapi.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/students")
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping
public List<Student> getAllStudents() {
return studentService.getAllStudents();
}
@GetMapping("/{id}")
public ResponseEntity<Student> getStudentById(@PathVariable Long id) {
return studentService.getStudentById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
public Student createStudent(@RequestBody Student student) {
return studentService.createStudent(student);
}
@PutMapping("/{id}")
public ResponseEntity<Student> updateStudent(@PathVariable Long id,
@RequestBody Student studentDetails) {
try {
Student updatedStudent = studentService.updateStudent(id, studentDetails);
return ResponseEntity.ok(updatedStudent);
} catch (RuntimeException e) {
return ResponseEntity.notFound().build();
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteStudent(@PathVariable Long id) {
studentService.deleteStudent(id);
return ResponseEntity.noContent().build();
}
}
This structure provides a clear separation of concerns, making the API maintainable
and scalable. Remember to configure
your application.properties or application.yml for database connectivity.
16. What is the use of @RequestBody in Spring Boot REST APIs? How does Spring 7
Boot automatically convert JSON to Java objects and vice versa?
Answer: The @RequestBody annotation in Spring Boot REST APIs is used to bind
the body of an HTTP request to a method parameter in a controller handler
method. This annotation instructs Spring to convert the incoming request body,
typically in formats like JSON or XML, into a specified Java object. This is crucial
for handling data sent from clients in the request body, commonly seen
in POST or PUT requests.
Spring Boot automatically converts JSON to Java objects and vice versa through the
use of HTTP Message Converters.
JSON to Java Object (Deserialization):
When a request with a Content-Type header indicating JSON
(e.g., application/json) is received, Spring Boot, by default, utilizes a
library like Jackson (or Gson if configured) to perform the
deserialization.
The MappingJackson2HttpMessageConverter is a common
implementation that handles this conversion.
The structure of the incoming JSON data is mapped to the fields of
the Java object annotated with @RequestBody. For this mapping to
be successful, the field names in the Java object should ideally match
the key names in the JSON document.
Java Object to JSON (Serialization):
Conversely, when a Java object is returned from a controller method
annotated with @ResponseBody, Spring Boot uses the same
underlying message converters (e.g., Jackson) to serialize the Java
object into a JSON response.
This serialized JSON is then sent back to the client as the HTTP
response body.
17. Describe the steps to handle form data and file uploads in a Spring Boot application. 7
Provide sample code.
Answer: Handling form data and file uploads in a Spring Boot application is a
common requirement in web apps. Below are the steps and a working example.
Steps to Handle Form Data and File Uploads
🔹 1. Add Dependencies
In pom.xml (for Maven):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
import java.io.File;
import java.io.IOException;
@Controller
public class UploadController {
@Value("${file.upload-dir}")
private String uploadDir;
@PostMapping("/submit")
public String handleFormSubmit(
@ModelAttribute FormData formData,
@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes
){
try {
// Save file
File dest = new File(uploadDir + file.getOriginalFilename());
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
redirectAttributes.addFlashAttribute("message", "File upload failed!");
}
return "redirect:/form";
}
@GetMapping("/form")
public String showForm() {
return "form"; // thymeleaf template name
}
}
18. How does Spring Boot handle application configuration using application.properties 7
or application.yml files?
Answer: Spring Boot externalizes application configuration primarily
through application.properties or application.yml files, typically located in
the src/main/resources directory. This mechanism allows for flexible environment-
specific settings without modifying the application's code.
Key Aspects of Handling Configuration:
Automatic Loading:
Spring Boot automatically detects and loads properties
from application.properties or application.yml (and their profile-specific variants
like application-dev.properties).
Property Formats:
application.properties: Uses a simple key-value pair format
(e.g., server.port=8080).
application.yml: Employs YAML syntax, which is more human-
readable and supports hierarchical structures, lists, and maps
(e.g., server: port: 8080).
Property Source Hierarchy:
Spring Boot loads properties from various sources in a defined order, allowing for
overrides. Command-line arguments typically take precedence, followed by
environment variables, and then the application.properties or application.yml files. If
both application.properties and application.yml are present and define the same
property, application.properties takes precedence.
Accessing Properties:
@Value Annotation: Properties can be injected directly into Spring
components using the @Value annotation (e.g., @Value("$
{server.port}") private int port;).
@ConfigurationProperties Annotation: For more complex or grouped
configurations, a dedicated configuration class can be created and
annotated with @ConfigurationProperties, mapping properties to
fields (e.g., @ConfigurationProperties("my.service") public class
MyServiceProperties { ... }).
Profiles:
Spring Boot supports environment-specific configurations using profiles. By
creating files like application-dev.properties or application-prod.yml, different
property sets can be activated based on the active Spring profile, enabling seamless
deployment across various environments.
19. What is the difference between traditional Spring web application and a Spring Boot 7
web application? Explain with architecture.
Answer: Spring Boot simplifies and accelerates web application development
compared to traditional Spring. Spring Boot achieves this by automating much of
the configuration and setup, including dependency management and embedded
server deployment, whereas traditional Spring requires more manual configuration
and external server setup.
Traditional Spring Web Application:
Architecture:
Follows a layered architecture (e.g., Presentation, Business, Data Access layers)
with clear separation of concerns. Requires manual configuration for beans,
component scanning, and dependency management.
Configuration:
Relies heavily on XML-based configuration or Java-based configuration (using
annotations).
Deployment:
Typically deployed as a WAR file to an external application server (like Tomcat or
Jetty).
Dependencies:
Developers manually manage dependencies (JAR files) using tools like Maven or
Gradle.
Development Speed:
Slower development cycle due to the need for manual configuration and external
server setup.
Example:
A typical Spring web application would involve setting up a web server (like
Tomcat), configuring a DispatcherServlet, defining beans in XML or using
annotations, and managing dependencies.
Spring Boot Web Application:
Architecture:
Leverages the Spring Framework's layered architecture, but with added features for
rapid development. Spring Boot uses "starters" to manage dependencies and
autoconfiguration to simplify configuration.
Configuration:
Employs autoconfiguration, which automatically configures the application based on
its dependencies. This minimizes manual configuration and boilerplate code.
Deployment:
Can be deployed as a standalone JAR file with an embedded web server (e.g.,
Tomcat, Jetty, Undertow), simplifying deployment.
Dependencies:
Uses "starters," which are pre-packaged sets of dependencies that simplify
dependency management and avoid version conflicts.
Development Speed:
Offers faster development and prototyping due to its autoconfiguration, embedded
servers, and starter dependencies.
Example:
A Spring Boot application can be created with a
simple @SpringBootApplication annotated class and a main method. Spring Boot
handles the rest, including embedding a server and configuring the application
context.
Key Differences Summarized:
Feature Traditional Spring Spring Boot
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic"); // Enable a simple in-memory message
broker
config.setApplicationDestinationPrefixes("/app"); // Prefix for messages to be
routed to methods with @MessageMapping
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat").withSockJS(); // Define the WebSocket endpoint
}
}
Java
// ChatController.java
@Controller
public class ChatController {