Spring Blueprint

38
6400 Shafer Court Rosemont, Illinois 60018 847 384 6100 847 384 0500 fax ©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners. The Emperor Has New Clothes: Is J2EE Changing? By Kanbay’s Shared Architecture Services Group July 2004 PURPOSE The article is first in a series intended to generate awareness about the evolving J2EE trend of compositional, lightweight containers and their impact on J2EE application development. The document is an initial discussion draft and the ideas expressed here are meant to initiate discussion on the subject. SUMMARY The document starts by analyzing the current J2EE application development space and the prevalent architectures and development approaches are elaborated. The study argues that the problems with the enterprise java bean specification, emergence of compositional architectures based on several open source architectures as factors leading to the emergence of the parallel non-specification oriented thinking towards aspects and lightweight containers as the newer paradigms in the J2EE application space Lightweight frameworks are defined as context independent, compositional framework that support object oriented design. The two key patterns found in the implementation of these components are Inversion of Control which allow easy composition and Aspect Oriented Programming which allows transparent access to middleware services. Spring—a lightweight framework is thereafter described and the MVC implementation provided with the Spring Framework is compared with the market leading Struts Framework which is the current de-facto standard. A detailed comparison indicates that Spring MVC has significant advantages such as interface based design, transparent integration with middleware services and view independence. Additionally a detailed parametric analysis also points to the fact that Spring may have more flexible request processing, easier configuration, better performance and better support for transactions and se- curity. This however will need to be balanced against standards compliance and an established market base. The article concludes by making certain recommendations about the use of Spring framework. This is the first in a planned series of three such articles which compare lightweight practices and frameworks with the current recommended J2EE prac- tices. We start the series by comparing Spring MVC implementation with Jakarta Struts project, the most widely used J2EE framework. FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Transcript of Spring Blueprint

Page 1: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

The Emperor Has New Clothes: Is J2EE Changing?

By Kanbay’s Shared Architecture Services Group

July 2004

PURPOSE

The article is first in a series intended to generate awareness about the evolving J2EE trend of compositional, lightweight containers and their impact on J2EE ap-plication development. The document is an initial discussion draft and the ideas expressed here are meant to initiate discussion on the subject.

SUMMARY

The document starts by analyzing the current J2EE application development space and the prevalent architectures and development approaches are elaborated. The study argues that the problems with the enterprise java bean specification, emergence of composi-tional architectures based on several open source architectures as factors leading to the emergence of the parallel non-specification oriented thinking to-wards aspects and lightweight contain-ers as the newer paradigms in the J2EE application space

Lightweight frameworks are defined as context independent, compositional framework that support object oriented design. The two key patterns found in the implementation of these compo-nents are Inversion of Control which allow easy composition and Aspect Ori-ented Programming which allows trans-parent access to middleware services. Spring—a lightweight framework is thereafter described and the MVC im-plementation provided with the Spring Framework is compared with the market leading Struts Framework which is the current de-facto standard.

A detailed comparison indicates that Spring MVC has significant advantages such as interface based design, trans-parent integration with middleware ser-vices and view independence. Addition-ally a detailed parametric analysis also points to the fact that Spring may have more flexible request processing, easier configuration, better performance and better support for transactions and se-curity. This however will need to be bal-anced against standards compliance and an established market base.

The article concludes by making certain recommendations about the use of Spring framework.

This is the first in a planned series of three such articles which compare light-weight practices and frameworks with the current recommended J2EE prac-tices. We start the series by comparing Spring MVC implementation with Jakarta Struts project, the most widely used J2EE framework.

INTENDED AUDIENCE

This document is intended for use within Kanbay. While we make our best effort to be correct, the information is based on available public domain information. We intend to continue to evolve this analysis through demonstration based approaches.

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Page 2: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

J2EE PRACTICE

The mainstream J2EE application devel-opment is based on the use of standards compliant infrastructure designed to develop highly distributed, large scale, enterprise class application.

J2EE uses the component, container and services platform model with containers managing component life cycle and pro-viding services required for the distrib-uted applications such as naming and location, declarative transaction security etc.

The primary idea behind the separation is to ease application development where the application programmers could focus on developing business logic while container provides easy access to services necessary for distributed appli-cation development. The containers are required to support a certain minimum set of services for compliance to an evolving set of J2EE standard. The cur-rent specifications require supporting a large set of services as shown in the attached diagram.

The EJB containers also need to address architectural qualities necessary for mission critical, highly available, transactional enterprise systems. Each application server vendor adds features such as high performance cluster aware caches, failover and load balancing support for the application. EJB containers have evolved to become highly complex and heavyweight middleware components.

Application Architectures

The application development using J2EE framework use a standard set of com-ponents. Servlets are the primary web components with Java Server Pages forming the primary view tier. The com-ponents are hosted within the web con-tainer.

Enterprise Java Beans are the primary business and persistence implementa-tion. Message Driven Beans provide asynchronous access to services devel-oped as part of the container.

The enterprise java bean could be dis-tributed or collocated and provide both remote and local interfaces for the pur-pose.

Additionally POJO’s (plain old java ob-jects) are used across all tiers for data transfer and correlation between differ-ent tiers.

Both a fully distributed multi-JVM de-ployment and single JVM deployments with collocated web and EJB containers is widely used.

Exhibit 2 illustrates the commonly used architectures.

Application Development

The J2EE application development lead to a common set of challenges and pro-ductivity of application development has been a major challenge since the speci-

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Exhibit 1: Component, Container & Services Model

Table of Contents

Purpose................................1

Summary..............................1

Intended Audience...............1

J2EE Practice........................2

Web Only Architecture and

Light Weight Containers..4

Lightweight Containers

Implementation...............5

Aspect Oriented

Programming...................6

Spring Lightweight Container7

Web MVC..............................8

Participants &

Responsibilities...............9

Features of Spring MVC......10

Struts.................................12

Struts Features...................14

Comparing Spring with Struts15

Request Processing

Architecture..................16

Configuration.....................16

View...................................17

Security Model...................17

Transaction........................17

Validations and Error

Handling........................18

Performance.......................18

Community Acceptance.....19

IDE Support........................19

Conclusions........................20

References.........................20

Appendix A: List of open-

source MVC frameworks21

Appendix B: Some Issues

with EJB Specification....23

Page 3: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

fication began to be used on large scale applications.

Over a period of time several patterns have evolved as best practices. Argua-bly some of these patterns are attempts to workaround the limitations of the specification or implementation of J2EE technologies and have gone from the status of being patterns to anti-patterns. A number of micro architectures which are a combination of the J2EE patterns are widely used.

Two architectural styles that have been very widely used in J2EE applications include Layers and Model View Con-troller (subject of this article).

A large number of both open source and proprietary frameworks are available whose implementations are based on the current known best practices while some other become the source for some new patterns.

Today application development involves identification of application patterns, provisioning and composition of appro-priate frameworks and development of business specific services or compo-nents.

The ability to compose solutions through the use of available components, frameworks and micro-architecture therefore is a significant part of applica-tion development today and is important to achieve productivity.

Specification Resistance

“As components of application server technology, J2EE and Enterprise Java-Beans (EJB) are not the same thing. Most Java projects use Java Server Pages (JSP)/servlet capabilities and not EJB. Higher-priced application servers are designed to run EJB, yet they are using JSP/servlet capabilities instead.”

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Exhibit 2: Commonly Used Architectures

Page 4: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

“Companies have overspent about $1 billion on application server technology solutions since 1998. Moreover, an ad-ditional $2 billion may be wasted be-tween now and 2003.”

“Don't let confusion or hype push you to spend more than necessary.”

Gartner Group

J2EE application development and im-plementation has generally been com-plex and software development commu-nity has struggled with improving devel-opment and maintenance productivity.

The Enterprise Java Bean component model however has several weaknesses and has been slow in evolving. Some difficulties with the EJB specification are(1)—

Complex set of interfaces and classes required to implement EJB components and a programming model that requires external (non-compiler) consistency management.

Careful design requirements to achieve adequate performance for remote calls.

