Spring XML Configuration and Constructor Injection

This is an example to show you how we can inject dependencies using constructor injection within Spring XML configuration.

Use Case

Our use case is simple, we want to establish the dependencies between app, service and data access layers.

We want to retrieve list of users from database (mocked in our case) using a data access object. Service refers to the data access object to fetch the users.

As part of this example, we will create HibernateUserDAOImpl which implements UserDAO interface.

UserServiceImpl refers to UserDAO to fetch the users and it implements UserService interface.

Our app, Application refers to UserService to fetch the user list.

Creation of Maven Project

First create a simple Maven project by skipping archtype selection in STS.

Add below pom.xml file which can be found at the root of the project.

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.techstackjournal</groupId>
	<artifactId>xml-config</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.2.RELEASE</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Right click on the project, and select Maven=>Update Project, to download all the dependencies.

Creation of Model Object

User class is a POJO class to hold the individual user objects.

package com.techstackjournal.model;

public class User {

	private String userId;
	private String firstName;
	private String lastName;
	private String email;
	
	public User() {
		// TODO Auto-generated constructor stub
	}
	
	public User(String userId, String firstName, String lastName, String email) {
		super();
		this.userId = userId;
		this.firstName = firstName;
		this.lastName = lastName;
		this.email = email;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	@Override
	public String toString() {
		return "User [userId=" + userId + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email
				+ "]";
	}
	
}

Creation of Data Access Object Layer

Create UserDAO interface in com.techstackjournal.dao package under src/main/java.

package com.techstackjournal.dao;

import java.util.List;

import com.techstackjournal.model.User;

public interface UserDAO {

	List<User> findAll();

}

Create HibernateUserDAOImpl class in com.techstackjournal.dao package under src/main/java. This class supposedly fetch user data from the database, but for simplicity we are mocking user details.

package com.techstackjournal.dao;

import java.util.ArrayList;
import java.util.List;

import com.techstackjournal.model.User;

public class HibernateUserDAOImpl implements UserDAO {
	public List<User> findAll() {
		List<User> users = new ArrayList<User>();
		users.add(new User("1", "John", "Doe", "john.doe@techstackjournal.com"));
		users.add(new User("2", "Jane", "Doe", "jane.doe@techstackjournal.com"));
		return users;
	}
}

Creation of Service Layer

Create UserService interface in com.techstackjournal.service package under src/main/java.

package com.techstackjournal.service;

import java.util.List;

import com.techstackjournal.model.User;

public interface UserService {

	List<User> findAll();

}

Create UserServiceImpl class in com.techstackjournal.service package under src/main/java.

package com.techstackjournal.service;

import java.util.List;

import com.techstackjournal.dao.UserDAO;
import com.techstackjournal.model.User;

public class UserServiceImpl implements UserService {

	private UserDAO userDao;

	public UserServiceImpl(UserDAO userDao) {
		super();
		this.userDao = userDao;
	}

	public List<User> findAll() {
		return userDao.findAll();
	}

}

Wiring Beans in Application Context using Constructor Injection

Create appContext.xml file under src/main/resources to declare and wire the UserDAO and UserService beans together.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean name="userDao" 
	      class="com.techstackjournal.dao.HibernateUserDAOImpl" />

	<bean name="userService" 
		  class="com.techstackjournal.service.UserServiceImpl">
		  <constructor-arg index="0" ref="userDao" />
		
	</bean>

</beans>

Getting the Service Instance in Application

Finally, in our application we’ll get the instance of UserService and call the findAll method to fetch user list.

package com.techstackjournal.app;

import java.util.List;

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

import com.techstackjournal.model.User;
import com.techstackjournal.service.UserService;

public class Application {

	public static void main(String[] args) {

		ApplicationContext appContext = new ClassPathXmlApplicationContext("appContext.xml");

		UserService service = appContext.getBean("userService", UserService.class);

		List<User> users = service.findAll();

		for (User user : users) {
			System.out.println(user);
		}

	}

}

The output of this program would be as below:

User [userId=1, firstName=John, lastName=Doe, email=john.doe@techstackjournal.com]
User [userId=2, firstName=Jane, lastName=Doe, email=jane.doe@techstackjournal.com]

Leave a Comment