Spring constructor based dependency injection

February 15, 2018

You can use constructor-arg tag to pass string literal and you can use value attraibute to pass the name of the Car which you create

So your Car class would be like this

 
package com.kayak;

public class Car {

    private String name;

    public Car(String name) {
      this.name= name;
    }

    public String getName() {
        return name;
    }

}

You can create the configuration file with the following code. In this code, I have used constructor-arg with the value attribute

 




    
         
    
   
    

Now you can test the above code with following code

 
package springstrat;

import com.kayak.Car;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class SpringStrat {


    public static void main(String[] args) {
        
        ApplicationContext ctx = new  ClassPathXmlApplicationContext("bean.xml");
        Car car=(Car)ctx.getBean("car");
        System.out.println(car.getName());
        
    }
    
}