Dependency Injection With Java and Ruby Examples

Learn dependency injection with practical Java and Ruby examples covering services, repositories, testing, loose coupling, SOLID, and common backend mistakes.

By Anderson Alvarez Vásquez · 2026-07-08

  • technology
  • programming
  • ruby
  • tutorials
  • Java

Dependency Injection: A Practical Guide for Backend Developers Dependency Injection is a design technique where an object receives the dependencies it needs instead of creating them directly. It helps backend developers write code that is easier to test, extend, and maintain. The Problem Without Dependency Injection Imagine a service that creates its own dependency. java public class CheckoutService { private final PaymentGateway paymentGateway = new StripePaymentGateway ; public void checkout BigDecimal amount { paymentGateway.charge amount ; } } This works, but it creates a problem: CheckoutService is tightly coupled to StripePaymentGateway . If you want to test the service, replace the gateway, or support another provider, the code becomes harder to change. What Dependency Injection Solves With dependency injection, the dependency is provided from the outside. java public class CheckoutService { private final PaymentGateway paymentGateway; public CheckoutService PaymentGateway paymentGateway { this.paymentGateway = paymentGateway; } public void checkout BigDecimal amount { paymentGateway.charge amount ; } } Now CheckoutService depends on an abstraction instead of a specific implementation. java public interface PaymentGateway { void charge BigDecimal amount ; } Implementation: java public class StripePaymentGateway implements PaymentGateway { @Override public void charge BigDecimal amount { System.out.println "Charging with Stripe: " + amount ; } } The service does not need to know which gateway is being used. Constructor Injection Constructor injection is usually the safest and clearest form of dependency injection. java public class UserService { private final UserRepository userRepository; private final EmailSender emailSender; public UserService UserRepository...