Dependency Injection
- Dependency injection is used to inject one object into another object.
- There are two types of injection:-
- Property Injection
- Setter Injection
Key Points:
- Partial Dependency can be achieved using setter injection but it is not possible by constructor.
- When a class has three properties with a three-argument constructor and setter methods, passing information for only one property is possible only through the corresponding setter method.
Steps to achieve dependency injection (setter or property injection):
- Create a Java project with the respective package.
- Download the Spring Jar files and add them to the build path. (Spring jar file and commons-logging jar file)
- Create a Bean Class with respect to the getter and setter method.
- Create a configuration file (XML file).
- Search for the configuration file get the bean and utilize the bean.
Example :
package com.quipoin;
import java.util.Map;
public class Student {
private String name;
private int id;
private Map<String,Integer> marks;
private char gender;
public void setName(String name) {
this.name=name;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Map<String, Integer> getMarks() {
return marks;
}
public void setMarks(Map<String, Integer> marks) {
this.marks = marks;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
}
Configure.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- bean definitions here -->
<bean class="student.Student" name="st">
<property name="name" value="Naveen" />
<property name="id" value="101" />
<property name="marks">
<map>
<entry key="Java" value="68" />
<entry key="sql" value="85" />
<entry key="Spring" value="49" />
<entry key="jdbc" value="73" />
</map>
</property>
<property name="gender" value="M" />
</bean>
</beans>
App.java
package com.quipoin;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String []args) {
ApplicationContext context=new
ClassPathXmlApplicationContext("configure.xml");
Object obj=context.getBean("st");
Student s1=(Student)obj;
System.out.println("Student Name:"+s1.getName());
System.out.println("Student Id:"+s1.getId());
System.out.println("Marks:"+s1.getMarks());
System.out.println("Gender:"+s1.getGender());
}
}
Output:
Student Name:Naveen
Student Id:101
Marks:{Java=68, sql=85, Spring=49, jdbc=73}
Gender:M