The introduction of local interfaces was intended to address performance due to remote references. However the semantic differences (call by value vs. call by reference) prevented seamless migration from local to re-mote interfaces.

The use of separate local and. remote interfaces impacts location transparency

The need to use JNDI lookup, use of home interfaces and need to throw remote exception made the client de-pendent on EJB API or required the client to implement business dele-

1Note ?: For a full list of issues with Enterprise

Java Beans refer to Appendix B.

gates which hides API complexity but leads to code redundancy

Testability of applications developed with Enterprise Java Beans outside the container

Entity beans for data access proved very unsatisfactory because of poor performance, poor EQL capabilities, poorly designed O/R mappings and a whole host of other issues.

EJB’s subverted good object ori-ented designs as the limitation of the technology dictated design choices e.g. EJB’s provide no easy way to implement several patterns such as Singleton or the fact that a number of J2EE patterns are designed to provide workaround to these problems were developed as part of the J2EE specification. e.g.. Value Objects, Fast Lane Reader, Composite Entity etc.

Problems with the specification have lead to widespread evolution of non-standard specifications and adoption of architectures that use alternatives to the Enterprise Java Beans in both the busi-ness and persistence management tiers. The most noticeable such efforts being evolution of Aspects as an alternative to components allowing use of POJOs as business objects and development of persistence frameworks such as Hiber-nate.

Some of these changes have also started to influence the specification and EJB 3.0 is likely to adapt some of these changes.

Web Only Architectures

Alternative architectures that avoid use of Enterprise Java Beans completely and used only the web container have be-come increasingly common and are be-ing applied to a large class of applica-tions. These are combined with web server based load balancing to increase

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Page 5: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

service capacity thresholds. See Exhibit 3.

WEB ONLY ARCHITECTURE AND LIGHT WEIGHT CONTAINERS

The web only architectures though ele-gant lacked container support for dy-namic discovery, lifecycle management, pooling, declarative transactions and clustering middleware services available through the EJB container.

This is an area which has attracted a lot of attention recently and has lead to the emergence of several new techniques. Aspect Oriented Programming has re-cently gained a lot of momentum in the J2EE community.

A category of products called light-weight containers represents the con-vergence of the trends identified earlier in the article namely compositional na-ture of the application development, large number of open source projects and attrition from EJB’s. Although no standard definition exists for the light-weight containers category, for the pur-pose of this document we define light-weight containers as containers that—

Are mostly compositional and do not include a lot of behavior, other that allowing classes to be plugged to-gether. They help to assemble com-ponents from different projects into a cohesive application.

Do not use EJB’s as component model but rather use lightweight model such as POJOs, MBeans or some simpler component model.

Provide their own layer to simplify de-velopment and allow declarative binding of objects

Some provide capabilities such as declarative transaction handling.

Allow the component to be embedded in any context and are platform agnostic where they can be deployed on an existing J2EE platform

Allow the core object model to be preserved through the implementation unlike the EJB models

Do not normally support capabilities such as cache management and cluster aware application objects

Some examples in this category include Pico Container, HiveMind and Spring which is the most popular and mature lightweight container.

Some micro-kernels based application servers such as JBoss support similar capabilities underneath their J2EE serv-ers. Although originally intended as in-frastructural components for a layer below the application servers, some vendors are beginning to expose their microkernel as lightweight containers for direct use by application developers.

LIGHTWEIGHT CONTAINERS IMPLEMENTATION

Lightweight containers usually are based on the notion of Inversion of Control to allow composition of components and support Aspect

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Exhibit 3: Web Only Architectures

Page 6: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

Oriented Programming to provide several of the transparent middleware services such as declarative transactions, security and logging.

Inversion of Control or Dependency Injection

Inversion of Control (IoC) is a design pattern that helps to reduce coupling and dependencies between components. In general, IoC is a principle that separates an API from a framework, and is based on who is “in control”. The word “inversion” from the pattern name refers to inverting the “normal” way in which components obtain references to each other.

This principle can be illustrated by ex-ample through the difference between an IoC framework and a class library.

The major difference between an IoC framework and a class library is that the

framework calls the application code, whereas normally the application code would call the class library. This princi-ple is also referred to as the Hollywood Principle, (“Don’t call us, we call you!”)

In lightweight containers that use this principal of inversion of control you don't create our objects, you describe how they should be created. You don't directly connect your components and services together in code, you describe which services are needed by which components, and the container is re-sponsible for hooking it all together.

The container creates all the objects, wires them together by setting the nec-essary properties, and determines when methods are invoked.

The main process of Inversion of Control is illustrated by the diagram in Exhibit 5.

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Exhibit 4: Implementation Pattern Types

Source: Avalon Project

Interface Injection Services need to implement a dedicated interface through which they are provided with an object from which they can look up de-pendencies (other services). This is the pattern used by the earlier containers provided by Avalon.

Setter Injection Services dependencies upon are assigned via JavaBeans properties (setter methods). Both HiveMind and Spring use this approach.

Constructor Injection Services dependencies are provided as constructor parameters (and are not exposed as JavaBeans properties). This is the exclusive ap-proach

Exhibit 5: Web Only Architectures

Page 7: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

More recently, this concept has been renamed Dependency Injection. The article by Martin Fowler provides a de-tailed explanation of the concept.

As shown in Exhibit 4, there are three different implementation pattern types for IoC.

ASPECT ORIENTED PROGRAMMING

Some lightweight frameworks use im-plementation of Aspect Oriented Pro-gramming to further improve on their support for transparent middleware ser-vices such as declarative transactions on POJOs.

Aspect Oriented Programming is in-tended to address requirements that do not decompose neatly into behavior centered around a single locus. AOP is based on the idea of programming by externalizing the crosscutting concerns of the system, describing the cross cut-ting concerns and then using the AOP system to weave or compose them to-gether into a coherent program. Aspects can range from high-level notions like security and quality of service to low-level notions such as caching and buff-ering. They can be functional, like fea-tures or business rules, or nonfunctional (systemic), such as synchronization and transaction management.

AOP is focused on mechanisms for sim-plifying the realization of such crosscut-ting concerns. Aspectual requirements are concerns that (for common struc-tural decompositions) introduce cross-cutting in the implementation.

Aspects are beginning to replace the Enterprise Java Bean component models as the way of non-intrusively weaving middleware services to POJO based business objects. The EJB 3.0 specifica-tion is making a tentative move the di-rection

SPRING LIGHTWEIGHT CONTAINER

In this document we explore Spring the current leader in the implementation of the lightweight container. The container provides compositional capabilities as well as a number of packages that pro-vide capabilities corresponding to differ-ent tiers in the application stack as an integrated consistent solution.

In this series of articles we explore the MVC framework, business object imple-mentation and persistence capabilities of the Spring framework and compare it with current practice

Design Intent

The Spring design goals as stated by Rod Johnson—

Make J2EE easier to use or address the productivity challenge

Address end-to-end requirements rather than one tier

Eliminate need for middle tier “glue” or support composition

Provide the best Inversion of Control solution as the strategy to implement easy composition

Provide a pure Java AOP implementation, focused on solving common problems in J2EE

Fully portable across application servers

Overview

Spring contains a lot of functionality and features, which are well-organized in seven modules shown in Exhibit 6. This section discusses each of the modules in turn.

The Core package is the most funda-mental part of the framework and pro-vides the Dependency Injection features allowing you to manage bean container functionality. The basic concept here is the BeanFactory, which provides a fac-

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Page 8: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

tory pattern removing the need for pro-grammatic singletons and allowing you to decouple the configuration and speci-fication of dependencies from your ac-tual program logic.

On top of the Core package sits the Context package, providing a way to access beans in a framework-style man-ner, that somewhat resembles a JNDI-registry. The context package inherits its features from the beans package and adds support for text messaging using e.g. resource bundles, event-propaga-tion, resource-loading and transparent creation of contexts by, for example, a servlet container.

The DAO package provides a JDBC-ab-straction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes. Also, the JDBC package provides a way to do programmatic as well as declara-tive transaction management, not only for classes implementing special inter-faces, but for all your POJOs (plain old java objects).

