Logo InterviewVault

Welcome back, Sujit Kumar Mishra

SKM

Revision Mode

Document technical questions and best-practice answers.

Cancel

Dependency Injection

- What are the different ways to implement dependency injection in Spring Boot?

- Which approach is recommended and why?

Dependency Injection in Spring Boot

There are three main ways to implement dependency injection in Spring Boot:

1: Constructor Injection

Inject dependencies using the class constructor.

Example:

public MyService(MyRepository repo) { ... }

2: Setter Injection

Inject dependencies using setter methods.

Example:

public void setRepo(MyRepository repo) { ... }

3: Field Injection

Inject dependencies directly into fields using @Autowired.

Example:

@Autowired private MyRepository repo;


Recommended Approach:

Constructor injection is generally recommended because:

1: It makes dependencies clear and required.

2: It helps with testing and immutability.

3: It avoids issues related to Spring’s internal processing.


Summary:

Use constructor injection for most cases in Spring Boot. It’s clean, safe, and easy to test.

Ready for commit