Spring MVC Tutorial - What is Dependency Injection


Spring MVC Tutorial - What is Dependency Injection

Dependency Injection is a Software design Pattern that allows removing hard-coded dependencies and making it possible to change them, whether at run-time or compile-time.

When an Object is created in Spring Framework it is not necessary to call it explicitly like for example i am making two classes here.

Class1 :-

public class Test
{
public void showMessage()
{
System.out.println("Hello World");
}
}

now i make an another class for calling the showMessage() method.

public class TestRun
{
public static void main(String st[])
{
Test t=new Test();
t.showMessage();
}
}

The above method is hard coding method to create an Object explicitly but the Spring Framework provide certain classes for doing this automatically with the help of a XML file this technique is called Dependency Injection 


to do this we need to change the TestRun class as below.



public class TestRun
{
public static void main(String st[])
{
BeanFactory factory=new XmlBeanFactory(new FileSystemResourse("spring.xml"));
Test t=(Test)factory.getBean("test");
t.showMessage();
}
}

Now we need to map the bean into XML file like this.



<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans SYSTEM "http://www.springframework.org/dtd/spring-beans-2.0.dtd" PUBLIC "-//SPRING//DTD BEAN 2.0//EN">

<beans>
<bean id="test" class="Test"/>

</beans>




{ 0 comments... read them below or add one }

Post a Comment