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:

screenshot1


32 comments to Developing A Simple Java Application With Spring

Leave a Reply

  

  

  

*

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>