Donate : Link
Medium Blog : Link
Applications : Link
Spring Tutorial Index Page: Link
- Simple definition of DI is passing required parameters to POJO classes from xml.
- Dependency Injection is a fundamental aspect of the Spring framework, through which the Spring container “injects” objects into other objects or “dependencies”.
- Spring use IOC to get runtime parameters from spring.xml and pass to POJO. To receive parameters from IOC to POJO class it need to have setters method or parameterized constructor.
- * Dependency Injection (DI) Type
Create Java Project
- Open Eclipse
- Go to File -> New -> Others… -> Java Project
- Create DI project
- Right click on project -> Build Path -> Configure Build Path -> Libraries tab -> Add External JARs
- commons-logging-X.X.jar
- spring-beans-X.X.X.jar
- spring-context-X.X.X.jar
- spring-core-X.X.X.jar
- spring-expression-X.X.X.jar
- * You can find dtd information from spring-beans-X.X.X.jar -> org -> springframework -> beans -> factory -> xml -> spring-beans.dtd (line no 36 & 37)

spring.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="t" class="com.codeFactory.beans.Test">
<property name="gender" value="Mr." />
</bean>
</beans>
Test.java
package com.codeFactory.beans;
/**
* @author code.factory
*
*/
public class Test {
String gender;
public void setGender(String gender) {
this.gender = gender;
}
public void hello(String name) {
System.out.println("Hello " + gender + " " + name);
}
}
Client.java
package com.codeFactory.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codeFactory.beans.Test;
/**
* @author code.factory
*
*/
public class Client {
public static void main(String... args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/codeFactory/resources/spring.xml");
Test t = (Test) context.getBean("t");
t.hello("CodeFactory");
}
}
Output:
Dec 11, 2020 7:18:09 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4bf558aa: startup date [Fri Dec 11 19:18:09 IST 2020]; root of context hierarchy
Dec 11, 2020 7:18:09 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/codeFactory/resources/spring.xml]
Hello Mr. CodeFactory

