Dependency injection in Spring allows components to have their dependencies satisfied externally rather than internally. This is done by describing dependencies in a configuration file rather than hardcoding them in code. The container is then responsible for satisfying the dependencies. There are two main types of dependency injection - constructor injection, where dependencies are passed via a class constructor, and setter injection, where dependencies are passed via setter methods. The best practice is to use constructor injection for mandatory dependencies and setter injection for optional dependencies.
Dependency injection in Spring allows components to have their dependencies satisfied externally rather than internally. This is done by describing dependencies in a configuration file rather than hardcoding them in code. The container is then responsible for satisfying the dependencies. There are two main types of dependency injection - constructor injection, where dependencies are passed via a class constructor, and setter injection, where dependencies are passed via setter methods. The best practice is to use constructor injection for mandatory dependencies and setter injection for optional dependencies.
Dependency Injection, an aspect of Inversion of Control (IoC), is a general concept, and it can be expressed in many different ways.This concept says that you do not create your objects but describe how they should be created. You dont directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (the IOC container) is then responsible for hooking it all up.
19. What are the different types of IoC (dependency
injection)?
Constructor-based dependency injection: Constructor-based DI is
accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class. Setter-based dependency injection: Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a noargument constructor or no-argument static factory method to instantiate your bean.
20. Which DI would you suggest Constructor-based or
setter-based DI? You can use both Constructor-based and Setter-based Dependency Injection. The best solution is using constructor arguments for mandatory dependencies and setters for optional dependencies.