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
A 1-3 sentence explanation of what the example demonstrates, often including an Islamic finance scenario for real-world context.
2. Heavily Annotated Code
Self-contained, runnable Java and Kotlin implementations with // => annotations on every significant line.
Annotation density: 1.0-2.25 comment lines per code line
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
}
@Transactional // => Transaction boundary
public void recordPayment(BigDecimal amount) {
repository.save(new ZakatRecord(amount)); // => Persists within transaction
// => Auto-commit on success
}
}3. Optional Diagram
Mermaid diagrams for complex concepts showing data flow, object hierarchies, or execution sequences.
4. Key Takeaways
Bullet points highlighting critical concepts and common pitfalls.
5. Why It Matters
50-100 words explaining the business and production relevance of the concept, specifically in the context of Islamic finance systems.
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
Examples by Level
Beginner (Examples 1–25)
- Example 1: Creating Spring ApplicationContext (Coverage: 1.0%)
- Example 2: Defining and Retrieving Simple Bean (Coverage: 3.0%)
- Example 3: Constructor Dependency Injection (Coverage: 6.0%)
- Example 4: Component Scanning with @Component (Coverage: 10.0%)
- Example 5: @Autowired Constructor Injection (Coverage: 13.0%)
- Example 6: Custom Bean Names (Coverage: 16.0%)
- Example 7: Bean Aliases (Coverage: 18.0%)
- Example 8: Setter Injection (Coverage: 20.0%)
- Example 9: Field Injection (Coverage: 22.0%)
- Example 10: @Qualifier for Disambiguation (Coverage: 25.0%)
- Example 11: Singleton Scope (Default) (Coverage: 27.0%)
- Example 12: Prototype Scope (Coverage: 30.0%)
- Example 13: @PostConstruct Lifecycle Callback (Coverage: 33.0%)
- Example 14: @PreDestroy Lifecycle Callback (Coverage: 36.0%)
- Example 15: @Primary for Default Bean (Coverage: 38.0%)
- Example 16: @Value with Literal Values (Coverage: 40.0%)
- Example 17: @Value with Property Placeholders (Coverage: 42.0%)
- Example 18: @Value with Default Values (Coverage: 44.0%)
- Example 19: Profile-Based Configuration (@Profile) (Coverage: 46.0%)
- Example 20: Environment Abstraction (Coverage: 48.0%)
- Example 21: Loading Resources (Coverage: 50.0%)
- Example 22: Injecting Collections (Coverage: 52.0%)
- Example 23: Conditional Bean Registration (@Conditional) (Coverage: 54.0%)
- Example 24: Lazy Bean Initialization (@Lazy) (Coverage: 56.0%)
- Example 25: DependsOn for Bean Creation Order (Coverage: 58.0%)
Intermediate (Examples 26–50)
- Example 26: Constructor Injection with Multiple Dependencies (Coverage: 61.0%)
- Example 27: Optional Dependencies with @Autowired(required=false) (Coverage: 63.0%)
- Example 28: Injecting ApplicationContext (Coverage: 65.0%)
- Example 29: Circular Dependency Resolution (Coverage: 67.0%)
- Example 30: Generic Type Injection (Coverage: 69.0%)
- Example 31: Basic @Aspect with @Before Advice (Coverage: 71.0%)
- Example 32: @After and @AfterReturning Advice (Coverage: 73.0%)
- Example 33: @Around Advice (Coverage: 74.0%)
- Example 34: Pointcut Expressions (Coverage: 75.5%)
- Example 35: @AfterThrowing Exception Handling (Coverage: 77.0%)
- Example 36: Basic @Transactional (Coverage: 78.5%)
- Example 37: Transaction Propagation (Coverage: 80.0%)
- Example 38: Transaction Isolation (Coverage: 81.5%)
- Example 39: Rollback Rules (Coverage: 83.0%)
- Example 40: Programmatic Transactions (Coverage: 84.5%)
- Example 41: Basic JdbcTemplate Query (Coverage: 86.0%)
- Example 42: Querying with RowMapper (Coverage: 87.5%)
- Example 43: NamedParameterJdbcTemplate (Coverage: 89.0%)
- Example 44: Batch Operations (Coverage: 90.5%)
- Example 45: Result Extraction with ResultSetExtractor (Coverage: 92.0%)
- Example 46: Simple @Controller (Coverage: 93.5%)
- Example 47: @RequestParam and @PathVariable (Coverage: 95.0%)
- Example 48: @RequestBody and JSON (Coverage: 96.5%)
- Example 49: Exception Handling with @ExceptionHandler (Coverage: 98.0%)
- Example 50: Form Validation with @Valid (Coverage: 100.0%)
Advanced (Examples 51–75)
- Example 51: @RestController and ResponseEntity (Coverage: 76.5%)
- Example 52: Content Negotiation (Coverage: 78.0%)
- Example 53: CORS Configuration (Coverage: 79.5%)
- Example 54: API Versioning (Coverage: 81.0%)
- Example 55: Global Exception Handler (Coverage: 82.5%)
- Example 56: Basic Security Configuration (Coverage: 84.0%)
- Example 57: Method Security (Coverage: 85.5%)
- Example 58: Custom UserDetailsService (Coverage: 87.0%)
- Example 59: JWT Token Authentication (Coverage: 88.5%)
- Example 60: Password Encoding (Coverage: 90.0%)
- Example 61: Spring Cache Abstraction (Coverage: 91.5%)
- Example 62: Async Method Execution (Coverage: 93.0%)
- Example 63: Application Events (Coverage: 94.5%)
- Example 64: Scheduled Tasks (Coverage: 96.0%)
- Example 65: Custom Conditional Bean Registration (Coverage: 97.5%)
- Example 66: Spring TestContext Framework (Coverage: 99.0%)
- Example 67: MockMvc for Web Layer Testing (Coverage: 100.0%)
- Example 68: @Transactional in Tests (Coverage: 100.0%)
- Example 69: Test Profiles (Coverage: 100.0%)
- Example 70: Mocking with @MockBean (Coverage: 100.0%)
- Example 71: Custom Health Indicator (Coverage: 100.0%)
- Example 72: Custom Metrics (Coverage: 100.0%)
- Example 73: Request/Response Logging Interceptor (Coverage: 100.0%)
- Example 74: Connection Pooling with HikariCP (Coverage: 100.0%)
- Example 75: Custom Validation Annotation (Coverage: 100.0%)
Last updated January 28, 2025