In Spring, If the name of a bean is same as the name of other bean property is called “Autowiring by Name“.

Example:

  1. Create an Engine.java 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;
    	}
    	@Override
    	public String toString() {
    		return "Engine [engineID=" + engineID + ", validity=" + validity + "]";
    	}
    }
    
  3. Create Truck.java class.
  4. package com.java2learn.core;
    
    public class Truck {
    	
    	private Engine engine;
    
    	public Engine getEngine() {
    		return engine;
    	}
    
    	public void setEngine(Engine engine) {
    		this.engine = engine;
    	}
    
    }
    
  5. Configure Truck and Engine classes in Spring-Core.xml configuration file.
  6. <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-3.0.xsd">
    
    	<bean id="engine" class="com.java2learn.core.Engine">
    		<property name="engineID" value="123"></property>
    		<property name="validity" value="3Yrs."></property>
    	</bean>
    	<bean id="truck" class="com.java2learn.core.Truck"  autowire="byName"/>
    	
    </beans>
    
  7. Create the client program.
  8. package com.java2learn.app;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    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("Validity::"+truck.getEngine().getValidity());
    		System.out.println("Engine ID::"+truck.getEngine().getEngineID());
    		
    	}
    }
    

    Output:
    Validity::3Yrs.
    Engine ID::123