In this particular article we will see one of the 5 autowiring strategy in spring, auto-wiring with type means if a bean type is same as the type of a property in another bean, wire it. For example if we have a Orange bean (orange) and another bean Apple(apple) has a property with type Orange auto-wire orange 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 type

spring-conf.xml

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



	
	




Test: auto-wite by type 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 type in orange and method is called accordingly as shown below:

Apple bean.


To auto-wire by type in spring we have to do following things:

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



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

// wired automatically by type
Apple apple;
Name of called bean dont need to be same, as wiring will be resolved based on type and not name.

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