Unit 4: Spring




SPRING CORE BASICS

Introduction to Spring Framework

Spring Framework is a lightweight, open-source Java framework used to build enterprise-level applications. It provides comprehensive infrastructure support and reduces complexity in Java development.

Key Features of Spring

  • Lightweight and modular
  • Loosely coupled architecture
  • Supports Dependency Injection (DI)
  • Simplifies enterprise application development

Spring Dependency Injection (DI) – Concepts

Dependency Injection is a design technique where objects are provided with their dependencies instead of creating them.

In simple words, Spring creates and manages objects and injects them where needed.

Problem without DI

Car car = new Car();

  • Tight coupling
  • Difficult to test and maintain

With DI

Car car = context.getBean(Car.class);

Types of Dependency Injection in Spring

TypeDescription
Constructor InjectionDependency provided through constructor
Setter InjectionDependency provided through setter method
Field InjectionDependency injected directly into fields

Example: Constructor Injection

public class Car { Engine engine; public Car(Engine engine) { this.engine = engine; } }

Advantages of Dependency Injection

  • Loose coupling
  • Better maintainability
  • Easy testing
  • Improved reusability

Spring Container

The Spring Container is responsible for:

  • Creating objects (beans)
  • Injecting dependencies
  • Managing bean life cycle

Types of Containers

ContainerDescription
BeanFactoryBasic container
ApplicationContextAdvanced container (commonly used)

DESIGN PATTERNS

A Design Pattern is a reusable solution to commonly occurring software design problems.

Why Design Patterns?

  • Provide standard solutions
  • Improve code quality
  • Promote best practices
  • Reduce development time

Types of Design Patterns

TypeExamples
CreationalFactory, Singleton
StructuralAdapter, Decorator
BehavioralStrategy, Observer

Factory Design Pattern

The Factory Design Pattern is a creational pattern that provides an interface for creating objects but allows subclasses or logic to decide which object to create.

When to Use Factory Pattern

  • Object creation logic is complex
  • Client should not know object creation details

Example

Step 1: Interface

interface Shape { void draw(); }

Step 2: Implementations

class Circle implements Shape { public void draw() { System.out.println("Drawing Circle"); } }

Step 3: Factory Class

class ShapeFactory { public Shape getShape(String type) { if(type.equals("CIRCLE")) return new Circle(); return null; } }

Step 4: Usage

ShapeFactory factory = new ShapeFactory(); Shape shape = factory.getShape("CIRCLE"); shape.draw();

Advantages

  • Loose coupling
  • Centralized object creation
  • Easy scalability

Strategy Design Pattern

The Strategy Design Pattern is a behavioral pattern that allows selecting an algorithm’s behavior at runtime.

Key Idea

  • Encapsulate algorithms
  • Make them interchangeable

Example

Step 1: Strategy Interface

interface PaymentStrategy { void pay(int amount); }

Step 2: Concrete Strategies

class CreditCardPayment implements PaymentStrategy { public void pay(int amount) { System.out.println("Paid using Credit Card"); } }
class UpiPayment implements PaymentStrategy { public void pay(int amount) { System.out.println("Paid using UPI"); } }

Step 3: Context Class

class ShoppingCart { PaymentStrategy strategy; public void setStrategy(PaymentStrategy strategy) { this.strategy = strategy; } public void checkout(int amount) { strategy.pay(amount); } }

Advantages

  • Avoids conditional statements
  • Open/Closed principle
  • Flexible behavior

Factory vs Strategy Pattern

Factory PatternStrategy Pattern
Object creationBehavior selection
Creational patternBehavioral pattern
Decides which object to createDecides how to perform task

Relation with Spring Framework

Spring FeatureDesign Pattern Used
Bean creationFactory Pattern
Dependency InjectionStrategy Pattern
ApplicationContextFactory + Singleton

Summary Table

TopicKey Concept
SpringEnterprise framework
DILoose coupling
Factory PatternObject creation
Strategy PatternRuntime behavior

