Sunday 26 June 2022

Spring Part 04 - Setter Injection (Class)

Spring - Dependency Injection

Dependency Injection using class

Sample Program for Dependency Injection using 'Spring Framework'

beans_di.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
        https://www.springframework.org/schema/beans/spring-beans.xsd"
>

    <bean 
id="car" class="com.ah.di.Car">
        <property 
name="engine">
            <bean 
class="com.ah.di.Engine"/>
        </property>
    </bean>

</beans>



package com.ah.di;
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.xml");
       
Car car = context.getBean("car",Car.class);
       
car.checkCarEngine();
   
}
}


package com.ah.di;

public class
Car {
   
private Engine engine;

    public void
setEngine(Engine engine) {
       
this.engine = engine;
   
}
   
public void checkCarEngine(){
       
if(engine!=null){
           
engine.testEngine();
       
}else{
            System.
out.println("Engine is dead");
       
}
    }
}

package com.ah.di;
public class
Engine {
   
public void testEngine(){
        System.
out.println("engine is working" );
   
}
}


                                                                         Watch Demo





No comments:

Post a Comment