In this particular article we will see one of the 5 autowiring strategy in spring, auto-wiring with name means if a bean name is same as the name of a property of another bean, wire it.

For example if we have a Orange bean (orange) and another bean Apple(apple) has a property with name orange auto-wire oramge in apple.

Now lets see the complete example, first of all we have a bean class Apple as shown below:

package com.tbNext.beans;

public class Apple {
	public void printName(){
		System.out.println("Apple bean.");
	}
}

This bean is having an method printName(), we will try to get an instance of Apple in Orange bean and than will call the method.
package com.tbNext.beans;

public class Orange {

	// wired automatically by name
	Apple apple;

	public Apple getApple() {
		return apple;
	}

	public void setApple(Apple apple) {
		this.apple = apple;
	}

	public void printApple() {
		apple.printName();
	}
}

Spring autowiring by name

spring-conf.xml

We have declared two beans apple and orange, where orange is having attribute, autowire="byName". This means all the bean references in orange will be auto-wired by name if any bean with same property is found in context. We dont need to pass a property with id and reference here in orange's definintion.



	
	




Test: auto-wite by name example
Lets now test the implementation:
package com.tbNext.App;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tbNext.beans.Orange;

public class Application {
	public static void main(String args[]) {
		@SuppressWarnings("resource")
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				"spring-conf.xml");

		// Getting instance
		Orange orange = (Orange) applicationContext.getBean("orange");
		orange.printApple();

	}
}

Output: We can see, apple is auto-wired by name in orange and method is called accordingly as shown below:

Apple bean.


To auto-wire with name in spring we have to do following things:

1) Set an attribute autowire="byName" in the calling bean tag.



2) Craete a property with the same name as called bean in calling bean class.

// wired automatically by name
Apple apple;


That's it for this article, we have seen how to auto-wire beans by name in spring, in upcoming articles we see more about Spring and other technologies.
  • By Techburps.com
  • Oct 8, 2015
  • Spring Framework