In Spring, “Autowiring by Constructor” is actually autowiring by Type in constructor argument. It means, if data type of a bean is same as the data type of other bean constructor argument, auto wire it.


  1. Create an class
  2. package com.java2learn.core;
    public class Engine {
    	private String engineID;
    	private String validity;
    	public String getEngineID() {
    		return engineID;
    	public void setEngineID(String engineID) {
    		this.engineID = engineID;
    	public String getValidity() {
    		return validity;
    	public void setValidity(String validity) {
    		this.validity = validity;
    	public String toString() {
    		return "Engine [engineID=" + engineID + ", validity=" + validity + "]";
  3. Create class.
  4. package com.java2learn.core;
    public class Truck {
    	private Engine engine;
    	public Truck(Engine engine) {
    		this.engine = engine;
    	public Engine getEngine() {
    		return engine;
  5. Configure Truck and Engine classes in Spring-Core.xml configuration file.
  6. <beans xmlns=""
    	<bean id="engine" class="com.java2learn.core.Engine">
    		<property name="engineID" value="123"></property>
    		<property name="validity" value="3Yrs."></property>
    	<bean id="truck" class="com.java2learn.core.Truck"  autowire="constructor"/>
  7. Create the client program.
  8. package;
    import org.springframework.context.ApplicationContext;
    import com.java2learn.core.Truck;
    public class ApplicationContextDemo {
    	public static void main(String[] args) {
    		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("Spring-Core.xml");
    		Truck truck=(Truck)applicationContext.getBean("truck");
    		System.out.println("Engine ID::"+truck.getEngine().getEngineID());

    Engine ID::123