The ORM package provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis. Using the ORM package you can use all those O/R-Mappers in com-bination with all the other features Spring offers, like simple declarative transaction management mentioned before.

Spring's AOP package provides an Aop Alliance compliant aspect-oriented pro-gramming implementing allowing you to define, for example, method-intercep-tors and pointcuts to cleanly decouple code implementing functionality that should logically speaking be separated. Using source-level metadata functional-ity you can incorporate all kinds of be-havioral information into your code, a little like .NET attributes.

Spring's Web package provides basic web-oriented integration features, such as multipart functionality, initialization of contexts using servlet listeners and a web-oriented application context. When using Spring together with WebWork or

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Exhibit 6: Overview of the Spring Framework

Page 9: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

Struts, this is the package to integrate with.

Spring's Web MVC package provides a Model-View-Controller implementation for web-applications. Spring's MVC im-plementation is not just any implemen-tation, it provides a clean separation between domain model code and web forms and allows you to use all the other features of the Spring Framework like validation.

Spring Web MVC and Struts

As explained above Spring addresses all tiers of the web application. In the sec-tion that follows we compare Spring’s implementation of the MVC framework with the current market leader Struts. As Spring is a scalable system using Spring allows a common set of infrastructure classes to be used across tiers of the application.

WEB MVC

In the following section we describe MVC, Spring MVC and Struts (the most widely used MVC framework) and com-pare the two on a series of parameters

The Pattern

Model-View-Controller (MVC) architec-ture separates core business model functionality from the presentation and control logic. Such separation allows multiple views to share the same enter-prise data model, which makes sup-porting multiple clients easier to imple-ment, test, and maintain.

PARTICIPANTS & RESPONSIBILITIES

The MVC architecture has its roots in Smalltalk, where it was originally applied to map the traditional input, processing, and output tasks to the graphical user interaction model. However, it is straightforward to map these concepts into the domain of multi-tier enterprise applications.

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Exhibit 7: Interactive Between Model, View & Controller Objects

Page 10: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

Model—The model represents enterprise data and the business rules that govern access to and updates of this data. Often the model serves as a software approximation to a real-world process, so simple real-world modeling techniques apply when de-fining the model.

View—The view renders the contents of a model. It accesses enterprise data through the model and specifies how that data should be presented. It is the view's responsibility to maintain consistency in its presentation when the model changes. This can be achieved by using a push model, where the view registers itself with the model for change notifications, or a pull model, where the view is responsible for calling the model when it needs to retrieve the most current data.

Controller—The controller translates interactions with the view into actions to be performed by the model. In a stand-alone GUI client, user interactions could be button clicks or menu selections, whereas in a Web application, they appear as GET and POST HTTP requests. The actions performed by the model include activating business processes or changing the state of the model. Based on the user interactions and the outcome of the model actions, the controller responds by selecting an appropriate view.

Introduction to the Spring Web Framework

Spring's web framework is designed around a DispatcherServlet that dis-patches requests to handlers, with con-figurable handler mappings, view reso-lution, locale and theme resolution as well support for upload files. The default handler is a very simple Controller in-terface, just offering a ModelAndView handleRequest(request, response)

method. This can already be used for application controllers, but you will pre-fer the included implementation hierar-chy, consisting of for example Ab-stractController, AbstractCommandCon-troller and SimpleFormController. Appli-cation controllers will typically be sub-classes of those. Note that you can choose an appropriate base class: If you don't have a form, you don't need a FormController. This is a major differ-ence to Struts.

Any object as command or form object: There's no need to implement an inter-face or derive from a base class. Spring's data binding is highly flexible, e.g. it treats type mismatches as vali-dation errors that can be evaluated by the application, not as system errors. So you don't need to duplicate your busi-ness objects' properties as Strings in your form objects, just to be able to handle invalid submissions, or to convert the Strings properly. Instead, it's often preferable to bind directly to your business objects. This is another major difference to Struts which is built around required base classes like Action and ActionForm—for every type of action.

Spring has differentiated object roles: It supports the notion of a Controller, an optional command or form object, and a model that gets passed to the view. The model will normally include the com-mand or form object but also arbitrary reference data.

Regarding views: Spring's view resolu-tion is extremely flexible. A Controller implementation can even write a view directly to the response, returning null as ModelAndView. In the normal case, a ModelAndView instance consists of a view name and a model Map, containing bean names and corresponding objects (like a command or form, reference data, etc). View name resolution is highly configurable, either via bean names, via a properties file, or via your

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Page 11: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

own ViewResolver implementation. The abstract model Map allows for complete abstraction of the view technology, without any hassle: Be it JSP, Velocity, or anything else—every renderer can be integrated directly. The model Map sim-ply gets transformed into an appropriate format, like JSP request attributes or a Velocity template model.

FEATURES OF SPRING MVC

If just focusing on the web support, some of the Spring's unique features are—

Clear separation of roles: controller vs. validator vs. command object vs. form object vs. model object, Dis-patcherServlet vs. handler mapping vs. view resolver, etc.

Powerful and straightforward configuration of both framework and application classes as JavaBeans, including easy in-between referencing via an application context, e.g. from web controllers to business objects and valuators.

Adaptability, non-intrusiveness: Use whatever Controller subclass you need (plain, command, form, wizard, multi action, or a custom one) for a given scenario instead of deriving from Action/ActionForm for every-thing.

Reusable business code, no need for duplication: You can use existing business objects as command or form objects instead of mirroring them in special ActionForm subclasses.

Customizable binding and validation: type mismatches as application-level validation errors that keep the offending value, localized date and number binding, etc instead of String-only form objects with manual parsing and conversion to business objects.

Customizable handler mapping, cus-tomizable view resolution: flexible model transfer via name/value Map, handler mapping and view resolution strategies from simple to sophisti-cated instead of one single way.

Customizable locale and theme resolution support for JSPs with and without Spring tag library, support for JSTL, support for Velocity without the need for extra bridges, etc.

Simple but powerful tag library that avoids HTML generation at any cost, allowing for maximum flexibility in terms of markup code.

Spring Request Processing

Spring's web framework is a request driven web framework, designed around a servlet that dispatches requests to controllers and offers other functionality facilitating the development of web ap-plications. Spring's DispatcherServlet however, does more than just that. It is completely integrated with the Spring ApplicationContext and allows you to use every other feature Spring has through IoC based context configuration.

When a DispatcherServlet is setup for use and a request comes in for that specific DispatcherServlet it starts proc-essing it. The list below describes the complete process a request goes through if a DispatcherServlet is sup-posed to handle it—

1. The WebApplicationContext is searched for and bound in the re-quest as an attribute in order for controller and other elements in the chain of process to use it. It is bound by default under the key Dis-patcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE

2. The locale resolver is bound to the request to let elements in the chain resolve the locale to use when proc-essing the request (rendering the

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Page 12: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

view, preparing data, etcetera). If you don't use the resolver, it won't affect anything, so if you don't need locale resolving, just don't bother

