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
- Tight coupling
- Difficult to test and maintain
With DI
Types of Dependency Injection in Spring
| Type | Description |
|---|---|
| Constructor Injection | Dependency provided through constructor |
| Setter Injection | Dependency provided through setter method |
| Field Injection | Dependency injected directly into fields |
Example: Constructor Injection
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
| Container | Description |
|---|---|
| BeanFactory | Basic container |
| ApplicationContext | Advanced 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
| Type | Examples |
|---|---|
| Creational | Factory, Singleton |
| Structural | Adapter, Decorator |
| Behavioral | Strategy, 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
Step 2: Implementations
Step 3: Factory Class
Step 4: Usage
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
Step 2: Concrete Strategies
Step 3: Context Class
Advantages
- Avoids conditional statements
- Open/Closed principle
- Flexible behavior
Factory vs Strategy Pattern
| Factory Pattern | Strategy Pattern |
|---|---|
| Object creation | Behavior selection |
| Creational pattern | Behavioral pattern |
| Decides which object to create | Decides how to perform task |
Relation with Spring Framework
| Spring Feature | Design Pattern Used |
|---|---|
| Bean creation | Factory Pattern |
| Dependency Injection | Strategy Pattern |
| ApplicationContext | Factory + Singleton |
Summary Table
| Topic | Key Concept |
|---|---|
| Spring | Enterprise framework |
| DI | Loose coupling |
| Factory Pattern | Object creation |
| Strategy Pattern | Runtime 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)
- Tight coupling
- Difficult to test
Spring IoC Approach
Role of IoC Container
- Creates objects (beans)
- Injects dependencies
- Manages bean lifecycle
Types of IoC Containers
| Container | Description |
|---|---|
| BeanFactory | Basic IoC container |
| ApplicationContext | Advanced 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
| Term | Meaning |
|---|---|
| Aspect | Cross-cutting logic |
| Advice | When action is executed |
| Join Point | Execution point |
| Pointcut | Expression selecting join points |
| Weaving | Linking 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
| Scope | Description |
|---|---|
| Singleton | One object per Spring container (default) |
| Prototype | New object for every request |
| Request | One object per HTTP request |
| Session | One object per HTTP session |
| Application | One object per ServletContext |
| WebSocket | One 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
| Type | Description |
|---|---|
| byType | Match by class |
| byName | Match by variable name |
| Constructor | Inject via constructor |
| @Autowired | Annotation-based |
Example
Advantages
- Reduces boilerplate code
- Improves readability
Spring Annotations
Annotations provide metadata to configure Spring applications.
Common Spring Annotations
| Annotation | Purpose |
|---|---|
| @Component | Generic component |
| @Service | Service layer |
| @Repository | DAO layer |
| @Controller | MVC controller |
| @Autowired | Dependency injection |
| @Qualifier | Resolve ambiguity |
| @Scope | Define bean scope |
Bean Life Cycle Callbacks
Spring manages the complete lifecycle of a bean.
Bean Lifecycle Phases
- Bean instantiation
- Dependency injection
- Initialization
- Destruction
Lifecycle Callback Methods
Using Interfaces
Using Annotations
Using XML
Bean Configuration Styles
Spring supports multiple configuration styles.
1. XML-Based Configuration
2. Annotation-Based Configuration
3. Java-Based Configuration
Configuration Styles Comparison
| Style | Advantage |
|---|---|
| XML | Clear separation |
| Annotations | Less configuration |
| Java Config | Type-safe |
Summary Table
| Topic | Key Concept |
|---|---|
| IoC | Container manages objects |
| AOP | Separation of concerns |
| Bean Scopes | Lifecycle control |
| Autowiring | Automatic DI |
| Lifecycle | Init & destroy |
| Configuration | XML, Annotation, Java |
Exam Tips
- Always define IoC and AOP clearly
- Write bean scopes in table format
- Mention lifecycle phases
- Compare configuration styles