Exam Tips

  • Always define DI clearly
  • Draw simple diagrams if allowed
  • Write advantages in bullet points
  • Compare Factory and Strategy patterns

Spring Inversion of Control (IoC)

Inversion of Control (IoC) is a principle where the control of object creation and dependency management is transferred from the programmer to the Spring container.

Instead of the developer creating objects, Spring creates and manages them.

Traditional Approach (Without IoC)

Car car = new Car();

  • Tight coupling
  • Difficult to test

Spring IoC Approach

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Car car = context.getBean(Car.class);

Role of IoC Container

  • Creates objects (beans)
  • Injects dependencies
  • Manages bean lifecycle

Types of IoC Containers

ContainerDescription
BeanFactoryBasic IoC container
ApplicationContextAdvanced container (recommended)

Aspect Oriented Programming (AOP)

AOP (Aspect Oriented Programming) is used to separate cross-cutting concerns from business logic.

Cross-Cutting Concerns

  • Logging
  • Security
  • Transaction management
  • Exception handling

AOP Terminology

TermMeaning
AspectCross-cutting logic
AdviceWhen action is executed
Join PointExecution point
PointcutExpression selecting join points
WeavingLinking aspect with target

Example Use

  • Logging method calls
  • Security checks before method execution

Bean Scopes in Spring

Bean Scope defines the lifecycle and visibility of a bean.

Types of Bean Scopes

ScopeDescription
SingletonOne object per Spring container (default)
PrototypeNew object for every request
RequestOne object per HTTP request
SessionOne object per HTTP session
ApplicationOne object per ServletContext
WebSocketOne object per WebSocket session

Scope Details

1. Singleton

  • Default scope
  • Same instance shared

2. Prototype

  • New instance every time

3. Request

  • Valid only in web applications

4. Session

  • One instance per user session

5. Application

  • One instance per application

6. WebSocket

  • One instance per WebSocket connection

Autowiring in Spring

Autowiring allows Spring to automatically inject dependencies without explicit configuration.

Autowiring Types

TypeDescription
byTypeMatch by class
byNameMatch by variable name
ConstructorInject via constructor
@AutowiredAnnotation-based

Example

@Autowired private Engine engine;

Advantages

  • Reduces boilerplate code
  • Improves readability

Spring Annotations

Annotations provide metadata to configure Spring applications.

Common Spring Annotations

AnnotationPurpose
@ComponentGeneric component
@ServiceService layer
@RepositoryDAO layer
@ControllerMVC controller
@AutowiredDependency injection
@QualifierResolve ambiguity
@ScopeDefine bean scope

Bean Life Cycle Callbacks

Spring manages the complete lifecycle of a bean.

Bean Lifecycle Phases

  1. Bean instantiation
  2. Dependency injection
  3. Initialization
  4. Destruction

Lifecycle Callback Methods

Using Interfaces

InitializingBean → afterPropertiesSet() DisposableBean → destroy()

Using Annotations

@PostConstruct @PreDestroy

Using XML

init-method="init" destroy-method="cleanup"

Bean Configuration Styles

Spring supports multiple configuration styles.

1. XML-Based Configuration

<bean id="car" class="com.Car"/>

2. Annotation-Based Configuration

@Component public class Car {}

3. Java-Based Configuration

@Configuration public class AppConfig { @Bean public Car car() { return new Car(); } }

Configuration Styles Comparison

StyleAdvantage
XMLClear separation
AnnotationsLess configuration
Java ConfigType-safe

Summary Table

TopicKey Concept
IoCContainer manages objects
AOPSeparation of concerns
Bean ScopesLifecycle control
AutowiringAutomatic DI
LifecycleInit & destroy
ConfigurationXML, Annotation, Java

Exam Tips

  • Always define IoC and AOP clearly
  • Write bean scopes in table format
  • Mention lifecycle phases
  • Compare configuration styles