A design pattern in which the dependencies (other objects) an object needs are injected from outside rather than created directly. It realizes the D (Dependency Inversion Principle) of the SOLID principles and greatly improves loose coupling, testability, and maintainability.
Applying dependency injection lowers the coupling of the code and makes testing easier.
❌ Without DI (Tight Coupling)
class UserService: def __init__(self): # Created directly - tight coupling self.db = MySQLDatabase() self.email = SmtpEmailService()
# Problems: # - Code must be modified when replacing the DB # - A real DB connection is required for testing # - Mocks cannot be used
✅ With DI (Loose Coupling)
class UserService: def __init__(self, db: Database, email: EmailService): # Injected from outside self.db = db self.email = email
# Advantages: # - Depends on interfaces # - Easy unit testing by injecting mocks
📐 Core Principles: IoC and SOLID
🔃 IoC (Inversion of Control)
"Don't call us, we'll call you"
Inversion of Control. Instead of an object finding or creating its dependencies directly, the framework/container injects them. DI is a representative way to implement IoC.
📌 SOLID - D (DIP)
Dependency Inversion Principle
"High-level modules do not depend on low-level modules. Both depend on abstractions (interfaces)."
💉 Comparison of DI Types
Recommended
Constructor Injection
Constructor Injection
Dependencies are injected through constructor parameters. All dependencies are guaranteed when the object is created.
✅ Guarantees immutability (final fields)
✅ Makes required dependencies explicit
✅ Easy to test
⚠️ Constructor gets long when there are many dependencies
Recommended
Setter Injection
Setter Injection
Dependencies are injected through setter methods. Suitable for optional dependencies.
✅ Optional dependencies possible
✅ Can be replaced at runtime
⚠️ Incomplete objects can be created
⚠️ Null checks required
Not recommended
Field Injection
Field Injection
Dependencies are injected directly into fields using @Autowired and the like. Concise, but has many drawbacks.
Inside a service class new DatabaseConnection()Isn't it okay to create it directly with ? It looks simpler.
🏗️
Senior developer
Then how will you handle testing? Every unit test has to connect to a real database, and you also have to clean up the test data. With DI, you can inject a Mock object and test quickly without a DB.
👤
Junior Developer
Ah, so it's because of testing. But isn't @Autowired field injection the simplest?
🏗️
Senior developer
Field injection looks convenient, but it requires reflection for testing and makes it hard to detect circular references. Constructor Injectionis recommended. The dependencies are explicit, immutability is guaranteed with final, and the official Spring documentation also recommends this approach.
👤
Junior Developer
What if the constructor has 10 dependencies? It gets too long...
🏗️
Senior developer
That's not a DI problem, but a class with too many responsibilitiesis the signal! Split the class according to the Single Responsibility Principle (SRP). When the constructor gets complicated, ask yourself, "Isn't this class doing too much?"
⚠️ Cautions
🔄
Circular Dependency
If A depends on B and B depends on A, a circular dependency occurs. With constructor injection, it can be detected early through compile/runtime errors. Rather than using @Lazy, reconsider the design.
🔧
Over-Engineering (Excessive Abstraction)
There is no need to create an interface for every class. If there is only one implementation and no possibility of replacing it, depending on it directly is fine. Remember the YAGNI (You Aren't Gonna Need It) principle.
🎭
Overuse of Mocks
If everything is mocked, tests become tied to the implementation. Mock only external systems (DB, API) and test internal logic with real objects. The principle of "Mock only at the boundaries."
📦
Service Locator Anti-Pattern
Fetching dependencies at runtime, as in Container.get(UserService), hides the dependencies. Use constructor injection, where dependencies are made explicit at compile time.
📋 Real-World Application Cases
Achieving 90% Test Coverage
Success
Situation: Legacy code created DB connections directly, making unit testing impossible. A real DB was needed to run tests, and test execution took more than 30 minutes.
Application: Refactored with the Repository pattern + constructor injection. Defined interfaces and changed the code so that Mock objects could be injected.
Result: Unit test execution time reduced to 30 seconds. Test coverage 20% → 90%. Tests run automatically on every PR in the CI/CD pipeline.
Key point:
DI is the foundation of testable code. Mock injection builds a fast feedback loop without external dependencies.
Replacing the Payment System - Completed in 3 Days
Success
Situation: The existing payment API (PaymentGatewayA) had to be replaced with a new payment API (PaymentGatewayB). A gradual migration without service interruption was needed.
Application: Because the system was designed to depend on the PaymentService interface, only the new implementation was added. Configured A/B switching with a Feature Flag.
Result: Only the DI configuration changed, with no business logic changes. Gradual transition 1% → 10% → 100%. Rollback is also possible immediately with just a configuration change.
Key point:
If you depend on an interface, replacing the implementation becomes a "configuration change." A practical benefit of loose coupling.
Application Startup Failure Due to Circular Dependency
Failure
Situation:OrderService depended on InventoryService, and InventoryService depended on OrderService. It was not detected at compile time because field injection (@Autowired) was used.
Problem: The service went down in a production deployment due to a Spring Context initialization failure. It was temporarily resolved with @Lazy, but the root cause was not resolved.
Solution: Separated the common logic into a separate service to eliminate the circular dependency. Switched to constructor injection so the circular dependency is detected at compile time.
Lesson:
With constructor injection, circular dependencies are caught early as compile errors. @Lazy is not a solution but merely hides the symptom.
🧠 Comprehension Quiz
Q. Which of the following is NOT a main advantage of dependency injection (DI)?
A. Mock objects can be injected during unit testing
B. Runtime performance improves
C. Implementations are easy to replace
D. Coupling between classes is reduced
Answer: B
Dependency injection is unrelated to improving runtime performance. If anything, some overhead may arise from IoC container initialization, the use of reflection, and so on.
The actual advantages of DI are: • Testability: Isolated unit tests are possible by injecting mocks • Loose coupling: Depending on interfaces makes it easy to replace implementations • Maintainability: Dependencies are explicitly revealed