3. The theme resolver is bound to the request to let e.g. views determine which theme to use (if you don't needs themes, don't bother, the re-solver is just bound and does not affect anything if you don't use it)

4. If a multipart resolver is specified, the request is inspected for multi-parts and if so, it is wrapped in a MultipartHttpServletRequest for further processing by other ele-ments in the chain (more informa-tion about multipart handling is pro-vided below)

5. An appropriate handler is searched for. If a handler is found, it execution chain associated to the handler (preprocessors, postprocessors, controllers) will be executed in order to prepare a model

6. If a model is returned, the view is rendered, using the view resolver that has been configured with the WebApplicationContext. If no model was returned (which could be the result of a pre- or postprocessor in-tercepting the request because of for instance security reasons), no view is rendered as well, since the request could already have been fulfilled

Exception that might be thrown during processing of the request get picked up by any of the handlerexception resolvers that are declared in the WebApplica-tionContext. Custom behavior can be defined using exception resolvers.

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Page 13: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

Spring's DispatcherServlet can be cus-tomized by adding context parameters in the web.xml file or servlet init pa-rameters.

STRUTS

Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design. This definition implies that Struts is a framework, rather than a library, but Struts also contains an extensive tag library and utility classes that work independently of the framework.

The following content is based on the on an article by Jean-Michel Garnier in the http://rollerjm.free.fr web site. Copyright (c) 1999-2002 The Apache Software Foundation. All rights reserved.

Struts MVC Implementation

The components in a Struts implemen-tation include Struts.xml which is a con-figuration resource file parsed by the Struts Controller for initialization.

Class Diagram

The major classes in the implementation are explained in Exhibit 8.

Application Configuration

ModuleConfigImpl contains a collection of static configuration information that describes an application module. For application initialization, struts-con-fig.xml is parsed in order to dispatch mapping information in instances of Ac-tionConfig, ForwardConfig and Form-BeanConfig.

ActionConfig contains information on how specific events are mapped to

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Exhibit 8: Class Diagram

Page 14: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

action classes. The mapping is based on the path in the request mapping

ForwardConfig contains information on where the request will be for-warded to. Properties name and path correspond to the strut-config.xml line : <forward name="next" path="/forwardedPage.jsp" />. Ac-tionForward extends ForwardConfig and is not deprecated because of backward compatibility with version 1.02.

FormBeanConfig is a definition of ActironForm beans loaded from struts-config.xml form-bean name="userForm" type="org.apache.struts.action.Dy-naActionForm" />

FormPropertConfig is a JavaBean representing the configuration information of a <form-property> element in struts-config.xml : <form-property name="property1" type="java.lang.String"/>

Struts Controller

The ActionServlet class is the core of the framework. It is an HTTPServlet which receives requests from the browser and forwards it depending on a configuration file : struts-config.xml.

Since Struts 1.1, the processing logic has been delegated to the RequestProc-essor class—

Method processMapping selects the ActionConfig used to process the se-lection path for this request.

Method processActionForm retrieves the ActionForm associated with a mapping or creates and stashes one if necessary.

Method processPopulate populates the properties of the specified ActionForm from the request parameters included with this request.

Method processValidate calls the validate() method of the specified ActionForm, and forwards back to the input form if there are any errors.

Method processActionPerform asks the specified Action instance to han-dle the request, returns an Action-Forward

The subclasses of Action are created and used by RequestProcessor. It is a wrapper around Business logic. To use Action, subclass it and overwrite the execute() method.

Method execute processes the HTTP request, and creates the correspond-ing HTTP response. Returns an Ac-tionForward instance describing where and how control should be forwarded.

Method saveErrors saves the specified error messages keys into the appropriate request

HTML Form Processing

ActionForm represents a general concept of data that is set or updated by a HTML Form. Struts will automati-cally set the state of the DynaAction-Form using the corresponding fields from the HttpServletRequest.

DynaActionForm is specialized sub-class of ActionForm that allows the creation of form beans with dynamic sets of properties, without requiring the developer to create a Java class for each type of form bean.

DynaActionFormClass is used by Dy-naActionForm to manage its internal state.

User Classes

HelperBean is a “Helper” class; it is a value object bean which holds the data required by the screens.

UserAction is a typical Action, inherits the Struts Action class.

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Page 15: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

UserDelegate is based on the Business Delegate Pattern. This is an intermediate class which decouples business components from the code that uses them, encapsulates busi-ness services and access to the Model.

Struts Request Processing

The sequence diagram in Exhibit 9 ex-plains struts request processing.

STRUTS FEATURES

Here are some specific design points which contribute to the frameworks effi-ciency.

Struts is not only thread-safe but thread-dependant. The response to a request is handled by a light-weight Action object, rather than an individual servlet. Struts instantiates each Action class once, and allows other requests to be threaded through the original object.

ActionForm beans minimize subclass code and shorten subclass hierarchies. Another key component in the Struts architecture is automatically populating any ActionForm bean from any request. Without this component, custom code may have to be written and instantiated to populate each class of bean.

The Struts tag libraries provide general-purpose functionality. Most any JSP tag need can be met by the bean and logic tags bundled with Struts, and reduce or eliminate the need to write and instanti-ate additional tags.

Struts components are reusable by the application. Utilities bundled with the framework have uses throughout most applications. The BeanUtil.populate() method is a good example. This is used to populate form beans from a HTTP request, but can also be used to popu-late any bean from any type of map.

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Exhibit 9: Strut Request Processing

Page 16: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

Reusing components reduces overhead and saves resources.

Struts i18n strategies reduce the need for redundant JavaServer Pages. By al-lowing i18n message to be retrieved at runtime, applications that need interna-tionalization can provide a single page where one page for each language would otherwise be needed. Meanwhile, the same messaging system is also used to handle error messages, providing dual use of the same objects. 

Struts is designed with an open archi-tecture. Struts components are designed so that they can be subclasses by an application to provide additional functionality. This allows developers to extend existing classes rather than add the overhead of creating and integrating new classes. Also, Struts exposes its internal resources to the application. This allows developers to leverage ex-isting components, so they do not have to write and instantiate their own.

Struts is standards compliant. Struts strict observance to standards leverage optimizations present in many contain-ers.

Struts is open source and well docu-mented. This means developers can easily examine the code to identify and resolve any potential bottlenecks.

Struts is model neutral. Since Struts does not make any assumptions about the backend model, an application can implement that portion in the most effi-cient way possible. Struts Actions can call a set of helper classes to access needed data. Once retrieved, Struts re-liance on JavaBeans makes it easy to retain value objects and reduce the number of calls to the Integration and (consequently) Resource layers.

COMPARING SPRING WITH STRUTS

The section aims at evaluating Spring with Struts framework. Struts framework is the more evolved and widely accepted framework whereas Spring represents the most promising new kid on the block.

Before we make a detailed comparison of Struts with Spring Framework the following section lists some of the key differences in the implementation of the two frameworks.

Struts Framework uses inheritance as the primary model for using the frame-work capabilities. Users are typically required to extend several struts specific bases classes such as ActionForm, Ac-tion etc. The use of concrete inheritance ties the application to the framework implementation. The Spring Framework on the contrary uses interface based design and IOC to allow user objects to be transparently configured. This makes Spring design more flexible than Struts design. This however should be weighed against the fact that Struts introduces better discipline in the project imple-mentation.

Struts uses name mapping approach to resolve dependencies of framework classes to implementation classes. Te configuration is defined in the struts-config.xml and at run time ModuleConfi-gImpl class is instantiated. Spring is based on the Dependency Injection Pattern. This allows Spring to be inte-grated to middletier without coding.

Struts is primarily intended to be used in a web application and it is often argued that Action classes which are the handoff points to the model are tied to servlet APIs. Similarly Struts uses tag libraries which tie it to use of JSPs as the preferred view technology. Spring on the other hand uses Application Context and is view agnostic.

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Page 17: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

The independence from specific view technology allow Spring applications to be tested outside the web container which is a huge improvement if test driven development is important to the request processing cycle.

In what follows we compare Struts framework with Struts using a series of criteria.

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Page 18: Spring Blueprint

6400 Shafer CourtRosemont, Illinois 60018

847 384 6100847 384 0500 fax

©2004 Kanbay Incorporated. All rights reserved. Kanbay and the Kanbay logo are trademarks of Kanbay Incorporated. Other trademarks are the property of their respective owners.

REQUEST PROCESSING ARCHITECTURE

Controller

Front Controller is the choice for both Spring and Struts framework. This is an accepted pattern from the Sun J2EE core patterns. However, the pattern can be implemented in different flavors.

CONFIGURATION

Configuration file has the mapping for all the beans. The number of configuration files needed, the ability to split the information into multiple files repre-senting one per module etc. This is shown in Exhibit 11.

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated

Exhibit 10: Controller Patterns

Criteria Spring Struts Score

FrontController In-stances. This acts as the controller servlet in MVC

Can have multiple Displatch-erServlet configured for an ap-plication. Each servlet will have its own context information. The various modules can share a common root context.

Works with single ActionServlet for an application. The module concept can be use for logical separation of modules.

Plugin mechanism to support extension without inheritance

Mapping form ac-tions to handlers

The mechanism is pluggable. The default is BeanNameUrlhan-dlermapping where the action specified is the name of the bean. The other mechanism is the SimpleUrlHandlerMapping, which has Ant-style pathmatch-ing capabilities.

The match is based on url path resolution.

No other matching option sup-ported

Transferring form data to the handlers

Uses reflection to populate the data to the form controller the java beans way.

PropertyEditor mechanism al-lows type conversion

The advised way is to create sub-class of the ActionForm for every form. Uses reflection to populate the Action Form which is re-stricted to using only strings

Command Controller types, M of MVC

In Spring, the controllers come in various flavors; one can use different controllers depending on the need. For example for a form submit one can use the SimpleFormController, for grouping multiple requests to one controller a MultiActionCon-troller can be used. Wizard-FormController for wizard-style manipulation of data objects.

Most controllers have to extend the Action class. Struts1.1 has DispatcherAction which has the similar kind of behavior

Per Class initializa-tion of Bean, M of MVC

Can have one per request, is configurable for single or multi-ple

Once by servlet Interceptors Can add Handle Interceptors

when want specific functionality to all the request at pre, post and execute

Need to use filters or Extend the Action class with changes in exe-cute method for pre post changes

Page 19: Spring Blueprint

Exhibit 11: Configuration

Criteria Spring Struts Score

Type of configu-ration

Mixed – XML, properties. For rela-tively small applications, the con-figuration file can be done away with and the information included as Source Metadata.

XML,use of strut-con-fig.xml

Multiple con-figuration files for a single ap-plication

This is allowed and the various files can be built into one context with the parent-child relationship.

Only with Struts 1.1 is multiple configuration files allowed.

VIEW

This section examines the strategy used for decoupling the actual view resource name from the controller.

Exhibit 12: View

Spring Struts Score

Name View /URL Path Spring uses a pluggable view mapping strategy viz.., Re-sourceBundleViewResolver, UrlBasedViewResolcer, Inter-nalResourceViewResolver, VelocityViewResolver and Ab-stractCachingViewResolver.

Struts use the struts-config file to identify the next view through configuration file

Composite view Can adapt using some exter-nal entity as using tiles of struts

Tiles gives this compo-sition

View Technologies

Can use any of the following as V of MVC JSP/Tag/JSTL/Page-flow/xml-xsl/applet

Can use any kind of view for e.g. velocity, xslt, and jsp. Uses view resolvers(above mentioned) for the same.

Biased towards JSP. SECURITY MODEL

The security model that each of the framework supports. Does it allow plugging of some well-known implementations?

Exhibit 13: Security Model

Spring Struts Score

Security includes Authentication and Authorization

Acegi is an open source project that is written specifically for Spring. This security framework is quite abundant in its features.

Struts use the JAAS specification to sup-port the security model.

TRANSACTION

This features looks at any support for declaratively transactions

Page 20: Spring Blueprint

Exhibit 14: Transaction

Spring Struts Score

Transaction Man-agement

Declarative or pro-grammatic support for both local and distrib-uted transactions

Will require programmatic transaction definition through standard J2EE UserTransaction interface

VALIDATIONS AND ERROR HANDLING

In this section we examine the validation mechanism and exception response of the application.

Exhibit 15: Validations & Error Handling

Spring Struts Score

Validation Spring allows validation through bean wrapper which are trans-parent to the developer and ap-ply to objects in any layer

Provides a validtor framework which allow declarative validations

Error Handling Can define HanlerexceptionRe-solver to handle unexpected exception

Each action can specify the error condition for-ward

PERFORMANCE

Performance criteria of a framework will be vastly different from the performance characteristics of an application. Some of the characteristics that have been identified include the no of layers, the heap size, inheritance roadmap etc.

Exhibit 16: Performance

Spring Struts Score

No of data translations in the request processing cycle

Spring allow bean properties to be set to actual type

Any object can act as a command and can directly interface with domain layer

Specific API restric-tions cause data to be populated into multiple objects

Use of the re-flection API.

The concept of Dependency injection relies heavily on the reflection API.

But with the modern day Java runtime engines the cost of reflection is not as it used to be.

Not much. Runtime heap size (no of classes loaded)

Depending on the choice made for a specific layer the no of classes loaded will vary, but the important fact is that the framework provides the flexibility to make the right decisions. The tag libraries for Spring are light-weight

The over-emphasis of the Tag libraries makes the view proc-essing a bit bulky.

Multithreaded Command

Spring allows objects to be created as prototype or a singletons

Singleton

Page 21: Spring Blueprint

COMMUNITY ACCEPTANCE

The community acceptance criterion looks at the framework from the developer and the industry community point of view. What features of the framework encourages or dissuades the community from accepting the framework.

In terms of the community acceptance Struts wins hands down with regard to Spring framework at the time of writing this document. We will examine some of the issue that has brought about this viewpoint.

IDE SUPPORT

Exhibit 17: IDE Support

Spring Struts Score

Common IDE support

Eclipse. The feature list of this plug-in is quite less.

Eclipse, WSAD, JBuilder, JDeveloper etc. Most of the well known IDE have extensive support for the Struts framework.

Books Professional Java Development with the

Spring Framework – Wiley publication.

This book is due out in Dec 2004. This book is written by the authors of the Spring framework

There are plenty of books available in the market ranging from the begin-ners guide to the more advanced ones.

Online Documenta-tion

The online documentation on the Springframework site is good for start-ers, but there is no information for best Practices or recommendations.

The online documentation is quite adequate.

Testability of application developed

Supports the JUnit testing framework. Struts Test Case—a cus-tom-built test framework using cactus.

Maintain-ability, in terms of the code/ framework maintenance

About framework, if continues to grow. About code very clean, easy to main-tain once acquired to

Very clean, has the logical separation of classes. Continuous growing with the large community around; Wide availability of skills

Compatibil-ity

J2SE 1.3 and J2EE 1.3 (Servlet 2.3, JSP 1.2, JTA 1.0, EJB 2.0), J2SE 1.4 is required for building the framework. J2EE 1.2 (Servlet 2.2, JSP 1.1) is good enough if not using

Spring's web MVC or EJB support. The framework integrates to 14 other third party tools / applications.

J2EE 1.3 compatible

Skills / learning curve

From the skill set perspective in addi-tion to Java and J2EE, the developer needs a good understanding of the Aspect Oriented Programming. Meta-data / Annotations concept.

Java, JSP, servlets and tag libraries. The framework is not difficult to understand. Easy as most developers already using for long time now

Page 22: Spring Blueprint

CONCLUSIONS

The above discussion along with earlier discussions about the direction of the J2EE specification seem to indicate that Spring will have a significant impact on the way applications are built and since Spring MVC is based on the same set of principals it should form part of the consideration set for any MVC implementation

Considering that Spring scores over Struts on most technical parameters and is rapidly catching up on the community acceptance is a strong reason to further investigate Spring in the context of a specific project particularly in case of Greenfield develop-ment

Struts however offer a strong accepted solution and there seems to be no compelling reason for porting an application currently in Struts to a Spring MVC framework

Adoption of Spring may also be viewed in the context of technology usage on other tiers

Finally the question of standards conformance should be carefully considered and is a very important consideration while making any choices.

REFERENCES

Spring: http://www.springframework.org

Sun J2EE Core Patterns: http://java.sun.com/blueprints/corej2eepatterns/index.html

Struts: http://struts.apache.org

Java BluePrints: http://java.sun.com/blueprints/patterns/MVC-detailed.html

Appendix A: http://java-source.net/open-source/web-frameworks

Appendix B: http://www.softwarereality.com/programming/ejb/conceptual.jsp

ABOUT THE AUTHORS

Kanbay’s Shared Architecture Services team includes the company’s leading distributed systems architects and designers. The group advises and implements architectural solutions for Kanbay clients.

The SAS team is led by Chetan Juneja, Kanbay’s Chief Architect. Chetan holds a Master’s degree in Computer Science and has over 10 years of experience building, designing and architecting distributed systems.

Page 23: Spring Blueprint

APPENDIX A: LIST OF OPEN-SOURCE MVC FRAMEWORKS

Struts

The core of the Struts framework is a flexible control layer based on standard tech-nologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages. Struts encourages application architectures based on the Model 2 approach, a variation of the classic Model-View-Controller (MVC) design para-digm.

Category Web Frameworks

License Apache Software License

HomePage http://jakarta.apache.org/struts/

WebWork

WebWork is a web application framework for J2EE. It is based on a concept called "Pull HMVC" (Pull Hierarchical Model View Controller).

Category Web Frameworks

License Apache Software License

HomePage http://www.opensymphony.com/webwork/

Spring

Spring is a layered Java/J2EE application framework, based on code published in Expert One-on-One J2EE Design and Development. Its flexible MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. Note that a Spring middle tier can easily be combined with a web tier based on any other web MVC framework, like Struts, WebWork.

Category Web Frameworks

License Apache Software License

HomePage http://www.springframework.org/

Maverick

Maverick is a Model-View-Controller (aka "Model 2") framework for web publishing using Java and J2EE. It is a minimalist framework which focuses solely on MVC logic, allowing you to generate presentation using a variety of templating and transformation technologies.

Category Web Frameworks

License Apache Software License

HomePage http://mav.sourceforge.net/

SOFIA

Conceptually, SOFIA is similar to other J2EE MVC open source frameworks, like Apache Struts. But SOFIA sets a new standard for Java development by delivering so much more in a framework matching best-of-breed tools integration with robust JSP class and

Page 24: Spring Blueprint

tag libraries. SOFIA shortens application development time on the strength of its visual development capabilities and pre-built Java components that dramatically simplify coding.

Category Web Frameworks

License GNU Library or Lesser General Public License (LGPL)

HomePage http://www.nextapp.com/products/echo/

Jucas

Jucas is a web-framework which brings together the pull MVC concept with component orientated design GUI programming.

Category Web Frameworks

License Apache Software License

HomePage http://jucas.sourceforge.net/

WebOnSwing

WebOnSwing is a revolutionary multiple environment application framework that al-lows you to create web applications in the same way you develope a desktop one. You dont need to use JSP files, special tags, XML files, requests, posts, etc. Everything is Java and pure HTML files that comes directly from the graphic designer. This frame-work constructs and handles html pages with Swing components, allowing to use MVC architecture and all the facilities provided by Swing in the web.

Category Web Frameworks

License GNU Library or Lesser General Public License (LGPL)

HomePage http://webonswing.sourceforge.net/

Chrysalis

Chrysalis is a Java web development framework. It has a different focus from most Model-View-Controller (MVC) web frameworks. Chrysalis controllers resemble normal Java classes with multiple methods. Client request URLs are mapped to each controller method.

Category Web Frameworks

License GNU Library or Lesser General Public License (LGPL)

HomePage http://chrysalis.sourceforge.net/

VRaptor

VRaptor is a MVC web framework. It is highly based on the Inversion of Control princi-ples, using constructor injection to decouple your components from your business logic classes.

Category Web Frameworks

License Apache Software License

HomePage http://www.vraptor.org/

Page 25: Spring Blueprint

APPENDIX B: SOME ISSUES WITH EJB SPECIFICATION

Exhibit 18: Issues with EJB Specification

Source: http://www.softwarereality.com/programming/ejb/conceptual.jsp

1 EJB represents a radical departure from the Beans model. Beans was based on the (proven) component model also used in Delphi. This means that for projects that are migrating to EJBs, much of their code base is no longer valid.

Very little effort was made getting EJB to naturally extend the Beans specification (remember JavaBeans are not just about GUI widgets).For example, there is no men-tion of Events in the EJB model. Enterprise Beans don't have property change events or vetoable events, or indexed properties. The specifications focus almost entirely on the server side specification and hypothetical roles.

2 A rigorous set of examples and design goals for application programmers has been missing from the start. Instead the focus has been on remote objects and pessimistic locking, rather than the high performance and soft locking required by most Internet applications today.

3 EJB is based on an Object Pooling optimisation. Optimisations should not be incorpo-rated into the design, but left for vendors to decide and compete on. The logic of basing a system on saving a resource as cheap as memory seems absurd.

4 Sun's recommendation to "Use Container-Managed Persistence When You Can" is contrary to our experience. I am sure we're not alone in that CMP seems to be useless for complicated applications.

5 The EJB specification makes no reference to other well known distributed system de-sign references—for example the ISO Basic Reference Model of Open Distributed Processing 1992. Most seminal communication specifications make reference to the ISO Open Communication Models. Either there is a lack of theoretical grounding, or perhaps the designers didn't think it was worth mentioning.

The above-mentioned ISO ODP reference model has several goals for a distributed system. Many of the important goals have not been met—in particular (points 6-9 as follows):

6 The EJB spec doesn't address access transparency. Local and remote object definitions are not transparent, as you inherit from a different interface and have to cast using the narrow convention.

7 The EJB spec doesn't address performance transparency. The performance solutions for EJB involve radical redesign of your code, such as session-based methods, value objects, entity bean serialization or client side caching.

8 The EJB spec doesn't address migration transparency. If any object moves, the client must throw away the remote or local interface and get a new one.

9 The EJB spec doesn't address Concurrency transparency. There are no clear sets of locking strategies to suit different application programming tasks. The application and EJB programmer is left to handcraft locking strategies.

10 The only justification for EJB is on large projects, yet EJB makes those large projects larger still, and yet more unwieldy. You need to scale to get EJB to perform.

11 Role based class/method security is rarely useful. Data security is far more important.

Page 26: Spring Blueprint

Exhibit 18: Issues with EJB Specification

Source: http://www.softwarereality.com/programming/ejb/conceptual.jsp

12 EJB Query Language is another language to learn. This is reminiscent of the situation with WML, where an attempt to write a simpler language than HTML failed because they didn't just simplify HTML. Instead they started from the ground up, having de-cided erroneously that they could do a better job themselves.

EJB Query language doesn't support many SQL operators, (e.g. subqueries, IN, ALL, ANY, String comparison, ORDER BY, GROUP BY).

There is a good critique of EJB-QL here.

13 The specification does not provide for proper handling of views or read only tables. Back in the real world, read only tables and views are very important.

14 EJB only handles first class objects (i.e. beans that have primary keys). It would be nice if it also handled second class objects (do not have primary keys), where they have a one-one relationship with a first class object.

For example, a Cash object might contain a currency and an amount. Using CMP En-tity Beans you would be forced to have a Cash table. A better design would be to automatically map the Cash.currency and Cash.amount into the parent table's col-umns.

15 No proper handling of validation (e.g. String lengths). For a specification whose main purpose is reading and writing to a database, this is a surprising omission.

16 No proper handling of Enumerated Types. Enumerated Types represent fixed sets of data, such as Sex, Industrial Classification, or Marital Status. It should be possible to use them as properties on Beans.

It has been argued that this is more of a Java issue, i.e. a deficiency in the Java lan-guage rather than EJBs per se. This is not necessarily the case though. For example, our JBeans spec includes Enumerated Types defined via a standard interface and an EnumeratedType abstract class.

Adding Enumerated Types to the Java language would be better; but the EJB spec would definitely benefit from a similar addition.

17 EJB doesn't make a clear separation between the components and the machinery that is supposed to persist it. For example a bean can remove itself, which assumes a bean is always persisted and it must always be tied to a persistence mechanism.

18 Entity Beans bind the business logic with the persistence mechanism. Hence the need for Data Access Objects. If the persistence was orthogonal to the beans this function-ality would have been accommodated more naturally.

19 Optimistic locking is not accounted for. The EJB spec assumes either pessimistic lock-ing or not locking, or roll your own. There could have been a locking interface; or a way to specify a logical concurrency mechanism like isolation levels.

20 Most 'fast' EJB patterns seem to involve using sessions that go straight to the metal. Half the time is spent navigating, so half of the system ends up being rewritten.

Entity beans only appear to be useful in single entity transactions, but not where the entity bean needs to know about its dependent beans. When you save a bean, the graph of dependent beans should also be saved—but it doesn't work like that.

For EJB you can specify cascading deletes, but not combinations of creates, updates and deletes. To save a graph of beans you must create your own client side User Transaction and call each create on the home, set on the bean and remove on the bean. The beans should understand what has been changed in the graph and update the database accordingly.

If we were "putting the boot" into EJB, we would suggest that this means EJB is only half complete.

Page 27: Spring Blueprint

Exhibit 18: Issues with EJB Specification

Source: http://www.softwarereality.com/programming/ejb/conceptual.jsp

21 There is no meta-data for business, i.e. no meta level to describe your business. Just code.

22 EJB tries to address both the client side interfaces and the service provider interfaces. Really as a client we should only care about the client side interfaces. This would make EJB open to different implementations.

23 No standards for writing Session beans as Beans. Yet this approach is one of the most talked about on the web.

24 There is no concept of dependency, so that a bean is stored, removed or updated at the same time.

25 There is no concept of whether the primary key is generated externally by the appli-cation, internally by the container, or automatically by the database.

26 EJB is designed to handle high-transaction units of work in a distributed environment. A very small percentage of applications need this. When we define high-transaction usage we mean thousands, not hundreds. Most users need only tens a second. The EJB spec also neglects applications that need to return static data, or real-time data. There are not designs in place to return these objects.

27 No standardised integration with content management tools (other than "roll your own" solutions via JSP, for example). For large web sites, it isn't clear how these would integrate.

This is more of an issue with J2EE as a whole than EJB by itself.

28 To attach enterprise development without going to a higher level, without approach-ing it with a blueprint, is like trying to dig a tunnel through a mountain with ever so slightly sharper spoons. They shouldn't be working on this level.

29 Sun doesn't have a joined up strategy for persistence, i.e. JDO, JDBC, Java Blend, serialisation, XML, EJB without any common interfaces. This is similar to the case with GUIs, i.e. Swing, AWT, MIDP, and web front-ends which they are trying to address with the mysterious JavaFaces. This gives the impression that the various design groups at Sun are out of control.

30 ACID is not always wanted. For example, a search engine wants high performance, availability, in exchange for accuracy.

As with many of the issues raised in this article, the obvious answer appears to be: "So don't use EJB for this type of work." Unfortunately, we believe that this blinkered approach seriously limits EJB's usefulness. Why should it be limited to such a narrow field of use, simply because of some erroneous assumptions made early on regarding the sort of features that all enterprise applications would surely want?

31 Most web apps are not very transactional. EJB comes from a TP/MTS type background. Perhaps it should have been called TJB, Transactional Java Beans, so that people knew where it belonged. As it is, EJB co-opts areas that simply don't belong to it. It's a baroque framework for transactional Java beans, which tries to wear the clothes of the enterprise emperor.

EJB is very transactional—it sucks when it comes to high performance queries, read-only work.

32 EJB hasn't really addressed the issue of efficient access to remote objects. Effectively you have hand code. It would have been better to have client side beans where ven-dors could have generated different options. At the risk of plugging our own product, JGenerator allows you to do this.

Page 28: Spring Blueprint

Exhibit 18: Issues with EJB Specification

Source: http://www.softwarereality.com/programming/ejb/conceptual.jsp

33 There is no clear design for returning Relationships between beans. Should you return a primary key (and look it up on the client)? Or return a handle, which does the look up but needs Bean managed code, or return the related beans remote interface which in turn means referencing the remote bean from the server?

Container managed relationships can only exist between beans whose homes are on the same server. This makes it impossible to deploy an enterprise system where one bean references a bean in another database automatically. For example, several product databases may reference a central customer database. There is no way to automatically generate a getCustomer() method on a product. Not very Enterprise.

34 It's difficult for a bean to tell the server when it is dirty, or read-only. This is supported in some servers, not in others. This should become part of the specification.

35 Use of CMP beans locks you very much into the vendors' proprietary mapping tech-nology. Beware of the apparent ease of use that CMP tries to offer.

36 The EJB Spec imagines the role of a container builder and a server builder. This as-sumption that there would be separate container products that would run in the appli-cation server is incorrect. Hence the service puts unnecessarily tight constraints on state control. This should have been left up to the vendors.

37 Development is very slow. For example, the development cycle is tens of minutes, rather than seconds, simply to change a small value in a JSP. This is a huge project killer. Increased development time hardly helps with 'Internet time' projects.

38 There is no concept of a design time state, like in the Beans model that allows for a quick development cycle.

39 EJB represents a huge learning curve. The EJB spec is supposed to help, but seems to hinder. It's very complex. Even for the most experienced engineers and architects, getting all the niggling details correct makes development painfully slow.

40 Many sites do not need EJB complexity, yet people use EJB for the sake of fashion, or getting skills on their CV. Too many people are happy to sacrifice the future of their company/project, in order to get 'sexy' skills.

41 There is no way of knowing when set property values are done. Explicit transaction demarcation is done at the property level, not at the Bean level. If there was a store method on a home/session this would do this.

42 There are no standards for optimising Entity Beans, serializing the whole bean or sending property sets.

Page 29: Spring Blueprint

Exhibit 18: Issues with EJB Specification

Source: http://www.softwarereality.com/programming/ejb/conceptual.jsp

43 One way to fix the previous two problems would be to introduce "smart stubs" *. In-stead however, the programmer is expected to write straight to the wire for every property get or set, or to use facades, dependent objects etc. That's an awful lot of extra code, especially when it conceivably affects every single entity bean in your application.

* Smart stubs are a concept that CORBA came up with. A client side CORBA stub would have another stub subclassed (and could be delegated from). So the client side programmer thought they were going straight to the remote stub, but the application programmer had the opportunity to 'fiddle' with the call before it went.

Subclassing meant you could only do a little bit of fiddling, but delegation allows you to completely alter the RMI method call, so that you might write to the client a se-quence of "set" method calls, and all the time it would be storing the set values in a property list, instead of shoving them over the wire every time.

Then, when you call the commit transaction method, all the sets that you have done on all the objects in that transaction are bundled up and sent in one message. Con-versely all the properties can be pulled over when you call the first get, so you're not getting every tiny property every time you call a get method.

At Javelinsoft, we do this in our CJBs (Client Java Beans) by serializing the Entity Bean from the EJB server when we make the first get call, and filling it up and squirt-ing it back when we say save on the Home.

44 Stateless session beans are supposed to be the most scalable, yet they are not much more than RMI. However we still need to jump through all the hoops to get them working.

45 It isn't easy to put EJB in Applets. There is no concept of a lightweight interface.

46 EJB does not have count methods optionally automatically generated. This feature is used in many applications I have worked on to save loading objects into memory.

47 Non web app client access to EJB is vague, and inconsistently supported. Sometimes an application server will supply you with a jar to include in your application to get access to the EJBs; sometimes you just have to figure it out yourself and end up in-cluding several megabytes of jars.

48 The spec for EJB cross beans mapping is constantly under change, and inconsistent across servers. It's also not flexible. The result is that you cannot easily port from one application server to another.

49 We need to use value objects to get any real performance, else each get/set makes an RMI call. Why was this concept of local stubs or property sets not put into EJB? Performance should not be an irrelevance.

50. EJB wizards are often shaky and dangerous. They end up creating code that simply won't work. So you waste time thinking it must be your own problem somewhere. For example, the RI (Reference Implementation) 1.3 container entity bean wizard misses out "throws CreateException" on ejbCreate.

51 The RI seems to have had 0 to little Q.A. For example, 1.3 RI code generation tools simply produce wrong code. Their entity bean managed findByPrimary would never work. This is of no help to anyone learning EJB.

As the RI is the "Reference Implementation" this is very bad. No one expects the RI to be fast, but we do expect it to be a model of compliance and correctness.

52 The WAR/JAR/EAR model is horrible for development and deployment. The deployment spec is opaque, using the Russian Doll metaphor.

Page 30: Spring Blueprint

Exhibit 18: Issues with EJB Specification

Source: http://www.softwarereality.com/programming/ejb/conceptual.jsp

53 EJB deployment is incredibly fragile. Miss setting a property and the container won't use a sensible default. Of course this depends on the container, but mostly they sim-ply throw a vague error message and refuse to continue. This is just plain unhelpful—"jobsworth", even.

The servlet world has it easy in comparison—e.g. the "invoker" servlet executes anonymous servlet classes that have not been defined in a web.xml file (usually maps to /servlet/*).

In other words, servlet engine writers go to special efforts to make deployment easy. Easiness is what it's all about. EJB containers don't have the equivalent of a default web.xml file that they can inherit default properties from.

54 There is no standard way to deploy an EJB application. The details change with each server, and (worse still) with each revision of each server.

55 EJB needs to be more IDE-friendly, particularly when it comes to deploy-ment.Deployment is not always opened up to tools, e.g. RI 1.2.2/1.3 uses batch files which call Java. Its deploy/package code is not meant to be called by tools. The RI uses the broken concept of current directory, i.e. must be called from a DOS window, not from an IDE VM.

56 The EJB spec has too many fictitious roles. In reality there are container/server pro-viders, and application providers who develop, assemble, deploy, and administer the EJB server. The EJB spec should reflect this reality.

57 There is no such thing as cross platform EJB. Each platform has its own horrible bugs. Escape one system to fall prey to another.

58 Developers have to repeat the same meta-data in the code as SQL, as client proper-ties as server properties, as XML attributes.

59 Container managed EJB often requires you to specify a lot of what would be in your code, for example the SQL.

60 Administration is different with every server. There is no standard for administering the deployed EJBs.

61 XML is all about interpretation. Different vendors interpret the XML differently. For example (on the servlet/JSP side), web.xml's <welcome-file-list>. Some see this as 'look for these files in this order', others as 'these files should be here'.

Of course this sort of misunderstanding just can't be helped sometimes, but is in-cluded here as something to be wary of—it's an example of how ambiguity can creep into a seemingly bullet-proof spec and cause standards to fragment.

62 The specifications are continually changing. That's ok, but when new versions cannot run old applications without major changes, then we have a problem.

63 The server vendors have graced us with some remarkably vague and misleading de-ployment tools, e.g verifiers that spout unhelpful error messages, or pass classes that then fail on deployment.

64 Loose coupling between the bean and interface. The XML is not strongly typed, i.e. too much room for error. Very little use of reflection to work out class relationships.

65 Deployment of code, in order to test it, is a horribly complex, click-laden process. As well as involving many stages, there seems to be no proper way to automate it, espe-cially if you are attempting to target many different EJB servers.

Page 31: Spring Blueprint

Exhibit 18: Issues with EJB Specification

Source: http://www.softwarereality.com/programming/ejb/conceptual.jsp

66 The basic ejb.xml, web.xml and application.xml descriptors are not sufficient to de-ploy. The result is that further descriptor information must be written using app-server specific XML. This means that every ear must be changed to be deployed. It would have been better to have defaults set up so that a minimally defined EJB would deploy and run without modification.

67 The XML descriptors use ambiguous names—for example, displayName isn't just the display name, it's used as the reference name.

68 An EJB ear should be able to be deployed on ANY compliant EJB server, with no changes to the ear.It should expose and advertise the environmental items that can be changed (like war mount point), and those that MUST be changed (like database connections).

However, there should be no requirement on the ear developer to produce X different versions, for all the servers out there. This seems to be the current state, which is madness.

69 The Validator passes descriptors which later fail on deploy. For example (using Cata-lina/Tomcat in RI 1.3), try creating a war file with multiple entries with the same name. The war is passed on verify, but of course fails to deploy.

A connected problem is that once deployed, there is no way to automatically test that your beans have actually deployed.

These might not be such terrible issues, but they merely add time and frustration to an already slow process.

70 The real bottleneck is data access and transactions, of which the average database can only handle about 50-100 a second. EJB needs to take on board replication server duties in order to really speed things up.

71 There is very little scope for run-time optimisation. The EJB specification contains no standard flags or extensions for improving performance. For example, WebLogic has used a 'dirty' flag to help determine if the object should be written down to the data-base. Despite being a well-known extension with well-understood semantics, this did-n't make it into the latest specification.

72 EJB performance is very slow, and uses lots of resources. It's costly to scale. The "fetch my primary key" query model suggests that the designers did not understand how relational databases work: The EJB queries return a list of primary keys. Each of these primary keys are then used to perform another query to the database. This operates in a way contrary to the way relational databases are optimised, i.e. on sets of rows. The whole philosophy behind EJB object pools is to re-use objects, and not cache them. This relates to Damnation #3—that EJB is designed to preserve memory, when memory is not a scarce resource—in fact it's a dime-a-bucket at the moment.

73 EJB cannot scale. Because your entity beans need to be synchronised across all the servers that they are deployed on, the amount of network traffic multiplies.

74 Black box. When your deployed system goes slow you can't work out why unless you have the container source.

75 An EJB server is harder to build than a servlet engine. Hence they tend to be far more fragile and mad, which is hardly a good base for an enterprise application.

76 Sun said that to be 2.0 compliant an EJB app-server would also have to support 1.2 compliant EJBs. But their own reference implementation does not support 1.2 compli-ant beans, because the Sun specific 2.0 XML interpretation throws errors with 1.2 compliant XML.

Page 32: Spring Blueprint

Exhibit 18: Issues with EJB Specification

Source: http://www.softwarereality.com/programming/ejb/conceptual.jsp

77 Sun's J2EE compliance tests seem to let some pretty obvious omissions through. For example HP-AS doesn't handle nested archives (i.e. referencing one jar from another through a declaration in the Manifest file), which is part of the J2EE spec. A server can be officially branded J2EE, even if half its J2EE features are broken. The promise that they'll be made to work in the next service release doesn't quite cut it, and often ends up not happening.

78 Where is the large-scale EJB usage? The thousands of downloads of J2EE, WebLogic, HP-AS, JBoss etc don't quite tally with the number of real-life EJB systems in use.

79 Where is the large-scale usage of EJBs? How many companies are really using EJB for massively scalable back-end systems?

80 Where is the thriving EJB component marketplace 3 years from inception? The situa-tion seems similar to what was said of C++. VB/Delphi/Java had and has loads of components, as it is so easy to write them.

81 The EJB specification was not focused on any applications. There should have been two or three big, complex, real world apps that needed to be expressed in EJB as a testbed.

It took Sun about 2 years to come up with Pet Cemetery, and even then, it proves nothing except that they don't have a clue. This same criticism is just like that of Swing—it took years to come up with proper test apps, e.g. Forte!

82 Sun's main revenue stream is from hardware, not Java. Their profit driver is to sell hardware. This explains why EJB has not been reigned in and rationalised.

83 There is no real synergy between EJB and the rest of J2EE.

84 Most, if not all, EJB articles on the web seem to be about hacks, bugs, workarounds, optimizations, as opposed to glowing success stories. Where are they?

85 The creators of the EJB spec are in a privileged position. It's very easy to define huge, complex specifications and expect the industry to forever be trying doggedly to catch up with actual implementations of their mad schemes and "visions".

It's not so much an OO Utopia as a "Complexia". It would be much harder for them to try and implement their own specs (as they discovered with the RI mess).

The server vendors don't get a chance to make their servers useable or robust, as they're forever trying to catch up with Sun's latest promised feature-list made on their behalf. Then there's the even bigger problem of supporting legacy versions (for those vendors that can be bothered with such "trivial" notions).

86 Brave New World—this isn't just a comment on EJB, but on the state of enterprise computing:

Everyone expected the OO dream to materialise with interconnected, co-operating objects whizzing around global networks—instead we have gronky EJBs and labour-intensive EAI systems (e.g. BizTalk), much too complex for their own good.

87 The basic idea behind EJBs, and Sun's approach to APIs, is good. The principle of de-fining standard specifications for the industry to follow is a noble one. But something, somewhere, has gone terribly wrong.