Spring dependency injection with XML example

26 December 2012
tags: springjava
In this tutorial you will learn how to configure Spring dependency injection using the Spring XML configuration file.

1. Introduction

Spring dependency injection can be configured by using annotations directly in your Java classes. Another available alternative is to specify it in the Spring XML configuration file as we will see in this tutorial. We will use a previous tutorial as the basis for the next following sections:

Spring dependency injection example


This tutorial considers the following software and environment:

  1. Ubuntu 12.04
  2. Maven 3.0.4
  3. JDK 1.7.0.09
  4. Spring 3.2.0

Configure Maven to get the required Spring dependencies:

Maven pom.xml file referencing Spring dependencies
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.byteslounge.spring</groupId>
  <artifactId>com-byteslounge-spring</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>com-byteslounge-spring</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <!-- Define Spring version as a constant -->
    <spring.version>3.2.0.RELEASE</spring.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
  </dependencies>
</project>

Now place yourself in the project directory and issue the following command to prepare your project for Eclipse:

mvn eclipse:eclipse

After conclusion you can import the project into Eclipse.

2. Constructor dependency injection

The goal of this tutorial will be exactly the same of the tutorial Spring dependency injection example with the difference that this time we will define dependency injection in the Spring XML configuration file. We will skip the details and go directly to the Java classes definition. Check the mentioned tutorial for details just in case you need to review something.

First we define the interface of the injected bean:

Injected bean interface
package com.byteslounge.spring;

public interface InjectedBean {

  void doSomething();
	
}

Now we define the implementation:

Injected bean implementation
package com.byteslounge.spring;

public class InjectedBeanImpl implements InjectedBean {

  @Override
  public void doSomething() {
    System.out.println("Bean was correctly injected!");
  }

}

Now we define a simple Spring bean that will receive the injected bean as a dependency in the constructor:

The target Spring bean
package com.byteslounge.spring;

public class ExampleBean {

  private InjectedBean injectedBean;

  // Injected bean will be injected in the constructor
  public ExampleBean(InjectedBean injectedBean) {
    this.injectedBean = injectedBean;
    System.out.println("InjectedBean was injected in constructor.");
  }

  public void callExampleMethod() {
    injectedBean.doSomething();
  }
}

Now we define both beans configuration in Spring XML configuration file:

Spring XML configuration file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    <bean id="injectedBean"
          class="com.byteslounge.spring.InjectedBeanImpl"/>
 
	<bean id="exampleBean" 
             class="com.byteslounge.spring.ExampleBean">
  		<constructor-arg ref="injectedBean"/>
	</bean>
    
</beans>

First we define injectedBean bean and the respective implementation class: com.byteslounge.spring.InjectedBeanImpl. Then we define exampleBean and we define the values that will be used in the constructor. In this case is the other bean - injectedBean - that will be passed to the Example bean constructor. Note the |constructor-arg element.

Now we define a simple Main class that will fetch our exampleBean and invoke callExampleMethod:

Simple Main testing class
package com.byteslounge.spring;

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

public class Main 
{
  public static void main( String[] args )
  {
    ApplicationContext ctx = 
                   new ClassPathXmlApplicationContext("spring.xml");
    ExampleBean exampleBean = (ExampleBean) ctx.getBean("exampleBean");
    exampleBean.callExampleMethod();
  }
}

When we run our simple test the following output will be generated:

InjectedBean was injected in constructor.
Bean was correctly injected!

We now know that the exampleBean was correctly initialized and that injectedBean was correctly passed in the constructor.

3. Setter dependency injection

We can also define the injection to be made by a property setter. Let's change our ExampleBean class a little bit:

The modified target Spring bean

package com.byteslounge.spring;

public class ExampleBean {

private InjectedBean injectedBean;

  // Injected bean will be injected in property setter
  public void setInjectedBean(InjectedBean injectedBean) {
    this.injectedBean = injectedBean;
    System.out.println("InjectedBean was injected in property setter.");
  }

  public void callExampleMethod() {
    injectedBean.doSomething();
  }

}

We also need to change the configuration file:

Modified Spring XML configuration file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    <bean id="injectedBean" 
              class="com.byteslounge.spring.InjectedBeanImpl"/>
 
	<bean id="exampleBean" class="com.byteslounge.spring.ExampleBean">
  		<property name="injectedBean" ref="injectedBean"/>
	</bean>
    
</beans>

This time we are saying that injectedBean will be injected by a property setter. Note the element . Spring will look for a setter named setInjectedBean (derived from injectedBean) and pass the injectedBean bean.

Now when we run the main class the following output will be generated:

InjectedBean was injected in property setter.
Bean was correctly injected!

Now you know how to use Spring dependency injection both in constructor methods and property setters. The tutorial source code can be downloaded in the bottom of this page.

Download source code from this tutorial

Related Articles

Comments

Share this website
Subscribe
Subscribe and receive the latest tutorials by email
Popular tags
Archive
 
About the author
Gonçalo Marques is a Software Engineer with 8+ years of experience in software development and architecture design. During this period his main focus was delivering software solutions both in banking and telecommunications area. He created the Bytes Lounge website with one ultimate goal: share his knowledge with the software development community. His main area of expertise is Java and open source.

He is also the author of the WiFi File Browser Android application:

Google Play logo