Spring - Dependency Injection
Dependency Injection using primitives & String
Sample Program for Dependency Injection without using 'Spring Framework'
package com.ah.di.setterdemo;
public class Test {
public static void main(String[] args) {
Car car = new Car();
car.setCarName("Ford");
car.displayCarInfo();
}
}
package com.ah.di.setterdemo;
public class Car {
private String carName;
public void setCarName(String carName) {
this.carName = carName;
}
public void displayCarInfo(){
System.out.println("Displaying car information"+
"\n car name : "+carName);
}
}
Maven Dependency:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.16</version>
</dependency>
Sample Program for Dependency Injection using 'Spring Framework'
beans_di_setter.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 id="car" class="com.ah.di.setterdemo.Car">
<property name="carName" value="Ford"/>
<property name="mileage" value="28"/>
</bean>
</beans>
package com.ah.di.setterdemo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans_di_setter.xml");
Car carObj = context.getBean("car", Car.class);
carObj.displayCarInfo();
}
}
package com.ah.di.setterdemo;
public class Car {
private String carName;
private int mileage;
public void setMileage(int mileage) {
this.mileage = mileage;
}
public void setCarName(String carName) {
this.carName = carName;
}
public void displayCarInfo(){
System.out.println("Displaying car information"+
"\n car name : "+carName+
"\n mileage : "+mileage);
}
}
Watch Demo
No comments:
Post a Comment