ONJava.com    
 Published on ONJava.com (http://www.onjava.com/)
 See this if you're having trouble printing code examples


Five Things I Love About Spring

by , coauthor of Spring: A Developer's Notebook
05/11/2005

On a sweltering June morning more than 15 years ago, I climbed into an old fiberglass kayak. It was so old that splinters would break off into my fingers, and the paddle was about twice as long as conventional whitewater paddles. I swam more than I boated, but it didn't matter. Fifteen years later, I am still hooked.

About two years ago, I tried out that Spring project that was prominently mentioned on the Hibernate site. It felt just like that old kayak: it fit me perfectly. For hardcore enterprise development, Spring became so deeply woven into my programming that I made it the topic of my fourth Java book, Spring: A Developer's Notebook. In this article, I'll tell you why.

1. Spring Provides Better Leverage

On a river, I've learned to paddle with more of my waist and back, because my arm muscles can't hold up to whole days of paddling on the river. I'm more efficient; I get better leverage. With Spring, I can do more work with each line of code. You'll find extra leverage in many places with Spring, but the biggest is in persistence. Here's a method from the Hibernate data access object:


public List getReservations( ) {
  return getHibernateTemplate( ).find("from Reservation");
}

Notice what you don't see. There's no transaction processing. Spring lets you build configuration code to handle that. You don't have to manage resources by closing the session. You don't have to do your own configuration. You don't have to manage exceptions at this level, because the exceptions are unchecked. You're free to manage them at the most appropriate place. Here's how another Hibernate method would look, without Spring:


public List getBikesOldWay( ) throws Exception {
  List bikes = null;
  Session s = null;
  try {
    s = mySessionFactory.openSession( );
    bikes = s.find("from Bike");
  }catch (Exception ex) {
    //handle exception gracefully
  }finally {
    s.close( );
  }
  return bikes;
}

Spring gives me leverage. I code faster, and maintain less.

2. Spring Enables POJO Programming

After the EJB 2.x debacle, we all look to find ways to express enterprise services without invading each and every bean with a cumbersome model. Sure, we need transactions, security, persistence, and sometimes, remoting. With EJB, I had to learn an extensive API and work through the new tools and deployment process. I was a slave to the services provided by the container. With Spring, I can choose my own services and persistence framework. I program in POJOs and add enterprise services to them with configuration files.

In Spring: A Developer's Notebook, I built a RentaBike application. Instead of a session bean or an entity bean, I called my POJO hibRentaBike; it serves as my data access object. I add the services elsewhere. The Spring configuration file, called a context, is an XML file with all of the beans in the container, along with their properties and the services the beans need. Here's a look.

The target:


<bean id="rentaBikeTarget" class="com.springbook.HibRentABike">
  <property name="storeName">
    <value>Bruce's Bikes</value>
  </property>
  <property name="sessionFactory">
    <ref local="sessionFactory"/>
  </property>
  <property name="transactionManager">
    <ref local="transactionManager"/>
  </property>
</bean>

The interceptor:



<bean name="transactionInterceptor" 
    class="org.springframework.transaction.interceptor.TransactionInterceptor">
  <property name="transactionManager">
    <ref local="transactionManager"/>
  </property>
  <property name="transactionAttributeSource">
    <value>
      com.springbook.RentABike.transferReservation=
      PROPAGATION_REQUIRED,-ReservationTransferException
      com.springbook.RentABike.save*=PROPAGATION_REQUIRED
      com.springbook.RentABike.*=PROPAGATION_REQUIRED,readOnly
    </value>
  </property>
</bean>

The proxy:



<bean id="rentaBike" class="org.springframework.aop.framework.ProxyFactoryBean">
  <property name="proxyInterfaces">
    <value>com.springbook.RentABike</value>
  </property>
  <property name="interceptorNames">
    <value>transactionInterceptor,rentaBikeTarget</value>
  </property>
</bean>

Notice three different beans: the proxy, the target, and the interceptors. The proxy will call the POJO, and also any services needed by the POJO. Interceptors contain glue code that invokes the service. They also specify how to treat each method in the target. Anyone needing to access RentaBike calls the proxy, which calls the transactional interceptor, which begins a transaction, and calls the target (the POJO). The target does its thing, returns to the interceptor (which commits the transaction), and returns to the proxy and the caller of the proxy.

Figure 1
Figure 1. POJO programming in action

You build your program out of POJOs and configure it, and Spring hides the rest from you. I'm a POJO programmer.

3. Dependency Injection Helps Testability

Spring greatly improves your testability through a design pattern called Dependency Injection (DI). When a consumer depends on a dependency (we'll call it a service), you'll create a property on the consumer. Spring will create the consumer and the service, and set the consumer's property to the value of the service. Said another way, Spring manages the lifecycle of the beans in the context, and resolves dependencies. Here's an example of dependency injection, without Spring. First, here's the consumer, which serves as a primitive view for the application:


public class CommandLineView {

  private RentABike rentaBike;

  public CommandLineView( ) {rentaBike = new ArrayListRentABike("Bruce's Bikes"); }

public void setRentABike(RentABike rentABike){

  this.rentABike = rentABike;

}

  public void printAllBikes( ) {
    System.out.println(rentaBike.toString( ));
    Iterator iter = rentaBike.getBikes().iterator( );
    while(iter.hasNext( )) {
      Bike bike = (Bike)iter.next( );
      System.out.println(bike.toString( ));
    }
  }

  public static final void main(String[] args) {
    CommandLineView clv = new CommandLineView( );
    clv.printAllBikes( );
  }

}

Next, here's the service, which is the model. It's a simple implementation with an array list. It has a dependency upon the model (RentaBike):


interface RentABike {
List getBikes( );
Bike getBike(String serialNo);
}

public class ArrayListRentABike implements RentABike {
   private String storeName;
   final List bikes = new ArrayList();
   public ArrayListRentABike(String storeName) {
      this.storeName = storeName;
      bikes.add(new Bike("Shimano", "Roadmaster", 20, "11111", 15, "Fair"));
      bikes.add(new Bike("Cannondale", "F2000 XTR", 18, "22222",12,"Excellent"));
      bikes.add(new Bike("Trek","6000", 19, "33333", 12.4, "Fair"));
   }

   public String toString() { return "RentABike: " + storeName; }
   public List getBikes() { return bikes; }
   public Bike getBike(String serialNo) {
      Iterator iter = bikes.iterator();
      while(iter.hasNext()) {
         Bike bike = (Bike)iter.next();
         if(serialNo.equals(bike.getSerialNo())) return bike;
      }
      return null;
   }
}

Here's an assembler. The code in bold is the dependency injection. The assembler instantiates the service and the consumer, and resolves the dependency by setting the rentaBike property:


public class RentABikeAssembler {
  public static final void main(String[] args) {
    CommandLineView clv = new CommandLineView( );
    RentABike rentaBike = new ArrayListRentABike("Bruce's Bikes");
    clv.setRentaBike(rentaBike);
    clv.printAllBikes( );
  }
}

Of course, Spring will eventually fill the role of the assembler. If you wrap the service in an interface, then you'll be able to inject any implementation of the interface into the container.

Dependency injection lets you code a production dependency and a test dependency. For example, this example creates a stub object that makes testing the view easier. (For more about stubs and mocks, read "Mocks Aren't Stubs.")

You've already seen the Hibernate implementation of RentaBike, and the array list version. I may not want to run all of my user interface tests on the full Hibernate implementation. Instead, I simply implement the interface another way, with an array list.

Dependency injection lets me wire up a production version (with HibRentaBike), a development version (with an ArrayListRentaBike list), and a test version (with a mock object). When I'm coding in Java, I've got to have Dependency Injection to get those mocks into hard-to-reach places.

4. Inversion of Control Simplifies JDBC

JDBC applications are ugly, verbose, and tedious. A good abstraction layer can help. Spring lets you customize a default JDBC method with a query and an anonymous inner class to eliminate much of the drudge work. Here's a simple JDBC example:


JdbcTemplate template = new JdbcTemplate(dataSource); 
final List names = new LinkedList();

template.query("SELECT USER.NAME FROM USER", 
  new RowCallbackHandler() { 
      public void processRow(ResultSet rs) throws SQLException {
        names.add(rs.getString(1));
      }
  }
); 

Related Reading

Spring: A Developer's Notebook
By Justin Gehtland

Think of the template.query method as a default JDBC method. Spring will execute the processRow method in the anonymous inner class for each line in the result set. You configure the data source in the context. You don't have to worry about opening or closing the statement or connection, configuring the data source, or managing transactions. You don't specify an outer result set, or manage exceptions at the lowest levels, because Spring folds your SQLException to a common set of unchecked exceptions. Other languages like Ruby and Smalltalk often use inversion of control with code blocks, but it's not very common in Java. Inversion of control simply rocks.

5. Spring's Community Thrives

Some open source projects don't need to be particularly active to be useful. JUnit, for example, does a targeted job, and has basically everything that you need, if you like the programming model. Lightweight containers like Spring need a vibrant community. Spring has one of the most active communities you can find, and you get lots of benefits:

The Spring community makes using the framework much easier. I can hire Spring developers and get them training. I can read books to supplement my knowledge, and get components for just about everything I need to do. I can't find a community for any other lightweight container that comes close.

Resources

If you want to read more, there are a whole lot of places you can go.


In April 2005, O'Reilly Media, Inc., released Spring: A Developer's Notebook.


Return to ONJava.com.

Copyright © 2009 O'Reilly Media, Inc.