Dependency Injection(DI) in Spring:-
Dependency Injection (DI) is a design pattern that removes the dependency from
the programming code so that it can be easy to manage and test the application.
Dependency Injection makes our programming code loosely coupled.In such case we
provide the information from the external source such as XML file.
In such case we write the code as:
class Student{
Name name;
Student(Name name){
this.name=name;
}
public void setName(Name name){
this.name=name;
} }
In such case, instance of Name class is provided by external souce such as XML file either by constructor or setter method.
There are two ways to perform Dependency Injection in Spring
framework-
Spring framework provides two ways to inject dependency
1 By Constructor:Constructor-based DI is accomplished when the container
invokes a class constructor with a number of arguments, each representing a
dependency on other class.We can inject the dependency by constructor. The
<constructor-arg> subelement of <bean> is used for constructor
injection.Here are some type of inject
1 Primitive and String-based values
2 Dependent object (contained object)
3 Collection values etc.
2 By Setter method:Setter-based DI is accomplished by the container
calling setter methods on your beans after invoking a no-argument constructor or
no-argument static factory method to instantiate your bean.We can inject the
dependency by setter method also. The <property> subelement of <bean>
is used for setter injection.