Developing A Simple Java Application With Spring
Introduction
Spring is a powerful application framework that can be used across any layer in your application. For example, you can use Spring to manage only your data access layer or you can use Spring to provide remote services for your swing client. In this article, I will explain how to get started with Spring by developing a simple java application.
Requirements
1. Your favorite IDE
2. Latest Spring framework.
(Note: This article makes use of Spring framework 2.5.6 which is the current production release)
The Application
We are going to develop a simple application that fetches and display the list of registered users. The application consists of just two interfaces, their implementation.
The DAO layer
Let us now develop the DAO layer of the application. This layer consists of just one interface “UserDao” and it’s implementation “UserDaoImpl”. The interface consists of just one method named “getUsers()”. Let us quickly develop them.
Listing 1. UserDao
package com.springapp.dao;
import java.util.Iterator;
/**
*
* @author James
*/
public interface UserDao
{
Iterator<String> getUsers();
}
Listing 2. UserDaoImpl
package com.springapp.dao;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
*
* @author James
*/
public class UserDaoImpl implements UserDao
{
public Iterator<String> getUsers()
{
List<String> users = new ArrayList<String>();
users.add("Gavin King");
users.add("Geertjan");
users.add("Mike Keith");
users.add("James");
return users.iterator();
}
}
Nothing fancy here. The implementation is pretty straight forward, though in a real environment you might fetch those details from the database using ORM frameworks like JPA.
The Service Layer
We will encapsulate the service layer from the dao implementaion by writing code against the interface UserDao. We will follow the same pattern we used in developing the dao layer and write the interface UserService and it’s implementation UserServiceImpl.
Listing 3. UserService
package com.springapp.service;
import java.util.Iterator;
/**
*
* @author James
*/
public interface UserService
{
Iterator<String> getUsers();
}
Listing 4. UserServiceImpl
package com.springapp.service;
import com.springapp.dao.UserDao;
import java.util.Iterator;
/**
*
* @author James
*/
public class UserServiceImpl implements UserService
{
private UserDao userDao;
public Iterator<String> getUsers()
{
return userDao.getUsers();
}
public void setUserDao(UserDao userDao)
{
this.userDao = userDao;
}
}
Kindly notice that both the service layer classes and dao layer classes are Spring agnostic. That’s the beauty of Spring. Spring is less invasive. Most of the application code can be developed without knowing anything about Spring.
The Client
Now we need someone to make use of our service layer and we will waste no time in developing the client for our service. We can just write a junit test class to invoke our service but I prefer to write a simple java class to be the client. Though our client will be a simple POJO class, you can easily replace it with a Swing or Web front end. Enough talking, let us dive into action! We will first develop our client as a normal java class without using Spring.
Standard Client
Listing 5. StandardUserServiceClient
package com.springapp;
import com.springapp.dao.UserDao;
import com.springapp.dao.UserDaoImpl;
import com.springapp.service.UserServiceImpl;
import java.util.Iterator;
/**
*
* @author James
*/
public class StandardUserServiceClient
{
private UserServiceImpl userService;
public StandardUserServiceClient()
{
userService = new UserServiceImpl();
UserDao userDao = new UserDaoImpl();
userService.setUserDao(userDao);
}
private void fetchUsers()
{
Iterator<String> users = userService.getUsers();
while (users.hasNext())
{
System.out.println(users.next());
}
}
public static void main(String[] args)
{
StandardUserServiceClient client = new StandardUserServiceClient();
client.fetchUsers();
}
}
Hmm, there you can see our client code is “coupled” tightly with the service and dao implementations. That’s where Spring comes to our rescue. Spring will dynamically “inject” the implemenations so our application will remain “loosely” coupled.
Spring Client
But how will Spring know about our implementations? We need to inform Spring a little about our application and define the “hotspots” where it can dynamically “inject” the dependencies or implementations. Spring expects these details in a configuration file and let us quickly write that. Create a package called “resources” and create a xml file called “applicationContext.xm” inside it.
Listing 6. applicationContext.xml
<?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-2.5.xsd">
<bean id="userDao" class="com.springapp.dao.UserDaoImpl">
</bean>
<bean id="userService" class="com.springapp.service.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
</beans>
In the “applicationContext.xml” file we defiend two beans named “userDao” and “userService”. We also specified their implementations using the “class” attribute. Also notice that we are setting the property “userDao” in the “UserServiceImpl” class with “UserDaoImpl” by referencing it’s name “userDao”. Pretty straighforward!
Now it’s time to churn out our Spring client.
Listing 7. SpringUserServiceClient
package com.springapp;
import com.springapp.service.UserService;
import java.util.Iterator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
* @author James
*/
public class SpringUserServiceClient
{
private UserService userService;
public SpringUserServiceClient()
{
//initialize the spring container
ApplicationContext context = new ClassPathXmlApplicationContext("resources/applicationContext.xml");
userService = (UserService) context.getBean("userService");
}
private void fetchUsers()
{
Iterator<String> users = userService.getUsers();
while(users.hasNext())
{
System.out.println(users.next());
}
}
public static void main(String[] args)
{
SpringUserServiceClient client = new SpringUserServiceClient();
client.fetchUsers();
}
}
A couple of details about this class:
- The ApplicationContext interface helps us to plug into the Spring container and lookup the classes we need by using the name we defined in the xml file.
- There are many implementataions of ApplicationContext available in Spring. One of the most widely used implementation is “ClassPathXmlApplicationContext”. It is used to load Spring configuration files found in classpath.
As seen from Listing 7, Spring helps us to program to interfaces and develop loosely coupled applications. As a result, applications become more testable as there are no external dependencies like application server. It is also very easy to switch the implementations effortlessly. For example, in our sample application you can easily write a UserDaoMockImpl and use it in your test cases effortlessly.
Project Structure
Here is the complete application looks like:


