Spring XML Configuration and Setter Injection

In this example, we will inject the dependencies of a class using setter injection. For setter injection, if class A refers to another class called as B, then A should expose a setter method with B as its argument.

Use Case

The use case that we implement is like the one we did using constructor injection.

We write a mock UserDAO class to retrieve User list. UserService class will access this UserDAO class to fetch user list. UserService class needs an instance of UserDAO.

In this example, we provide the UserDAO instance to UserService using a setter injection.

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-si</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 List<User> findAll() {
		return userDao.findAll();
	}

	public void setUserDao(UserDAO userDao) {
		this.userDao = userDao;
	}

}

In this UserServiceImpl class, you can observe that we have a setter method where the dependency UserDAO instance will be injected.

Wiring Beans in Application Context using Setter 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="hibernateUserDao" 
	      class="com.techstackjournal.dao.HibernateUserDAOImpl" />

	<bean name="userService" 
		  class="com.techstackjournal.service.UserServiceImpl">
		  <property name="userDao" ref="hibernateUserDao"/>
		
	</bean>

</beans>

Here, you can see that we are passing the bean “hibernateUserDao” into userService bean property attribute ref.

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