OOPS With JAVA
Unit 5
Spring Framework Spring Boot
What is Spring Framework ?
Spring Framework is a powerful, lightweight Java framework used to build enterprise
applications.
It simplifies the development of Java applications by providing tools for
Connect different parts of app ( by Handling transactions, security
Manage Objects ( Beans )
dependency injections ) and database access
Why is it called a Powerful, Lightweight Java Framework?
Lightweight Powerful
Spring doesn't require a heavy application Despite being lightweight, it gives you powerful tools:
server (like JBoss or WebLogic)
IoC (Dependency Injection) – to connect app
You can run a Spring app using just a simple
components without tight coupling.
Tomcat server or even a plain Java application.
AOP (Aspect-Oriented Programming) – for
It uses POJOs (Plain Old Java Objects) — no
logging, security, and transaction control.
special base classes or complex structure Spring MVC – to build REST APIs and web
needed
needed apps.
What Are Enterprise Applications?
These apps often need:
Large-scale business apps used by companies, like:
Many users to access the system
Banking systems
Database connection
E-commerce platforms
Security
Complex business logic
Important Topics
Spring Core Basics
Spring Core is the heart of the Spring Framework. It provides the Inversion of Control
(IoC) container, which manages the creation, configuration, and lifecycle of beans
(objects managed by Spring). The IoC container reduces manual dependency management,
allowing developers to focus on business logic.
Key Points :
Core component of Spring Framework.
IoC container manages beans.
Beans are objects defined and managed by Spring.
ApplicationContext is the key interface to access beans.
Enables dependency injection for loose coupling.
Program example:
// MyBean.java
public class MyBean {
private String message;
public void setMessage(String message) { this.message = message; }
public void printMessage() { System.out.println(message); }
}
// Main.java
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
MyBean bean = context.getBean("myBean", MyBean.class);
bean.printMessage(); // Output: Hello, Spring!
Spring Dependency Injection Concepts
Dependency Injection (DI) is a design pattern where dependencies are provided to a
class rather than the class creating them itself. Spring supports constructor
injection, setter injection, and field injection, making applications modular and
testable.
Key Points:
DI removes hard-coded dependencies.
Types: Constructor, Setter, Field injection.
Promotes loose coupling and easier testing.
Uses @Autowired annotation in modern Spring.
Spring Inversion of Control
Inversion of Control (IoC) is a principle where the control of object creation is
transferred from the application to the Spring container. This reduces coupling and
allows Spring to manage object lifecycles.
Key Points :
IoC inverts control from code to container.
Spring container creates and manages beans.
Configurable via XML, annotations, or Java.
Foundation for dependency injection.
Program example :
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
@Component
public class MyService {
public void serve() {
System.out.println("Service running");
}
}
// Main.java
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
MyService service = context.getBean(MyService.class);
service.serve(); // Output: Service running
AKTU 2024 bcs403
Q. Explain difference between Dependency Injection ( DI ) and Inversion of
Control ( IOC ).
Dependency Injection ( DI ) Inversion of Control
DI is a specific implementation of IoC where IoC is a general principle where control over
1. Concept objects receive their dependencies from an program flow is inverted from the application to
external source (the container). a framework or container.
Instead of creating dependencies inside a class, It means the framework calls your code, not the
2. Role
they are injected into the class. other way around.
A UserService is injected with a
Instead of instantiating classes manually, the
3. Example UserRepository by Spring rather than creating
container does it for you.
it internally.
To increase modularity and make code easier to To decouple the execution flow from the
4 Purpose
test and maintain. implementation.
DI is achieved using annotations like @Autowired, Spring Framework is the IoC container managing
5. In Spring
@Inject, or through XML configuration. bean creation and wiring.
6. Who The container injects the dependencies into your The container (like Spring) controls object
provides? class. creation and lifecycle.
AKTU 2024 bcs403
Spring Container and Spring Bean Life Cycle
Spring Container
The Spring container is the key aspect of the Spring Framework
It is responsible for managing the lifecycle of application objects known as beans. It performs
the following key functions:
Bean Management: Creates, configures, and assembles beans based on configuration metadata
provided through XML, annotations, or Java configuration.
Dependency Injection: Injects dependencies into beans, ensuring that components are loosely
coupled and properly wired together.
Lifecycle Management: Oversees the entire lifecycle of beans, from instantiation to destruction.
There are two main implementations of the Spring container:
BeanFactory: A basic container that provides core dependency injection functionality.
ApplicationContext: An advanced container that extends BeanFactory, adding features like
event propagation, internationalization support, and integration with Spring's Aspect
-Oriented Programming (AOP).
Spring Bean Life Cycle
A bean is an object managed by the Spring container, and its life cycle consists of the steps it undergoes
from creation to destruction. The key phases are:
Phases of the Bean Life Cycle
Instantiation: The container creates an instance of the bean using its constructor or a
factory method.
Dependency Injection: The container populates the bean’s properties and injects its
dependencies as defined in the configuration.
Initialization: The container triggers initialization callbacks to prepare the bean for use.
These callbacks can be:
A method annotated with @PostConstruct.
The afterPropertiesSet() method if the bean implements the InitializingBean interface.
A custom init-method specified in the configuration.
Usage: The bean is fully initialized and available for the application to use.
Destruction: When the container shuts down, it calls destruction callbacks to clean up
the bean. These can be:
A method annotated with @PreDestroy.
The destroy() method if the bean implements the DisposableBean interface.
A custom destroy-method specified in the configuration.
Summary
Phase Description Key Points
Bean Definitions Load bean metadata from
Metadata ready for bean creation
Loading XML/Java/Annotations
Uses no-arg constructor, sets default
Bean Instatiation Create bean instance
values
Values from XML, settings, or
Bean Initialization Set configured property values
annotations
Bean Destruction Destroy bean and release resources Calls destroy methods
Aspect Oriented Programming
AOP addresses cross-cutting concerns (e.g., logging, security) by applying them separately from
business logic. Spring AOP uses proxies to execute these concerns at specific points.
Key Points
Separates concerns like logging.
Key terms: Aspect, Advice, Pointcut ( @Aspect, @Before, etc )
Program Example:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* MyService.*(..))")
public void logBefore() {
System.out.println("Method called!");
}
}
@Component
class MyService {
public void doWork() {
System.out.println("Working...");
}
}
Bean Scopes (Singleton, Prototype, Request, Session, Application)
Bean scopes determine the lifecycle and number of bean instances. Singleton (default) creates
one instance, Prototype creates new instances per request, and Request, Session, Application are
web-specific scopes.
Key Points
Singleton: 1 instance.
Prototype: New instance per request.
Request: Per HTTP request.
Session: Per user session.
Application: App-wide.
Program Example
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
@Component
@Scope("prototype")
public class PrototypeBean {
public void sayHello() {
System.out.println("Hello from Prototype: " + this);
}
}
@Component
@RequestScope
public class RequestBean {
public void sayHello() {
System.out.println("Hello from Request: " + this);
}
}
Web Socket
WebSocket enables real-time, bidirectional communication. Spring supports it with the spring-
websocket module, often using STOMP for structured messaging.
Key Points
Real-time, two-way communication.
@EnableWebSocket enables support.
STOMP simplifies messaging.
Used for chat, live updates.
Program Example
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyHandler(), "/chat");
}
}
public class MyHandler extends TextWebSocketHandler {
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws
Exception {
session.sendMessage(new TextMessage("Echo: " + message.getPayload()));
}
}
Auto Wiring
Autowiring automatically injects dependencies, reducing manual configuration. It can be done by
type, name, or constructor using @Autowired.
Key Points
Auto-injects beans.
Modes: byType, byName, constructor.
@Autowired on fields, setters, constructors.
@Qualifier resolves ambiguity.
Program Example
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyService {
private final MyRepository repository;
@Autowired
public MyService(MyRepository repository) {
this.repository = repository;
}
public void work() {
repository.save();
}
}
@Component
public class MyRepository {
public void save() {
System.out.println("Saving data");
}
}
Annotations
Spring uses annotations to simplify configuration. Common ones include @Component,
@Service, @Repository, and @Autowired.
Key Points:
Replaces XML config.
@Component: Generic bean.
@Service, @Repository: Specialized.
@Autowired: Dependency injection.
Program Example
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Repository;
import org.springframework.beans.factory.annotation.Autowired;
@Service
public class MyService {
@Autowired
private MyRepository repository;
public void work() {
repository.save();
}
}
@Repository
public class MyRepository {
public void save() {
System.out.println("Saving...");
}
}
Life Cycle Callbacks
Spring manages a bean’s lifecycle: creation, initialization, use, and destruction. Use
@PostConstruct for initialization and @PreDestroy for cleanup.
Key Points
Lifecycle: Create → Init → Use → Destroy.
@PostConstruct: After creation.
@PreDestroy: Before destruction.
Customizable lifecycle methods.
Program Example
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
@PostConstruct
public void init() {
System.out.println("Bean initialized");
}
@PreDestroy
public void cleanup() {
System.out.println("Bean destroyed");
}
}
Bean Configuration Styles
Spring supports three configuration styles: XML, Java-based, and annotation-based. Modern
projects prefer annotations or Java config.
Key points
XML: Verbose, external config.
Java: @Configuration, @Bean.
Annotations: @Component, etc.
Choose based on project needs.
Program Example
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
class MyBean {
public void sayHello() {
System.out.println("Hello from MyBean");
}
}
Spring Boot
Spring Boot Framework
Spring Boot is an extension of the Spring framework that simplifies the development of
production-ready applications. It provides pre-configured templates and conventions, reducing
manual setup and allowing developers to focus on business logic rather than boilerplate code.
Benefits of Spring Framework
features that make Spring Boot a powerful choice for rapid development of robust,
scalable applications.
Auto-configuration: Automatically configures the application based on included
dependencies, minimizing manual effort and ensuring a correct setup.
Embedded Servers: Includes built-in web servers (e.g., Tomcat, Jetty), eliminating the
need for external server deployment and simplifying development.
Starter Dependencies: Offers pre-packaged "starter" dependencies (e.g., spring-boot-
starter-web) that bundle common libraries for specific use cases, streamlining project
setup.
Production-Ready Features: Provides tools like health checks, metrics, and externalized
configuration, making it easier to manage and monitor applications in production.
Microservice Support: Ideal for building microservices, enabling the creation of small,
independent, and scalable services.
Spring Boot
Build Systems Code Structure Runners
Spring Boot Build Systems
Spring Boot uses Maven or Gradle for builds. It provides starter dependencies to
simplify setup and plugins to package apps as executable JARs.
Maven and Gradle are build automation tools used for java projects
Spring Boot, a framework that makes building Java applications faster and easier,
relies on tools like Maven or Gradle to handle the heavy lifting of builds and
dependency management.
Spring Boot Code Structure
Spring Boot projects have a standard structure. The main class uses
@SpringBootApplication, and sub-packages organize controllers, services, etc.
Folder Structure
Program Example
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyAppApplication {
public static void main(String[] args) {
SpringApplication.run(MyAppApplication.class, args);
}
}
Spring Boot Runners
Runners (CommandLineRunner, ApplicationRunner) execute code after the app starts,
useful for initialization tasks.
Program Example
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
public class MyRunner implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("App started with args: " + Arrays.toString(args));
}
}
Logger
Spring Boot uses SLF4J with Logback for logging. Configure levels (e.g., INFO, DEBUG) in
application.properties.
Program Example
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
private static final Logger log = LoggerFactory.getLogger(MyController.class);
@GetMapping("/test")
public String test() {
log.info("Test endpoint called");
return "Hello";
}
}
Building RESTful Web Services
Spring Boot simplifies REST API creation with annotations like @RestController,
@GetMapping, etc. It auto-configures JSON serialization with Jackson.
Key Points
@RestController for APIs.
Maps HTTP methods (GET, POST).
Jackson for JSON handling.
Quick REST setup.
Request Flow
[HTTP Request] --> [RestController] --> [JSON Response]
Program Example
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
Rest Controller
@RestController combines @Controller and @ResponseBody, returning data (e.g., JSON)
directly for REST APIs.
Key Points
@RestController = @Controller + @ResponseBody.
Returns JSON/XML.
No view rendering.
Core of REST APIs.
Program Example
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.List;
import java.util.Arrays;
@RestController
public class UserController {
@GetMapping("/users")
public List<String> getUsers() {
return Arrays.asList("Alice", "Bob");
}
}
Request Mapping
@RequestMapping maps HTTP requests to methods. It’s flexible, supporting specific
methods (GET, POST) at class or method level.
key Points
Maps URLs to methods.
Supports HTTP methods.
Class/method level.
Shortcuts like @GetMapping.
Visual Mapping table
URL Method Handler
/api/hello GET sayHello()
http://localhost:3000/api/hello
Program Example
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@RestController
@RequestMapping("/api")
public class MyController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello() {
return "Hello!";
}
}
Request Body
@RequestBody binds the HTTP request body (e.g., JSON) to a method parameter,
typically used in POST/PUT requests.
Key Points
Deserializes JSON to objects.
Used with @PostMapping.
Requires Jackson.
Handles payloads.
Program Example
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
@RequestMapping("/api")
public class UserController {
@PostMapping("/users")
public User createUser(@RequestBody User user) {
return user;
}
}
class User {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
Path Variable
@PathVariable extracts values from the URL path (e.g., /users/{id}), useful for dynamic
REST endpoints.
Key Points
Captures URL variables.
Used in paths like /users/{id}.
Optional with required=false.
Common in GET/DELETE.
Visual Url Breakdown
API integration/users/123 --> @PathVariable("id") = 123
Program Example
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/users/{id}")
public String getUser(@PathVariable("id") Long userId) {
return "User ID: " + userId;
}
}
Request Parameter
@RequestParam extracts query parameters from the URL (e.g., /search?name=John),
often used in GET requests.
Key Points
Extracts query params.
Used in GET requests.
Default values possible.
Optional with required=false.
Visial Url breakdown
/search?name=John --> @RequestParam("name") = "John"
Program Example
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
@RequestMapping("/api")
public class SearchController {
@GetMapping("/search")
public String search(@RequestParam("name") String name) {
return "Found: " + name;
}
}
GET, POST, PUT, DELETE APIs
These HTTP methods form the basis of REST APIs: GET (retrieve), POST (create), PUT
(update), DELETE (delete). Spring Boot maps them with annotations.
GET: Fetch data.
POST: Create data.
PUT: Update data.
DELETE: Remove data.
Program Example
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public String getUser(@PathVariable Long id) { return "User " + id; }
@PostMapping
public String createUser(@RequestBody String user) { return "Created: " + user; }
@PutMapping("/{id}")
public String updateUser(@PathVariable Long id, @RequestBody String user) { return
"Updated: " + user; }
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) { return "Deleted " + id; }
}
Subscribe Multi Atoms & Multi Atoms Plus
Join Telegram Channel
Follow us on Instagram (@multi.atoms)
For Notes Check Description