Related posts:
hi, thanks for this simple and clean example for Spring to separate the DAO and service layer. May be can intro some Spring annotation in future
As I recon it just removes tight coupling from servic implementation classes, but adds tight coupling to spring… I think StandardUserServiceClient should get UserService through constructor or some setter method.
I think that application logic code should not be coupled to spring, but only application construction code.
@dendroot
Hi dendroot,
The class “StandardUserServiceClient” doesn’t make use of Spring and shows how the code would be if the services are consumed directly.
@mkyong
Hi Yong,
Yes Spring annotations help to remove much of the xml configurations, but, I like configuring using xml. That makes your application almost unaware of Spring.
@James
I think what dendroot mention is about the following code
ApplicationContext context = new ClassPathXmlApplicationContext(”resources/applicationContext.xml”);
userService = (UserService) context.getBean(”userService”);
Your code is tight coupling to Spring, suggest to use Spring AOP to pass in your userService implementation class
@mkyong
I still couldn’t get you. Could you please explain how to improve the lookup portion?
Thanx.. code is quite helpful to understand spring dependency injection
hey thanks for this example. i have let a lot from it.
ApplicationContext context = new ClassPathXmlApplicationContext
(”resources/applicationContext.xml”);
i don’t understand this part– please can you explain it.
@Styls
Basically we are instructing Spring here to load the application context file which is located in the classpath i.e inside your jar.
James
You saying this code requires a specific jar file..
reason I;m saying this is that, it the only code that is give me some difficulty.
please help.
ApplicationContext context = new ClassPathXmlApplicationContext
(”resources/applicationContext.xml”);
i don’t understand this part– please can you explain it.
@Styls
No you don’t need a specific jar file. This xml file can sit side by side with your java source files. Please see the last image in the post above to get more insight.
@James
thank you man, with the help of Spring and right now i have the basic understanding of Spring framework.
Don’t you have more tutorials on Spring,Hibernate,JSF,Junit and Integrator development.
Please help me James
@styls
great help man thanks