Java Spring Framework: High-Level Introduction
Target Audience: Beginning Java developers (comfortable with Java basics: classes, objects, interfaces, basic OOP)
Duration: 60 minutes
Objective: Understand what Spring is, why it matters, and the foundational concepts that underpin the entire framework
Opening: Why Spring Matters (5 minutes)
Key Message: Spring solves real problems that appear in enterprise Java applications.
Imagine you’re building a web application with a database. Without Spring, you’d need to:
- Create database connections manually
- Manage object lifecycle (when to create, when to destroy)
- Wire components together by hand
- Write lots of boilerplate code for configuration
- Handle cross-cutting concerns (logging, transactions) repetitively
Spring automates these tasks, letting you focus on business logic.
Analogy: Spring is like a factory supervisor for your Java objects. Instead of creating and managing every part yourself, the supervisor handles hiring (creation), scheduling (lifecycle), and assigning work (injection).
Historical Context: Spring emerged around 2004 as a response to the complexity of Enterprise JavaBeans (EJB). It’s now the de facto standard for Java enterprise applications.
Section 1: Core Concepts (15 minutes)
Inversion of Control (IoC)
Traditional Approach (Your Code Controls Flow):
Your code explicitly creates objects
MyService service = new MyService();
service.doSomething();
Your code directly instantiates and manages objects. You’re in control.
Spring Approach (Framework Controls Flow):
Spring creates objects automatically
@Autowired
private MyService service; // Spring injects this
Spring creates objects and injects them when needed. The framework is in control.
Why This Matters: Decoupling. Your code doesn’t need to know how to construct dependencies—just use them. Makes testing easier (you can inject mock objects) and code more flexible.
Dependency Injection (DI)
The Core Pattern: Classes receive their dependencies rather than creating them.
Three Ways to Inject:
- Constructor Injection (Recommended)
public class OrderService { private final DatabaseRepository db; public OrderService(DatabaseRepository db) { this.db = db; // dependency provided from outside } } - Setter Injection
public class OrderService { private DatabaseRepository db; public void setDatabase(DatabaseRepository db) { this.db = db; } } - Field Injection (Least recommended in modern Spring)
@Autowired private DatabaseRepository db;
Why This Matters: Dependencies are explicit (constructor injection makes them obvious), classes are loosely coupled, and testing becomes trivial—inject a mock instead of the real database.
The Spring Container (Application Context)
Think of this as Spring’s factory floor.
What it does:
- Reads configuration (annotations, XML, properties)
- Creates objects (called “beans”)
- Manages their lifecycle (creation → initialization → destruction)
- Injects dependencies
- Makes beans available to your application
Lifecycle: Spring boots up → creates all beans → injects dependencies → application runs → Spring shuts down.
Key Point: You don’t manually create most objects; Spring does based on configuration.
Section 2: Spring Architecture (12 minutes)
The Spring Ecosystem
Spring is actually multiple frameworks working together:
Spring Core: The foundation—IoC container, dependency injection, bean management
Spring Data: Simplifies database access with repositories and query methods
Spring Web/Spring MVC: Builds web applications and REST APIs
Spring Security: Authentication and authorization
Spring Boot: Makes Spring applications easy to start (auto-configuration, embedded servers)
Spring Cloud: Distributed systems, microservices features
Key Insight: You typically use Spring Core plus specialized modules. You rarely need the entire ecosystem.
Traditional Spring vs. Spring Boot
Traditional Spring (Pre-2014):
- Lots of XML configuration
- Manual setup of servers
- Many dependencies to manage
- Significant boilerplate
Spring Boot (Modern Standard):
- Annotation-based configuration
- Embedded application server
- Auto-configuration
- Minimal boilerplate
- “Convention over configuration”
For Beginners: Always use Spring Boot. It’s simpler and is the standard now.
How Spring Fits Into Java
Java Platform Layers:
Your Application Code
↓
Spring Framework
↓
Java Standard Library (java.util, java.io, etc.)
↓
Java Virtual Machine (JVM)
↓
Operating System
Spring sits between your code and the Java standard library, providing utilities and patterns.
Section 3: The Spring Boot Application Structure (10 minutes)
A Minimal Spring Boot Application
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
What @SpringBootApplication Does:
- Enables component scanning (finds your Spring classes)
- Enables auto-configuration (guesses sensible defaults)
- Allows you to define additional beans
That’s it. Spring handles everything else.
Core Annotations You’ll See Immediately
Component Annotations (Register objects with Spring):
@Component // Generic Spring-managed object
@Service // Business logic (same as @Component, but semantic)
@Repository // Database access (same as @Component, but semantic)
@Controller // Web request handler
@RestController // Web request handler returning JSON/data
When Spring scans your code, it creates instances of these classes and manages them.
Dependency Injection:
@Autowired // Spring injects the dependency
Properties/Configuration:
@Value("${property.name}") // Inject a property value
@ConfigurationProperties // Bind external properties to a class
Functional Annotations:
@Bean // Mark a method as creating a bean
@GetMapping // Handle HTTP GET requests
@PostMapping // Handle HTTP POST requests
Project Structure (Convention Over Configuration)
src/
├── main/
│ ├── java/
│ │ └── com/mycompany/
│ │ ├── Application.java (main class)
│ │ ├── controller/ (web handlers)
│ │ ├── service/ (business logic)
│ │ └── repository/ (database access)
│ └── resources/
│ ├── application.properties (configuration)
│ └── templates/ (HTML templates, if needed)
└── test/
└── java/ (unit tests)
Spring expects this structure. Following it keeps things organized and allows auto-configuration to work.
Section 4: Key Concepts in Action (12 minutes)
Example: A Simple REST API Endpoint
Scenario: Users request data about products, and we need to fetch from a database.
Database Layer:
@Repository
public class ProductRepository {
// Spring will manage this object
// Contains database queries
public Product findById(int id) {
// database logic
}
}
Business Logic Layer:
@Service
public class ProductService {
private final ProductRepository repository;
public ProductService(ProductRepository repository) {
// Spring injects the repository
this.repository = repository;
}
public Product getProduct(int id) {
return repository.findById(id);
}
}
Web Layer:
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductService service;
public ProductController(ProductService service) {
// Spring injects the service
this.service = service;
}
@GetMapping("/{id}")
public Product getProduct(@PathVariable int id) {
return service.getProduct(id);
}
}
What Happens:
- Application starts → Spring creates instances of ProductRepository, ProductService, ProductController
- User makes HTTP GET request to
/api/products/5 - Spring routes to
ProductController.getProduct(5) - Controller calls
ProductService.getProduct(5) - Service calls
ProductRepository.findById(5) - Result flows back through layers
- Spring converts result to JSON and sends to user
Key Points:
- Each layer is separate (single responsibility)
- Dependencies flow downward (controller needs service, service needs repository)
- Testing is easy (mock any layer)
- Spring wired everything together based on annotations
Configuration Example
application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
Spring automatically reads these and configures the database connection. No code needed.
Section 5: Advantages of Using Spring (8 minutes)
Reduced Boilerplate
Without Spring: 100 lines of configuration, XML, manual object creation With Spring: Annotations, auto-configuration, sensible defaults
Consistency
All Spring applications follow similar patterns. If you know one, you can understand others.
Ecosystem & Libraries
Thousands of integrations already built (databases, message queues, caching, security, etc.)
Testing Friendliness
Dependency injection makes unit testing straightforward—inject mocks, test in isolation.
Production Ready
Spring applications handle high traffic, clustering, and monitoring out of the box.
Industry Standard
If you want to work in enterprise Java, Spring is essential knowledge. Ubiquitous in job listings.
Section 6: What You Don’t Need to Worry About Yet (5 minutes)
Spring Covers Many Things
You might hear about these—they’re useful but not essential for beginners:
Spring Security: Authentication and authorization (login/permissions)—important for production apps, complex to learn first
Spring Data JPA: Advanced database querying—makes database work elegant, but add complexity if learning basics
Spring Cloud: Microservices, distributed systems—relevant for large enterprises, not for learning fundamentals
Spring AOP (Aspect-Oriented Programming): Cross-cutting concerns—powerful but abstract, come back later
Spring WebFlux: Reactive programming—high-performance, but adds complexity
Message: Focus on Spring Boot basics first. You’ll use these other modules when building real applications.
Closing: Key Takeaway (2 minutes)
Spring is infrastructure code for building applications. It handles the plumbing so you focus on solving business problems. Once you understand IoC, dependency injection, and the application structure, everything else is just learning which Spring modules to use.
Summary of Key Concepts
| Concept | Definition | Why It Matters |
|---|---|---|
| IoC | Framework controls object creation and lifecycle | Decouples code, enables flexibility |
| DI | Objects receive dependencies from outside | Makes testing easy, reduces coupling |
| Bean | A Spring-managed object | Spring handles creation and injection |
| Spring Boot | Simplified Spring with auto-configuration | Reduces boilerplate, easy to start |
| Annotation | Java metadata marking special classes/methods | Tells Spring how to process code |
| Application Context | Spring’s container managing all beans | Central registry of all objects |
| Layered Architecture | Repository → Service → Controller separation | Organized, testable, maintainable |
Questions to Test Understanding
- What’s the difference between IoC and DI?
- IoC is the principle (framework controls flow), DI is the mechanism (dependencies are injected)
- Why would you use constructor injection instead of field injection?
- Constructor injection makes dependencies explicit and required; field injection hides them
- What does @SpringBootApplication do?
- Enables component scanning, auto-configuration, and marks the entry point
- In a layered architecture, why shouldn’t the controller talk directly to the database?
- Separates concerns, makes testing easier, allows service logic to be reused, easier to change database implementation
- What does Spring create and manage?
- Beans (instances of classes marked with @Component, @Service, @Repository, etc.) based on configuration
Lecture Notes for Instructor
Timing Notes:
- Spend most time on IoC and DI concepts (they’re foundational)
- Use the ProductRepository/Service/Controller example as a reference point throughout
- If students seem lost on the Spring Container, use the factory supervisor analogy again
- Be ready to show a working Spring Boot project—live demo helps tremendously
Engagement Strategies:
- Ask “Why might this be useful?” frequently—relate to problems students have faced
- Compare traditional Java approaches vs. Spring for concrete tasks
- Show the same feature in XML config (if students ask) to highlight why Spring Boot is better
- Emphasize that Spring’s magic is really just reading annotations and configuration
Common Misconceptions to Address:
- Spring doesn’t magically solve architectural problems—it just provides tools
- @Autowired doesn’t create new objects; it injects existing ones managed by Spring
- Spring annotations are just metadata; a framework reads them and acts on them
- Spring Boot is not required to use Spring, but it’s the modern standard
Assumptions About Student Knowledge:
- Comfortable with Java syntax and basic OOP
- Have built a simple Java program before
- Understand interfaces and abstract classes
- Don’t need to know about servlet containers, XML, or advanced Java