Overview
Learning Approach
This By Example series teaches Spring Framework through code-first learning with heavily annotated examples. Each example is self-contained and runnable, demonstrating specific Spring Framework concepts.
Target: 75-90 examples achieving 95% Spring Framework coverage
Annotation Density: 1.0-2.25 comment lines per code line (per example)
Format: All examples in both Java and Kotlin
Why By Example?
Traditional tutorials often provide long explanations before showing code. This approach inverts that pattern:
Code First: Start with working, runnable examples
Inline Documentation: Every line annotated with // => explaining what happens
Incremental Complexity: Simple examples first, building to advanced patterns
Islamic Finance Context: Real-world scenarios (Zakat, Murabaha, Sadaqah)
Structure
Beginner Examples (0-50% Coverage)
Topics Covered:
- IoC Container basics
- Bean definitions with
@Configurationand@Bean - Component scanning with
@Component,@Service,@Repository - Dependency injection (constructor, setter, field)
- Bean scopes (singleton, prototype)
- Lifecycle callbacks (
@PostConstruct,@PreDestroy) - Property injection with
@Value - Profile-based configuration (
@Profile)
Example Count: ~25-30 examples
Skill Level: No prior Spring knowledge required
Intermediate Examples (50-85% Coverage)
Topics Covered:
- Advanced dependency injection (qualifiers, primary beans)
- Data access with JdbcTemplate
- Transaction management (
@Transactional) - Spring AOP (aspects, pointcuts, advice types)
- Event publishing and handling
- SpEL (Spring Expression Language)
- Resource handling
- Validation with Bean Validation API
- Testing with Spring Test framework
Example Count: ~30-35 examples
Skill Level: Completed beginner examples or equivalent knowledge
Advanced Examples (85-95% Coverage)
Topics Covered:
- Custom bean post-processors
- Advanced AOP (custom annotations, around advice)
- Programmatic transaction management
- Custom scope implementations
- Conditional bean registration
- Spring Web MVC (controllers, REST APIs)
- Exception handling strategies
- Async processing with
@Async - Caching with
@Cacheable - Integration testing strategies
Example Count: ~20-25 examples
Skill Level: Completed intermediate examples or production Spring experience
Example Format
Each example follows a five-part structure:
1. Concept Introduction
Brief explanation of what the example demonstrates.
Example:
Concept: Constructor injection - Spring injects dependencies via constructor parameters, ensuring immutability and required dependencies.
2. Islamic Finance Scenario
Real-world context using Islamic finance concepts.
Example:
Scenario: ZakatService requires a ZakatRepository to persist Zakat payments. Constructor injection ensures the repository is always available.
3. Code Example (Heavily Annotated)
Self-contained, runnable code with inline annotations.
Java Example:
@Service // => Marks as Spring-managed service component
public class ZakatService {
private final ZakatRepository repository; // => Final field - immutable
// => Constructor injection (recommended)
// => Spring automatically injects repository parameter
public ZakatService(ZakatRepository repository) {
this.repository = repository; // => Dependency injected
} // => Repository cannot be null
@Transactional // => Transaction boundary
public void recordPayment(BigDecimal amount) {
repository.save(new ZakatRecord(amount)); // => Persists within transaction
} // => Auto-commit on success
}Kotlin Example:
@Service // => Spring-managed service
class ZakatService(
private val repository: ZakatRepository // => Constructor injection
) { // => Concise Kotlin syntax
@Transactional // => Transaction boundary
fun recordPayment(amount: BigDecimal) {
repository.save(ZakatRecord(amount)) // => Persists record
} // => Auto-commit/rollback
}4. Key Takeaways
Bullet points highlighting critical concepts.
Example:
- Constructor injection ensures required dependencies are never null
@Serviceenables component scanning@Transactionalprovides declarative transaction management- Final fields promote immutability
5. Common Mistakes
Anti-patterns and how to avoid them.
Example:
❌ Mistake: Using field injection
@Autowired
private ZakatRepository repository; // => Hard to test, hides dependencies✅ Correct: Use constructor injection
public ZakatService(ZakatRepository repository) {
this.repository = repository; // => Explicit, testable, immutable
}Islamic Finance Context
Examples use authentic Islamic finance scenarios:
Zakat (Obligatory Charity)
Definition: 2.5% annual payment on qualifying wealth above nisab threshold
Examples:
- Calculating Zakat on savings
- Recording Zakat payments
- Tracking distribution to eligible recipients
Murabaha (Cost-Plus Financing)
Definition: Shariah-compliant financing where financier buys asset and sells at disclosed profit
Examples:
- Calculating payment schedules
- Recording installments
- Profit distribution calculations
Sadaqah (Voluntary Charity)
Definition: Voluntary charitable giving beyond obligatory Zakat
Examples:
- Recording donations
- Tracking campaigns
- Generating tax receipts
Qard Hassan (Benevolent Loan)
Definition: Interest-free loan as act of charity
Examples:
- Loan disbursement
- Repayment tracking
- Beneficiary management
How to Use This Series
Sequential Learning (Recommended)
Follow examples in order:
- Start: Beginner examples (foundational concepts)
- Progress: Intermediate examples (practical patterns)
- Master: Advanced examples (production techniques)
Reference Learning
Jump to specific topics using index:
- Need transaction management? → Intermediate #15
- Need REST APIs? → Advanced #08
- Need custom annotations? → Advanced #12
Practice-Based Learning
After each example:
- Read the annotated code
- Type the code yourself (muscle memory)
- Modify the example (experiment)
- Test your changes (verify understanding)
Prerequisites
Required Knowledge
Java or Kotlin:
- OOP concepts (classes, interfaces, inheritance)
- Generics basics
- Lambda expressions (Java 8+) or Kotlin functions
Build Tools:
- Maven or Gradle basics
- Dependency management concepts
Database Basics:
- SQL fundamentals (SELECT, INSERT, UPDATE)
- JDBC concepts (connections, statements)
Setup Requirements
Complete Initial Setup to have:
- Java 17+ or Kotlin 1.9+ installed
- Maven or Gradle configured
- IDE configured (IntelliJ IDEA recommended)
Learning Outcomes
After completing all examples, you will:
Understand:
- Spring IoC container architecture
- Dependency injection patterns and best practices
- Bean lifecycle and scopes
- Transaction management strategies
- AOP concepts and applications
Apply:
- Java-based configuration effectively
- Component scanning and stereotype annotations
- JdbcTemplate for data access
- Declarative transaction management
- Testing strategies with Spring Test
Evaluate:
- When to use Spring Framework vs Spring Boot
- Trade-offs between injection types
- Appropriate transaction boundaries
- Performance implications of AOP
Example Catalog
Core Container (Examples 1-15)
Beginner Level:
- Basic bean definition with
@Bean - Constructor injection
- Setter injection
- Component scanning with
@Component - Autowiring by type
- Singleton vs prototype scope
@PostConstructand@PreDestroy@Valueproperty injection- Profile-based configuration
- Multiple configuration classes
Intermediate Level:
@Qualifierfor disambiguation@Primaryfor default beans- Method injection with
@Lookup - Circular dependency resolution
- Lazy initialization with
@Lazy
Data Access (Examples 16-35)
Beginner Level:
- JdbcTemplate basics - insert
- JdbcTemplate - query with RowMapper
- JdbcTemplate - update and delete
- Named parameters with NamedParameterJdbcTemplate
Intermediate Level:
@Transactionalbasics- Transaction propagation (REQUIRED, REQUIRES_NEW)
- Transaction isolation levels
- Rollback rules
- Programmatic transaction management
- Multiple DataSource configuration
- Connection pooling with HikariCP
- Database initialization with schema.sql
Advanced Level:
- Custom TransactionManager
- Distributed transactions overview
- Optimistic locking patterns
- Batch operations with JdbcTemplate
- Stored procedure calls
- Custom exception translation
- JDBC testing strategies
- Transaction testing with
@Transactionalrollback
AOP (Examples 36-50)
Intermediate Level:
- Basic aspect with
@Beforeadvice @Afterand@AfterReturningadvice@Aroundadvice for method interception- Pointcut expressions
- Custom annotations as pointcuts
- Passing arguments to advice
- Aspect ordering
Advanced Level:
- Introduction aspects (
@DeclareParents) - Performance monitoring aspect
- Logging aspect
- Security aspect (authorization checks)
- Retry logic with AOP
- Caching with AOP
- Async execution with AOP
- AOP testing strategies
Web MVC (Examples 51-70)
Intermediate Level:
- Basic
@Controllerwith request mapping @RequestParamfor query parameters@PathVariablefor URL variables@RequestBodyfor JSON input@ResponseBodyfor JSON output- Model and View resolution
- Form handling with
@ModelAttribute - Validation with Bean Validation API
- Exception handling with
@ExceptionHandler - RESTful API with
@RestController
Advanced Level:
- Content negotiation
- Custom argument resolvers
- Interceptors for request processing
- File upload handling
- Async request processing
- Server-Sent Events (SSE)
- CORS configuration
- Security headers
- REST API testing
- Integration testing with MockMvc
Advanced Topics (Examples 71-90)
- Event publishing with
ApplicationEventPublisher - Event listening with
@EventListener - SpEL in annotations
- Resource loading
- Custom property sources
- Custom scope implementation
- Bean post-processors
@Conditionalannotations- Caching with
@Cacheable - Async methods with
@Async - Scheduling with
@Scheduled - Custom validators
- Type conversion with ConversionService
- Internationalization (i18n)
- Profile-specific beans
- Environment abstraction
- Application context events
- Graceful shutdown
- Health checks
- Metrics collection
Navigation
Start Learning:
- Beginner Examples - Examples 1-30 (0-50% coverage)
- Intermediate Examples - Examples 31-65 (50-85% coverage)
- Advanced Examples - Examples 66-90 (85-95% coverage)
Other Learning Paths:
- Overview - Conceptual introduction
- Initial Setup - Installation and project setup
- Quick Start - Complete working application