Dependency Injection in Spring

  • Dependency Injection (DI) is a design pattern that allows us to remove the hard-coded dependencies and make our application loosely coupled, extendable, and maintainable. We can implement dependency injection to move the dependency resolution from compile-time to runtime.

  • In the context of the Spring Framework, Dependency Injection is a design pattern in which objects are not responsible for looking up their dependencies. Instead, dependencies are automatically provided by the Spring Container.

  • There are two types of Dependency Injection in Spring:
       1. Constructor-based Dependency Injection: The container invokes a class constructor with a number of arguments, each representing a dependency.


@Component
public class ExampleClass {
    private DependencyClass dependency;
    public ExampleClass(DependencyClass dependency) {
        this.dependency = dependency;
    }
}


2. Setter-based Dependency Injection: The container calls setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

@Component
public class ExampleClass {
    private DependencyClass dependency;
    @Autowired
    public void setDependency(DependencyClass dependency) {
        this.dependency = dependency;
    }
}

 

In both cases, `DependencyClass` is a Spring-managed bean that is automatically wired up with `ExampleClass`.

  • How it works?

When a Spring application starts up, it reads the configuration metadata provided (either through XML, annotations, or Java config), and creates and wires up the beans as needed. When a bean is needed, the Spring container will create it, wire it up with its dependencies, and manage its lifecycle.

Post a Comment

Previous Post Next Post