Understanding Dependency Injection with Spring

Jul 11, 2024

Understanding Dependency Injection with Spring

Key Concepts

  • Dependency Injection (DI): technique where an object receives other objects it depends on, promoting loose coupling.
  • Unit Testing: DI simplifies creating mock implementations for testing.
  • Spring Framework: robust tool to facilitate DI with annotations, application contexts, and more.

Maven Project Setup

  • Simple Maven project without Spring Boot
  • Dependencies: Add spring-context to pom.xml

Code Structure

  • BackgroundVerificationService interface with two implementations
  • LoanService: Depends on BackgroundVerificationService via constructor
  • LoanRequest: Bean with some properties
  • Main Application: Console application setup with Spring DI for loan approval/rejection

Applying Dependency Injection with Spring

  1. Annotate Beans with @Component: Marks classes as Spring-managed components.
  2. Create Application Context: Use AnnotationConfigApplicationContext specifying base packages.
  3. Bean Lookup: Retrieve beans from application context with context.getBean(LoanService.class).

Steps Behind the Scenes

  1. Scanning Components: Using Spring's ClassPathScanningCandidateComponentProvider to find classes with @Component annotation.
  2. Identifying Dependencies: Using Java Reflection to inspect constructors and their parameter types.
  3. Instantiating Beans: Creating instances via reflection and injecting dependencies recursively.

Practical Implementation and Example

  • Scan Classes: Identify @Component annotated classes.
  • Reflection for Dependencies: Inspect constructor types to understand dependencies.
  • Create Instances: Use reflection to instantiate dependencies and assemble the final bean.

Benefits of Understanding DI Mechanics

  • Core concept across Spring ecosystem (e.g., Spring Data, Security, MVC).
  • Robust knowledge supports better utilization and troubleshooting of Spring's numerous modules.

Creating a Simple Custom Bean Factory

  • Example: Manually define and instantiate beans without using Spring, for small applications.
  • BeanFactory Class: A custom version of an application context.

Conclusion

  • Spring DI: Fundamental tool for building scalable, testable applications
  • Custom DI: Possible without frameworks for simpler projects.
  • Future Learning: Spring offers more complex customization like prototype beans, lazy initialization, etc.
  • Key takeaway: Flexibility in object instantiation through DI, promoting a more modular and maintainable codebase.