Sunday 26 June 2022

Spring Part 03 - Constructor Injection

 Spring - Construction Injection

Maven Dependency:

<dependency>

  <groupId>org.springframework</groupId>

  <artifactId>spring-context</artifactId>

  <version>5.3.16</version>

</dependency>


Sample Program for Construction 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="commonEngine" class="com.ah.di.Engine"/>

    <bean
id="car1" class="com.ah.di.Car">
        <constructor-arg
name="engine" ref="commonEngine"/>
    </bean>

    <bean
id="car2" class="com.ah.di.Car">
        <constructor-arg
name="engine" ref="commonEngine"/>
    </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) {

   
/*     Engine engine = new Engine();
        Car car = new Car(engine);
        car.callEngine();*/

/*        Car car = new Car(new Engine());
        car.callEngine();*/

        
ApplicationContext context = new ClassPathXmlApplicationContext("beans_di.xml");
        
Car carObj1 = context.getBean("car1",Car.class);
        
carObj1.callEngine();

        
Car carObj2 = context.getBean("car2",Car.class);
        
carObj2.callEngine();
    
}
}


package com.ah.di;
public class
Engine {
   
public Engine() {
        System.
out.println("Engine constructor.");
   
}
   
public void engineInfo(){
        System.
out.println("engineInfo method of Engine class called.");
   
}
}

package com.ah.di;
public class
Car {
   
private Engine engine;
    public
Car(Engine engine) {
       
this.engine = engine;
   
}
   
public void callEngine(){
       
if(engine==null){
            System.
out.println("Engine is dead");
       
}else{
            System.
out.println("Engine is working");
           
engine.engineInfo();
       
}
    }
}


                                                                  Watch Demo


No comments:

Post a Comment