Free tutorials for Java, Eclipse and Web programming



Follow me on twitter

6. Using dependency injection with XML

The following example will demonstrate the usage of the dependency injection via xml. The example will inject a writer into another class.

Tip

I think annotations rock in general, therefore I recommend not to use the XML configuration but the annotation one. If you have good reason to use the XML configuration please feel free to do so.

Create a new Java project "de.vogella.spring.di.xml.first" and include the minimal required spring jars into your classpath.

Copy your model class from the de.vogella.spring.di.model project into this project.

Under the src folder create a folder META-INF and create the following file in this folder. This is the Spring configuration file.

			
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">


<bean id="writer" class="writer.NiceWriter" />

<bean id="mySpringBeanWithDependency" class="testbean.MySpringBeanWithDependency">
<property name="writer" ref="writer" />
</bean>

</beans>
		

Again, you can now wire the application together. Create a main class which reads the configuration file and starts the application.

			
package main;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import testbean.MySpringBeanWithDependency;

public class Main {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"META-INF/beans.xml");
		BeanFactory factory = context;
		MySpringBeanWithDependency test = (MySpringBeanWithDependency) factory
				.getBean("mySpringBeanWithDependency");
		test.run();
	}
}