OOPs With Java
Unit: - 5
Spring framework & Spring Boot
Spring framework
Spring Framework is a powerful, lightweight Java-based
framework used to develop enterprise-level
applications.
It provides comprehensive infrastructure support for
developing Java applications.
The core feature of Spring is Dependency Injection (DI)
and Aspect-Oriented Programming (AOP), which makes
it easier to manage and decouple components.
Modules of Spring Framework:
1.Spring Core – Provides the core functionality including
Dependency Injection.
2.Spring AOP – Aspect-Oriented Programming to
separate cross-cutting concerns (like logging).
3.Spring MVC – For building web applications using the
Model-View-Controller pattern.
4.Spring JDBC – Simplifies database access using JDBC.
5.Spring ORM – Integration with ORM tools like
Hibernate, JPA, etc.
6.Spring Security – For authentication and authorization.
7.Spring Boot – Simplifies project setup with auto-
configuration and embedded servers.
8.Spring Cloud – For building scalable, distributed
systems in the cloud.
Features:
1. Lightweight
2. Dependency Injection (DI)
3. Aspect-Oriented Programming (AOP)
4. Transaction Management
5. MVC Framework
Dependency Injection (DI) in Spring Framework
Dependency Injection (DI) is a design pattern used to
remove the tight coupling between components by
injecting dependencies from the outside rather than
creating them inside the class.
In Spring Framework, DI is one of the core features that
helps manage object creation and their dependencies
automatically.
Types of Dependency Injection in Spring:
1. Constructor Injection
@Component
class Engine {}
@Component
class Car {
private Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
}
2. Setter Injection
@Component
class Car {
private Engine engine;
@Autowired
public void setEngine(Engine engine) {
this.engine = engine;
}
}
3. Field Injection
@Component
class Car {
@Autowired
private Engine engine;
}
IOC (Inversion of Control) in Spring Framework
Inversion of Control (IoC) is a principle in software engineering
where the control of object creation and dependency
management is transferred from the program itself to a
framework or container.
In the Spring Framework, IoC is implemented using the
Dependency Injection (DI) mechanism.
It allows the framework (Spring container) to take control of
creating objects and injecting their dependencies, instead of
having the application code do it manually.
Traditional Programming vs IoC
Traditional Approach IoC Approach
Class creates its own Dependencies are
dependencies using new provided by Spring
keyword container
Tight coupling between Loose coupling
classes
Hard to test and maintain Easy to test and flexible
How IoC Works in Spring
The Spring IoC Container is responsible for:
o Instantiating beans (objects)
o Configuring them
o Wiring dependencies
o Managing their life cycle
This is usually done via:
o XML Configuration
o Java Annotations (@Component, @Autowired, etc.)
o Java Configuration Class (@Configuration, @Bean)
Advantages of IoC in Spring
1. Loose Coupling
2. Easier Testing
3. Better Code Reusability
4. Easy to Manage
5. Configurable
AOP (Aspect-Oriented Programming) in Spring Framework
AOP (Aspect-Oriented Programming) is a programming
paradigm that allows you to separate cross-cutting concerns
from your main business logic.
In simple terms, AOP helps you write cleaner code by
separating common behaviours like logging, security,
transactions, etc., from your core logic — without repeating
them everywhere.
Core Concepts of AOP in Spring:
Term Description Example
Aspect A module that encapsulates a cross-cutting concern A logging module
The action taken by an aspect at a particular join A method executed
Advice
point before/after
Join A point in the execution of a program (e.g., method
Any method execution
Point call)
Pointcut An expression that selects one or more join points All methods in a package
Linking aspects with main logic at runtime or Done by Spring AOP at
Weaving
compile-time runtime
A wrapper around your original object that includes
Proxy Spring uses proxies for this
AOP advice
Benefits of AOP in Spring:
Benefit Explanation
Separation of
Keeps business logic clean and focused
concerns
Common code like logging written once,
Code reusability
applied everywhere
Easier maintenance Update cross-cutting logic in one place
Improved Removes repeated code blocks from business
readability classes
Bean Scopes in Spring
In Spring Framework, bean scopes define the lifecycle
and visibility of beans in the context of an application.
A scope determines how many instances of a bean will
be created and how they are shared.
Spring supports the following types of bean scopes:
1. Singleton (Default Scope)
Description: Only one instance of the bean is created for
the entire Spring container.
Use Case: When you want to share the same instance
across the application.
Defined As:
@Scope("singleton")
Behavior:
o Created at container startup (eager loading).
o Same object returned on every request for that
bean.
2. Prototype
Description: A new instance is created each time the
bean is requested from the container.
Use Case: When you need a fresh instance for each
request.
Defined As:
@Scope("prototype")
Behaviour:
o Created on demand.
o Spring does not manage the complete lifecycle after
instantiation.
3. Request (Web-aware scope)
Description: One instance per HTTP request. Valid only
in web-aware applications.
Use Case: When a bean should serve one HTTP request.
Defined As:
@Scope("request")
Behaviour:
o A new bean instance is created for each request
and discarded afterward.
4. Session
Description: One instance per HTTP session.
Use Case: For user session-based data.
Defined As:
@Scope("session")
Behaviour:
o Bean is tied to the lifecycle of the user’s session.
5. Application
Description: One instance per ServletContext.
Use Case: When a bean is needed across the entire web
application.
Defined As:
@Scope("application")
Behaviour:
o Shared across all sessions and requests in a web
app.
6. WebSocket
Description: One instance per WebSocket session.
Use Case: For stateful WebSocket communications.
Defined As:
@Scope("websocket")
Behaviour:
o Exists throughout a WebSocket session.
Auto-wiring in Spring
Autowiring in Spring is the process of automatically
injecting dependencies into a bean without explicitly
specifying them in the configuration (XML or Java-
based).
It simplifies bean wiring by letting Spring resolve and
inject the required beans automatically.
Why Autowiring?
Traditionally, beans were configured like this (manual
wiring):
<bean id="car" class="com.example.Car">
<property name="engine" ref="engine"/>
</bean>
With auto wiring, Spring can automatically match and
inject the engine bean into car without explicitly
defining the property.
Benefits of Autowiring
Reduces boilerplate XML/Java configuration.
Promotes loose coupling between components.
Simplifies unit testing and mocking.
Encourages dependency injection best practices.
Annotations in Spring
Annotations in Spring are metadata used to
configure and manage beans and their
dependencies in a more concise and declarative
way. They reduce boilerplate XML configuration and
make the code more readable and maintainable.
Commonly Used Spring Annotations
1.Component Scanning & Bean Declaration
Annotation Description
Declares a class as a
@Component Spring-managed bean
Specialized
@Service @Component for
service layer
Specialized
@Repository @Component for
DAO/persistence
Marks a class as a web
@Controller controller (Spring MVC)
Shortcut for
@RestController @Controller +
@ResponseBody
2.Dependency Injection
Annotation Description
Automatically injects dependencies
@Autowired by type
Resolves ambiguity when multiple
@Qualifier beans match
@Inject JSR-330 equivalent of @Autowired
Injects values from properties or
@Value literals
3.Configuration and Bean Definition
Annotation Description
Marks a class as source of bean
@Configuration definitions
Declares a bean method inside
@Bean @Configuration
Tells Spring to scan packages for
@ComponentScan components
Lifecycle Callbacks in Spring
1. InitializingBean and DisposableBean Interfaces
a) InitializingBean
Method: afterPropertiesSet()
Called after all properties are set by Spring.
@Component
public class MyBean implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception
{
System.out.println("Bean initialized
(afterPropertiesSet)");
}
}
b) DisposableBean
Method: destroy()
Called just before the bean is destroyed.
@Component
public class MyBean implements DisposableBean {
@Override
public void destroy() throws Exception {
System.out.println("Bean destroyed
(destroy)");
}
}
Different bean configuration styles in spring
1. XML-Based Configuration (Traditional Style)
Configuration is defined in an XML file (e.g.,
applicationContext.xml).
Useful for separation of concerns between code and
configuration.
🔹 Example:
xml
<bean id="car" class="com.example.Car">
<property name="engine" ref="engine"/>
</bean>
<bean id="engine" class="com.example.Engine"/>
2. Annotation-Based Configuration
Uses annotations like @Component, @Autowired, etc.,
directly in the Java code.
Requires component scanning to detect annotated
classes.
🔹 Example:
@Component
public class Engine {}
@Component
public class Car {
@Autowired
private Engine engine;
}
3. Java-Based Configuration (@Configuration +
@Bean)
Configuration is done using pure Java code instead of
XML.
Gives full control over bean creation logic.
🔹 Example:
@Configuration
public class AppConfig {
@Bean
public Engine engine() {
return new Engine();
}
@Bean
public Car car() {
return new Car(engine());
}
}
Dependency Management Helps in a Spring
Boot System
1. Automatic Version Management
You don’t need to specify versions for most
dependencies. Spring Boot manages them
based on the version of Spring Boot you're
using.
2. Prevents Dependency Conflicts
Spring Boot's BOM ensures that all modules use
compatible versions of Spring and third-party libraries.
Prevents version mismatches like one dependency
needing Jackson 2.13 and another needing 2.14.
3. Simplifies Build Files
You include starters (like spring-boot-starter-data-jpa,
spring-boot-starter-security) instead of listing individual
dependencies.
Starters bundle all required dependencies in a
consistent, tested set.
4. Supports Custom Dependency Management
You can override or define your own dependency
versions using the <dependencyManagement> section
in Maven or dependencyManagement block in Gradle.
5. Consistency Across Environments
With managed dependencies, all developers and CI/CD
environments use the same dependency versions,
reducing “it works on my machine” problems.
6. Integration with Spring Initializer
Spring Initializer generates projects with pre-configured
managed dependencies, helping you start quickly and
correctly.
Code Structure in Spring Boot Application
Spring Boot follows a standard project structure to
support convention over configuration, making the
development process faster, more organized, and
easier to maintain.
1. Main Application Class
It is the entry point of the Spring Boot application.
Annotated with @SpringBootApplication, which
combines:
o @Configuration
o @EnableAutoConfiguration
o @ComponentScan
It contains the main() method to launch the application.
Example:
@SpringBootApplication
public class MyAppApplication {
public static void main(String[] args) {
SpringApplication.run(MyAppApplication.class,
args);
}
}
2. Controller Layer
Handles HTTP requests and returns responses.
Annotated with @RestController or @Controller.
Maps endpoints using annotations like @GetMapping,
@PostMapping, etc.
Example:
@RestController
public class UserController {
@GetMapping("/users")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
}
3. Service Layer
Contains business logic of the application.
Annotated with @Service.
Called by controller classes.
Example:
@Service
public class UserService {
public List<User> getAllUsers() {
// Business logic
}
}
4. Repository Layer
Handles database operations.
Interfaces extend JpaRepository or CrudRepository.
Annotated with @Repository.
Example:
Repository
public interface UserRepository extends
JpaRepository<User, Long> {}
5. Model or Entity Layer
Contains POJO or Entity classes that represent database
tables.
Annotated with @Entity, @Id, @GeneratedValue, etc.
Example:
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
}
RESTful Web Services in Spring Boot
RESTful Web Services means using Spring Boot to create
API endpoints that follow REST (Representational State
Transfer) principles.
It lets different applications communicate over HTTP in a
simple, lightweight, and scalable way.
Spring Boot Support:
Spring Boot provides @RestController, @GetMapping,
@PostMapping, etc., which makes developing REST API
very easy.
It converts Java Objects to JSON or XML automatically.
Advantages:
1.Simplicity:
Annotations like @RestController make code much
simpler and clear.
2.Rapid Development:
Spring Boot handles configuration and boilerplate code,
allowing you to focus on business functionality.
3.Scalable:
Easily handle large amounts of requests with
lightweight, stateless services.
Platform-Independent:
Allows communication between different platforms
(Java, .NET, Python) over HTTP.
4.JSON Format:
By default, Spring converts Java Objects to JSON, which
is lightweight and widely supported.
5.Easy Integration:
Integrates smoothly with Spring components like
Security, Validation, and Data Access.
@RestController & @RequestMapping
@RestController is a Spring annotation that marks a
class as a controller which handles REST API requests.
It combines @Controller and @ResponseBody.
That means:
All methods in the controller return the actual data (like
JSON or text) instead of view names.
Example:
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello(){
return "Hello from Spring Boot!";
}
}
@RequestMapping is an annotation used to map URL
patterns to controller methods or classes.
It specifies the path and the HTTP method (GET, POST,
PUT, etc.).
Example:
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/users")
public List<String> getAllUsers(){
return List.of("Alice", "Bob", "Charlie");
}
}
GET, POST, PUT, and DELETE in context to Spring Boot
1.GET API:
Purpose: Retrieve or read existing resources.
Spring Annotation: @GetMapping
Example:
@RestController
@RequestMapping("/students")
public class StudentController {
@GetMapping
public List<String> getAllStudents(){
return List.of("Alice", "Bob", "Charlie");
}
}
2.POST API:
Purpose: Create or add a new resource.
Spring Annotation: @PostMapping
@RequestBody: converts incoming JSON into Java
object.
Example:
@RestController
@RequestMapping("/students")
public class StudentController {
@PostMapping
public String addStudent(@RequestBody String
student){
// Here we would normally save student to
database
return "Student added: " + student;
}
}
PUT API:
Purpose: Update an existing resource.
Spring Annotation: @PutMapping
@PathVariable: specifies which resource to update.
Example:
@RestController
@RequestMapping("/students")
public class StudentController {
@PutMapping("/{id}")
public String updateStudent(@PathVariable int id,
@RequestBody String student){
// Update student with given id
return "Student " + id + " updated to " + student;
}
}
DELETE API:
Purpose: Remove or delete a resource.
Spring Annotation: @DeleteMapping
Example:
@RestController
@RequestMapping("/students")
public class StudentController {
@DeleteMapping("/{id}")
public String deleteStudent(@PathVariable int id){
// Delete student with given id
return "Student " + id + " removed.";
}
}