Dependency Injection in Spring Framework Explained with Examples

Dependency Injection is one of the core concepts of the Spring Framework. It helps developers build loosely coupled applications that are easier to test, maintain and extend.


Almost every Spring interview contains questions about Dependency Injection because it forms the foundation of Spring's IoC Container.


What is Dependency Injection?

Dependency Injection is a design pattern where required objects are provided to a class from an external source instead of creating them manually.

Instead of creating dependencies using the new keyword, Spring injects them automatically.


Without Dependency Injection


public class EmployeeService {

    EmployeeRepository repository =
        new EmployeeRepository();

}

In this approach, EmployeeService tightly depends on EmployeeRepository.


Problems Without Dependency Injection

  • Tight coupling
  • Difficult unit testing
  • Harder maintenance
  • Code duplication
  • Poor flexibility

With Dependency Injection


@Service
public class EmployeeService {

    private EmployeeRepository repository;

    public EmployeeService(
            EmployeeRepository repository) {

        this.repository = repository;

    }
}

Now Spring automatically provides the EmployeeRepository object.


What is Inversion of Control (IoC)?

Dependency Injection is implemented through Inversion of Control.

Traditionally applications control object creation. In Spring, the IoC Container controls object creation and management.



Application
      |
      X

Spring IoC Container
      |
      v

Creates Objects
Injects Dependencies
Manages Lifecycle

Types of Dependency Injection

  • Constructor Injection
  • Setter Injection
  • Field Injection

Constructor Injection

Constructor Injection is the recommended approach in modern Spring applications.



@Service
public class EmployeeService {

    private final EmployeeRepository repository;

    public EmployeeService(
            EmployeeRepository repository) {

        this.repository = repository;

    }
}

Spring automatically provides EmployeeRepository when creating EmployeeService.


Advantages

  • Immutable dependencies
  • Easier unit testing
  • Better design
  • No NullPointerException surprises

Setter Injection

Dependencies can also be injected through setter methods.



@Service
public class EmployeeService {

    private EmployeeRepository repository;

    @Autowired
    public void setRepository(
            EmployeeRepository repository) {

        this.repository = repository;

    }
}

Setter Injection is useful when dependencies are optional.


Field Injection

Field Injection is simple but generally discouraged in enterprise applications.



@Service
public class EmployeeService {

    @Autowired
    private EmployeeRepository repository;
}

Although concise, Field Injection makes testing and maintenance more difficult.


How @Autowired Works

The @Autowired annotation tells Spring to automatically locate and inject the required bean.



@Autowired
private EmployeeRepository repository;

Spring searches its Application Context and injects the matching bean.


Real Example

Repository Layer


@Repository
public class EmployeeRepository {

    public String getEmployee() {

        return "John";

    }
}

Service Layer


@Service
public class EmployeeService {

    private final EmployeeRepository repository;

    public EmployeeService(
            EmployeeRepository repository) {

        this.repository = repository;

    }

    public String fetchEmployee() {

        return repository.getEmployee();

    }
}

Controller Layer


@RestController
public class EmployeeController {

    private final EmployeeService service;

    public EmployeeController(
            EmployeeService service) {

        this.service = service;

    }

    @GetMapping("/employee")
    public String getEmployee() {

        return service.fetchEmployee();

    }
}

Spring automatically wires the entire dependency chain.


Benefits of Dependency Injection

  • Loose coupling
  • Better testability
  • Easier maintenance
  • Improved scalability
  • Cleaner architecture

Dependency Injection vs Tight Coupling

Tight Coupling Dependency Injection
Manual object creation Spring manages objects
Hard to test Easy to mock
Rigid design Flexible design
High maintenance Better maintainability

Common Interview Questions

What is Dependency Injection?

A design pattern where dependencies are provided externally instead of being created internally.


What is IoC?

Inversion of Control means Spring manages object creation and dependency handling.


Which type of Dependency Injection is preferred?

Constructor Injection is generally preferred in modern Spring Boot applications.


Why is Field Injection discouraged?

It makes testing harder and hides dependencies.


Does @Autowired require constructors?

For a single constructor, Spring automatically performs injection even without @Autowired.


Best Practices

  • Prefer Constructor Injection.
  • Avoid Field Injection in production code.
  • Keep beans focused on single responsibilities.
  • Use interfaces wherever possible.
  • Write unit tests using mocked dependencies.

Frequently Asked Questions (FAQ)

Can Spring perform Dependency Injection without @Autowired?

Yes. Since Spring 4.3, a single constructor can be injected automatically.


Can multiple beans of the same type exist?

Yes. In such cases, @Qualifier can be used.


Why is Constructor Injection considered safer?

Because required dependencies must be provided during object creation.


Conclusion

Dependency Injection is one of the most important concepts in Spring Framework. It promotes loose coupling, improves testability and enables Spring to manage application components effectively. Understanding Dependency Injection, IoC Container and bean wiring is essential for building enterprise-grade Spring Boot applications and clearing Spring interviews.


Keywords

Dependency Injection Spring, Spring Dependency Injection, IoC Container Spring, Constructor Injection, Setter Injection, Field Injection, @Autowired Annotation, Spring Framework Tutorial, Spring Boot Interview Questions, Dependency Injection Example, Spring Core Concepts, Inversion of Control, Spring Bean Management, Spring Architecture, Java Spring Tutorial



Dependency Injection in Spring Framework Explained with Examples Dependency Injection in Spring Framework Explained with Examples Reviewed by 13thGhost on 12:31 AM Rating: 5

No comments:

Recommended Posts

Powered by Blogger.