Professional Documents
Culture Documents
12 Sep 2006 Apache Geronimo is making news with its latest release, version 1.1. At its core is the Inversion Of Control (IoC) model, which is also the core pattern for the Spring Framework, a layered Java Platform, Enterprise Edition (Java EE) and Java 2 Platform, Enterprise Edition (J2EE) application framework developed under the Apache License. The Spring Framework was built on the principle that Java EE should be easier to use. This six-part tutorial series covers the complete Spring Framework, front to back, including how to implement its functionality with Apache Geronimo. This installment, Part 1 of the series, introduces you to the Spring Framework architecture and explores the intersection between Geronimo and Spring.
Development methodology Copyright IBM Corporation 1994, 2008. All rights reserved.
Page 1 of 19
developerWorks
ibm.com/developerWorks
Showing the phonebook Showing details of each entry Adding a new entry to the phonebook Editing, modifying, and deleting an entry This installment, Part 1, introduces each module of the Spring Framework and how each relates to the development of Java EE applications on the Geronimo application server. It also explains the methodologies that the Spring Framework is based on. Part 2 goes over how to build your first bare-bones application using the Spring Framework on Geronimo. In Part 3, you'll extend the Geronimo application from Part 2 by adding Java Database Connectivity (JDBC) support via the Apache Derby database. You'll also learn how to integrate object-relational mapping to your application using iBatis. In Part 4, you'll meet Spring aspect-oriented programming (AOP) and Spring Web Framework. With the Spring AOP, any object managed by the Spring Framework can become aspect oriented, and this tutorial relies on the declarative transaction management services provided via the Spring AOP. Part 5 takes a look at the Spring Model-View-Controller (MVC). This tutorial gets you started with the Spring MVC by introducing you to its MVC framework and Web views. In Part 6, the conclusion of the series, you'll learn how to use JavaServer Pages (JSP), Velocity, Tiles, and PDF export using the Spring Framework. You'll use and experiment with various Web views built into the Spring MVC.
ibm.com/developerWorks
developerWorks
to solve this problem but have fallen short. Because Spring and Geronimo both use IoC as their core pattern of design, this level of configuration separation is now possible. It also simplifies the testing of each component. Components developed with the Spring Framework and deployed on Geronimo are easier to test independently because they are decoupled from other components on whom they might have a dependency. This tutorial prepares you for the rest of the series by introducing each module of the Spring Framework and how each relates to the development of Java EE applications on the Geronimo application server.
Prerequisites
This tutorial assumes that you're familiar with object-oriented programming (OOP) and that you're comfortable with Java EE terminology. An understanding of aspect-oriented programming is a plus, but isn't required.
System requirements
You will need at least the following tools to follow along with the series: Spring Framework -- You'll use the .zip file with all dependencies. Apache Geronimo -- Geronimo is a J2EE-certified application server from Apache. Apache Derby database -- This tutorial uses Derby, which is an open source, lightweight database. Derby is embedded within Geronimo, so no separate installations are required. Java 1.4.2 from Sun Apache Ant -- Make sure that Apache Ant is installed and configured properly and that its /bin directory is in your Path system variable. Each tutorial will have a list of other tools and APIs that will be needed for that particular tutorial.
Development methodology Copyright IBM Corporation 1994, 2008. All rights reserved.
Page 3 of 19
developerWorks
ibm.com/developerWorks
ibm.com/developerWorks
developerWorks
Both Geronimo and the Spring Framework allow you to loosely couple the various components of an application. Both use IoC (also known as dependency injection) to achieve this decoupling. Neither tries to reinvent the wheel; instead both try to make use of existing open source APIs wherever possible. IoC is a design pattern that helps eliminate coupling between OOP components. It does so by removing the dependency of an object (X) to another object (Y). There are different ways to implement IoC, but in basic terms it's achieved by introducing an interface for X and Y to interact with each other. The Spring Framework container takes care of dependency resolution and life cycle of that object at run time.
Development methodology Copyright IBM Corporation 1994, 2008. All rights reserved.
Page 5 of 19
developerWorks
ibm.com/developerWorks
//Create an XMLBeanFactory by specifying the configuration // file as a FileSystemResource Resource resource = new FileSystemResource("beans.xml"); XMLBeanFactory beanFactory = new XMLBeanFactory(resource);
A BeanFactory configuration consists of, at its most basic level, definitions of one or more beans that the BeanFactory must manage. In an XmlBeanFactory, these are configured as one or more bean elements inside a top-level beans element (see Listing 3). Listing 3. An XmlBeanFactory
<beans> <bean id="xxxxxx" class="yyyyyy"> ... </bean> ... </beans>
There's a lot more to BeanFactory, which is covered in later parts of this series.
ibm.com/developerWorks
developerWorks
As explained in the previous section, the BeanFactory provides the configuration framework and basic functionality for your applications, while the ApplicationContext adds enhanced capabilities to it. Because ApplicationContext is a subclass of BeanFactory, it has all the functionality that BeanFactory provides and adds a lot of specialized features to it. Some of them are: Easier integration with Spring AOP features. Message resource handling, for use in i18n (internationalization). Access to resources, such as URLs and files. Event handling and propagation to beans implementing the ApplicationListener interface. Advanced declarative mechanisms for transparent creation of different contexts, such as optional parent contexts and application layer-specific contexts (for example, WebApplicationContext). The ApplicationContext construct is a complete superset of a BeanFactory, and any references to functionalities of BeanFactory should be considered to apply to ApplicationContext as well. It might get confusing sometimes to decide whether to use a BeanFactory or an ApplicationContext in a particular situation. Because the ApplicationContext provides all the features of the BeanFactory and adds on to it in terms of features -- along with allowing the more declarative approach to use some functionality -- it should be preferred over BeanFactory. In cases when memory usage is of greater concern, such as an applet where every last kilobyte counts, it should be OK to use BeanFactory. You'll learn more about ApplicationContext and how to define and use it in Part 2 of this series.
AOP in brief
Before discussing AOP, first look at object-oriented programming. OOP decomposes the application into a number of interoperating objects. The modularity factor in this
Development methodology Copyright IBM Corporation 1994, 2008. All rights reserved.
Page 7 of 19
developerWorks
ibm.com/developerWorks
case is still primarily focused on objects. AOP extends this concept by focusing on Aspects or Concerns rather than objects. AOP decomposes the application into Aspects or Concerns that may otherwise span multiple objects. Transactions and Pooling are some of the aspects.
ibm.com/developerWorks
developerWorks
exception thrown by the underlying data access technology and show it to you in a standard and understandable format. Abstract classes for DAO support To make it easier to work with a variety of data access technologies like JDBC, JDO, and Hibernate in a consistent way, Spring provides a set of abstract DAO classes that you can extend. These abstract classes have methods for setting the data source and any other configuration settings that are specific to the technology you're currently using. The DAO support classes include: JdbcDaoSupport: Superclass for JDBC data access objects. Requires a DataSource to be set, providing a JdbcTemplate based on it, to subclasses. HibernateDaoSupport: Superclass for Hibernate data access objects. Requires a SessionFactory to be set, providing a HibernateTemplate based on it, to subclasses. JdoDaoSupport: Superclass for JDO data access objects. Requires a PersistenceManagerFactory to be set, providing a JdoTemplate based on it, to subclasses. Now let's look at how the Spring Framework supports data access using JDBC. Data access using JDBC There are a lot of pros and cons of using traditional JDBC in Java Platform, Standard Edition (Java SE) and Java EE applications. And there are some characteristics of JDBC that make it more difficult to use than one might like. Some of these are: The application developer has to write long and tedious try-catch blocks for even a small database function. The most common mistake by JDBC users is failure to properly close connections. This leaves a lot of such resources unavailable for other tasks. JDBC has no exception hierarchy. JDBC's SQLException is too generic and doesn't provide enough information about the problem. The JDBC support in the Spring Framework tries to overcome these problems in a very distinctive way. Simply stated, it abstracts the connection handling and
Development methodology Copyright IBM Corporation 1994, 2008. All rights reserved.
Page 9 of 19
developerWorks
ibm.com/developerWorks
database-related resource management functions away from the developer, enabling more consistent resource closures and more readable code. The JDBC abstraction framework provided by Spring consists of four different packages -- the core, datasource, object, and support packages. The core package contains the JdbcTemplate class. It follows the template pattern most commonly used in Web applications. The JdbcTemplate class is the central class in the JDBC core package. The datasource package contains a utility class for easy DataSource access. It also contains various DataSource implementations for testing database access code. The object package contains classes that represent relational database management systems (RDBMS) queries, updates, and stored procedures as threadsafe, reusable objects. The support package contains a lot of utility classes and SQLException translation functionality. You'll learn more about how Spring uses the template pattern to simplify your JDBC code in later installments of this series.
ibm.com/developerWorks
developerWorks
Ease of testing: As suggested above, Spring's IoC approach makes it easy to swap the implementations and configuration locations of different object-relation related entities. This makes it easy to test each piece of persistence-related code in isolation. Common data access exceptions: Spring can wrap exceptions from your ORM tool of choice into a defined set of exceptions that are understandable. Integrated transaction management: Spring takes care of both transaction semantics and proper transaction handling for you for operations like rollback; the framework takes care of exceptions. Avoiding vendor lock-in and allowing mix-and-match implementation strategies: Using Spring's decoupled approach, it's quite possible to use and change different APIs and implementations at run time. Therefore, you're not locked into using products and services from a particular vendor. You can mix and match according to your needs. Spring facilitates resource management, DAO implementation support, and transaction strategy integration with several ORM tools, such as Hibernate, JDO, Oracle Top Link, Apache ObJectRelationalBridge (OJB), and iBATIS SQL Maps. The next section looks at each of the integration strategies with Hibernate as the underlying API.
Development methodology Copyright IBM Corporation 1994, 2008. All rights reserved.
Page 11 of 19
developerWorks
ibm.com/developerWorks
destroy-method="close"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/> <property name="username" value="XXXX"/> <property name="password" value="YYYY"/> </bean> <bean id="mySessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean"> <property name="dataSource" ref="myDataSource"/> <property name="mappingResources"> <list> <value>product.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> net.sf.hibernate.dialect.MySQLDialect </prop> </props> </property> </bean> ... </beans>
Listing 6 shows an example of a DAO method implementation. Listing 6. Example of a DAO method implementation
public class EmployeeDaoImpl implements EmployeeDao { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; }
ibm.com/developerWorks
developerWorks
public Collection loadEmployeesByDepartment(final String department) throws DataAccessException { HibernateTemplate ht = new HibernateTemplate(this.sessionFactory); return (Collection) ht.execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query query = session.createQuery( "from test.Employee employee where employee.department=?"); query.setString(0, department); return query.list(); } }); } }
A callback implementation can be effectively used for any Hibernate data access. HibernateTemplate ensures that sessions are properly opened and closed and automatically participate in transactions. The template instances are threadsafe and reusable, so they can be kept as instance variables of the surrounding class.
Transaction strategies
The key to the Spring transaction abstraction is the notion of a transaction strategy. This is captured in the org.springframework.transaction.PlatformTransactionManager interface. Listing 7 shows a simple example of how to use it. Listing 7. Example showing use of PlatformTransactionManager
public interface PlatformTransactionManager { TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException; void commit(TransactionStatus status) throws TransactionException; void rollback(TransactionStatus status) throws TransactionException; }
You'll learn more about different transaction strategies in Part 4 of this series.
Development methodology Copyright IBM Corporation 1994, 2008. All rights reserved.
Page 13 of 19
developerWorks
ibm.com/developerWorks
listeners, and a Web-oriented application context. When using Spring together with WebWork or Struts, this is the package to integrate with.
SWF advantages
SWF advantages include the following: SWF is a self-contained module. This allows you to design reusable Web flows, which can be used in similar situations. SWF is easy to use because of its well-defined constructs. It has a clear, configurable life cycle, which is automatically managed by the container. The page flow in a Web application is clearly visible by looking at the corresponding Web flow definition (in an .xml file or Java class). As suggested above, SWF can be easily plugged into other frameworks.
ibm.com/developerWorks
developerWorks
In short, SWF is a powerful controller framework based on a finite-state machine, fully addressing the C in MVC. You'll learn more about SWF in future installments of this series.
MVC architecture
The MVC architecture is a widely used architectural approach for Web-based applications. It divides applications into the three layers of model, view, and controller and decouples their respective responsibilities. Each layer handles specific tasks and has specific responsibilities to the other areas. In short, a model represents business data and business logic. A view renders the contents of a model. It accesses data from the model and specifies how that data should be presented. And the controller defines application behavior. It dispatches user requests and selects views for presentation. The Spring Framework provides a well-thought-out MVC framework for building Web applications. Spring's MVC Web application framework is built on core Spring functionality. It's a request-based framework comparable to Struts, but attempts to overcome flaws present in Struts. The Spring MVC framework defines different strategy interfaces for all responsibilities that have to be handled by a modern request-based framework. The responsibility of each such interface is sufficiently simple and clear so that it's easy for Spring MVC users to write their own implementations if they choose to. Spring's Web MVC framework is designed around a DispatcherServlet that works as the front controller and is responsible for delegating control to the various interfaces during the execution phases of an HTTP request. The default handler is a very simple controller interface with just one method: ModelAndView handleRequest(request, response). Following are the most important interfaces defined by Spring MVC:
Development methodology Copyright IBM Corporation 1994, 2008. All rights reserved.
Page 15 of 19
developerWorks
ibm.com/developerWorks
HandlerMappings: Using handler mappings, you can map an incoming request to appropriate handlers. Spring MVC also provides a list of preand post-processors and controllers that would be executed on certain conditions, such as matching a URL specified with the controller. HandlerAdapater: Executes the appropriate objects that handle incoming requests. Controller(s): The beans providing the actual functionality of handling incoming requests. The C in the MVC. View Resolver: Capable of resolving view names to views. Locale Resolver: Capable of resolving the locale a client is using for i18n support. Theme Resolver: If your application offers personalized views, based on themes, this object is capable of resolving those themes. Multipart Resolver: Offers functionality to process multipart file uploads from HTML forms. One of the most important advantages of the high level of abstraction offered by Spring MVC is that it becomes very easy to test implementations of these interfaces and the whole application itself. The design of DispatcherServlet allows an easy and consistent way to follow the Spring IoC model for configuring the Web layers of applications. You'll learn more about Spring MVC in Part 6 of this tutorial series.
ibm.com/developerWorks
developerWorks
Development methodology Copyright IBM Corporation 1994, 2008. All rights reserved.
Page 17 of 19
developerWorks
ibm.com/developerWorks
Resources
Learn Check out The official Spring Reference Manual, a clean and simple way to learn more about the Spring Framework. Get another good introduction to the Spring Framework in "The Spring series, Part 1: Introduction to the Spring framework" (developerWorks, June 2005). Read "The Spring series, Part 3: Swing into Spring MVC" (developerWorks, September 2005) in which Naveen Balani provides a simple example to explain the Spring Web MVC framework. Read "Why Spring JDBC?," a neat little article on Spring JDBC by Vikram Veeravelu. Familiarize yourself with the Spring Framework by reading "Introduction to the Spring Framework," yet another good introduction written by one of the first and most active members of the Spring design team. Find helpful resources for beginners and experienced users at the Get started now with Apache Geronimo section of developerWorks. Read "Optimize your Apache Geronimo distribution" (developerWorks, May 2006) to learn to hone the deployment of your Apache Geronimo distribution to the necessary core services and applications. See Martin Fowler's seminal piece "Inversion of Control Containers and the Dependency Injection pattern." Take a look at helpful online and print documentation about Geronimo, including articles and interviews from apache.org. Get involved with Apache Geronimo's community. Find out how to get started with Geronimo in "A first look at Apache Geronimo: Start developing and deploying J2EE apps on Apache's open source J2EE server." Check out the articles in this three-part series to learn all sorts of technologies you can use to develop Geronimo Java EE applications: The Apache Geronimo machine shop sampler, Part 1: Servlets, JSPs, security, and JCA (developerWorks, March 2006) The Apache Geronimo machine shop sampler, Part 2: Data sources, JDBC, and Web services (developerWorks, April 2006) The Apache Geronimo machine shop sampler, Part 3: EJBs: Bean-managed persistence and container-managed persistence
ibm.com/developerWorks
developerWorks
(developerWorks, April 2006) Visit the developerWorks Open source zone for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM products. Check out the developerWorks Apache Geronimo project area for articles, tutorials, and other resources to help you get started developing with Geronimo today. Get the IBM Support for Apache Geronimo offering, which lets you develop Geronimo applications backed by world-class IBM support. Get involved in the developerWorks community by participating in developerWorks blogs. Browse all the Apache articles and free Apache tutorials available in the developerWorks Open source zone. Check out the book Expert One-on-One J2EE Design and Development by Rod Johnson. Get products and technologies Get the EJB 2.1 specification. Download the latest version of Apache Geronimo. Innovate your next open source development project with IBM trial software, available for download or on DVD. Download your free copy of IBM WebSphere Application Server Community Edition V1.0 -- a lightweight J2EE application server built on Apache Geronimo open source technology that is designed to help you accelerate your development and deployment efforts. Discuss Participate in the discussion forum for this content. Stay up to date on Geronimo developments at the Apache Geronimo blog.
Page 19 of 19