Dependency Injection

Spring Dependency Injection

The dependency injection pattern is a pattern that we may use to create IoC, where the Control Inversion sets the dependence of an object.

Rather than the items themselves, the assembler connects objects or "injects" objects into other objects.

Dependency Injection (DI) is a design pattern that removes the programming code dependency to quickly manage and test the application. Dependency Injection loosely combines our computer code.

Constructor-Based Dependency Injection

When a building dependency is injected, the container will run a builder with parameters, each dependent we wish to define.

Spring mostly resolves each parameter by type, followed by the attribute name and the debugging index.

The annotation @Configuration shows that the class is a source of definitions of beans. We can add it to several setup classes as well. We use @Bean to define the bean annotation. If a custom name is not specified, the bean name will default to the procedure's name.

Spring first checks if a cached instance of the bean exists and only builds a new one if it doesn't. For a bean with the default singleton scope. The container returns a new instance of bean for each method call if we use the prototype's scope.

Setter-Based Dependency Injection

For DI, after executing the no-argument builder or no-argument static factory method, the container shall use the setter methods of our class to instantiate the bean.

For the same bean, we can blend building and injection-based kinds. The documentation of Spring advises that builders are injected for compulsory dependence and setters for optional dependency.