Dependency Injection in Spring Example
Here is the code for Dependency Injection in Spring. This code is tested using NetBeans 8.0.2.
Dependency Injection:
Dependency Injection is a process where the Object define its Dependencies, that is with the Objects they work with.
Tightly Coupled vs Loosely Coupled
Tightly Coupled:
In tightly coupled objects interdependent on each other, So when a change is one Object requires changes to number of other objects.
Loosely Coupled:
In Loosely coupled, Reduces the inter-dependencies of the Objects, that is, Change made in one object does not require to make changes in other objects.
Types of Dependency Injection:
There are two ways in Dependency Injection,
- Setter Injection
- Constructor Injection
Create Project:
File –>New Project –>Java –>Web Application
Give a name to Web Application and click Next–>Next–>
Choose the Framework Spring and click Finish
Required Folders:
Right click the Source Packages and Create 2 Java Packages and name them as
1) Dao
2) SimpleValues
Inside Dao create a Java Class and name it as Studentdao.java
Inside SimpleValues create java class and name it as Student.java
Student.java
public class Student { String sname; String marks; int number; public Student(int number) // Constructor Injection { this.number=number; } public void sid() { System.out.println("ID number is: "+number); } public int getNumber() { //Setter Injection return number; } public void setNumber(int number) { this.number = number; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getMarks() { return marks; } public void setMarks(String marks) { this.marks = marks; } public void display() { System.out.println(sname+" scored marks of "+marks+" in Computer Science"); } }
applicationContext.xml
<beans> <bean id="Alpha" class="SimpleValues.Student"> <property name="sname" value="Alpha"></property> <property name="marks" value="92"></property> <constructor-arg value="132"/> </bean> <bean id="Beta" class="SimpleValues.Student"> <property name="sname" value="Beta"></property> <property name="marks" value="96"></property> <constructor-arg value="212"/> </bean> </beans>
Studentdao.java
public class StudentDao { public static void main(String args[]) { ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); Student student1=(Student)ac.getBean("Alpha"); Student student2=(Student)ac.getBean("Beta"); student1.display(); student1.sid(); student2.display(); student2.sid(); } }