Spring Bean Autowiring (XML)

Beans properties can be auto-wired “auto-set”!


  • How to autowire?
  • Different ways to autowire?


  • Eclipse (Indigo)


  • Spring Framework

For more info on how to setup Spring application see First Time Spring

The application

( 1 ) Java Code (Circle.java + ShapeBox.java + Main.java)


package com.hmkcode.beans.shapes;

public class Circle  {
//these variables (autowire & id) has nothing to do with spring autowire
//just to be used in output
    private String autowire;
    private String id;
	public Circle(){		


package com.hmkcode.beans;

import com.hmkcode.beans.shapes.Circle;

public class ShapeBox {

	private Circle circle;

	public ShapeBox(){

	public ShapeBox(Circle circle){
		System.out.println("ShapeBox autowire "+circle.getId()+" by constructor");	
	public Circle getCircle() {
		return circle;

	public void setCircle(Circle circle) {
		this.circle = circle;
		System.out.println("ShapeBox autowire "+circle.getId()+" by "+circle.getAutowire());



package com.hmkcode;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

	public static ApplicationContext ctx;
	public static void main(String args[]){

		// Laod spring-config.xml file
		ctx = new ClassPathXmlApplicationContext("com/hmkcode/config/spring-config.xml");



( 2 ) XML Configuration (spring-config.xml)

<?xml version="1.0" encoding="UTF-8"?>
	<beans 	xmlns="http://www.springframework.org/schema/beans"



	<bean id="circle" class="com.hmkcode.beans.shapes.Circle" autowire-candidate="false">
		<property name="autowire" value="name"></property>
		<property name="id" value="circle"></property>	
	<bean id="circle2" class="com.hmkcode.beans.shapes.Circle">
		<property name="autowire" value="type"></property>
		<property name="id" value="circle2"></property>	

	<!--shapeBox no wiring! -->
	<bean id="shapeBox" class="com.hmkcode.beans.ShapeBox" />

	<!--shapeBox wire by name -->
	<bean id="shapeBox2" class="com.hmkcode.beans.ShapeBox" autowire="byName" />

	<!--shapeBox wire by type -->
	<bean id="shapeBox3" class="com.hmkcode.beans.ShapeBox" autowire="byType" />

	<!--shapeBox wire by constructor -->
	<bean id="shapeBox4" class="com.hmkcode.beans.ShapeBox" autowire="constructor" />


( 3 ) Test Application

You should get the following result

( 4 ) Explain!

  • shapeBox has no wiring.
  • shapeBox2 autowire=”byName” -> shapeBox2.setCircle(bean named cirlce)
  • ShapeBox3 autowire=”byType” -> shapeBox3.setCirlce(bean of type Cirlce)
  • shapeBox4 autowire=”constructor” -> new ShapeBox(bean of type Cirlce)
  • autowire-candidate=”false” -> ignore when autowire by type

( 5 ) Autowire All Beans

Instead of adding autowire=”…” to each bean you can add default-autowire=”byType” once to the <beans> tag “root tag”.

Download Source Code: Autowire.zip