Sobes.tech
Senior

How is dependency injection recommended in Spring?

sobes.tech AI

Answer from AI

In Spring, it is recommended to inject dependencies via constructors (Constructor Injection). This ensures:

  • Immutability of dependencies after object creation.
  • Simplified testing, as dependencies can be passed explicitly.
  • Explicit declaration of required dependencies.

Example of constructor injection:

@Component
public class TicketService {
    private final PaymentService paymentService;

    public TicketService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }

    // service methods
}

You can also use the @Autowired annotation on the constructor, but starting with Spring 4.3, if the class has only one constructor, the annotation is not mandatory.

Injection via fields (@Autowired on fields) or setters is less preferred, as it complicates testing and violates the dependency inversion principle.