Notes on Spring Framework, version 2

batterycopperInternet και Εφαρμογές Web

12 Νοε 2013 (πριν από 3 χρόνια και 9 μήνες)

298 εμφανίσεις

Page
1

of
27

Notes on
Spring

Framework
, version 2

Created 08/22/07

Updated 08/25/07
, Updated 08/28
/07
,
Updated 08/29/07
, Updated 08/30/07
,
Updated 09/03/07
,
Updated 09/06/07

Updated 09/26/07
, Updated 09/28/07
,
Updated 10/01/07
, Updated 10/02/07
,
Updated 10/11/07
, Updat
ed 10/15/07

Updated 11/16/07
, Updated 11/19/07
, Updated 12/27/07
,
Up
da
ted 12/18/07,
Updated 01/13/08
, U
pdated 02/02/08

Updated 02/24/08
, Updated 03/16/08, Updated 05/26/08
, Updated 12/02/08
, Updated 12/14/08
, Updated 12/18
/08

Updated 02/07/09
, Updated 02/1
2/09
, Updated 03/12/09
, Updated 08/22/09
, Updated 10/26/09
, Updated 09/09/10

Introduction

The Spring Framework is one of the

most commonly used web application framework
s
. It is considered to be an
improvement over Struts

and EJB 2
, particularly as it als
o helps build non
-
web applications,
and to handle database
access
.
It has layers of available capabilities

(hence is
considered

“full stack”)
, is more flexible in how those layers
can be put together, and is more configurable in the “wiring” of those laye
rs and their components.


Spring consists a framework that handles initialization, configuration, web
-
servlet action dispatching, validation, a
tag library,

and database access. Spring has been under deve
lopment and use since about 2002
.


There are
three

primary versions of Spring:

the 3.0.x series is the newest

and
the 3.0.5

is the current version,
released
late

2010.

The Spring 3.0.x

versions introduce

extensive support for using Annotations to configure a web
application, but we have not tried this ye
t.
The Spring 2.5.x series was an interim step toward an Annotation
-
driven
system.
The 2.0.x series was released in

2006 through 2008
, with the
final
2.0.
8

release in
October

2008
.


Spring development is carried out by a full
-
time set of developers, plus

open
-
source member contributions. The
company is called SpringSou
rce (formerly called Interface21). In M
ay 2007, SpringSource received a $10M
investment from Benchmark Capital.

In August 2009, SpringSource was purchased by VMware for $420M.

Layers,

Arc
hitecture
, and Benefits

Layers

in Spring 2



Spring is composed of the above seven modules. In general, each one of is a separate JAR file. The most important
is Spring Core, which defines the Bean management facilities and the configuration reader. Th
e next most
important is Spring Context, which defines the runtime context for an application, and supporting tools such as
Page
2

of
27

email, JNDI, etc. Other pieces supply the persistence facilities, and the web tools including parsing HttpRequests,
connection to p
resentation facilities such as JSP or Velocity.


The majority of these modules and their component classes can be used in a flexible way, and they tend to be
organized around interfaces which can be implemented by various classes, to allow for easy extensi
on.


The best way to understand the goals of Spring
is

to see it as a component management
system

first, built around a
facility for using Dependency Injection to “wire up” the components. Then look at it as a set of component libraries
that provide servi
ces important to J2EE programs, such as database management, presentation generation, JNDI,
mail, etc.

These libraries can be understood on an “as
-
needed” basis.
In this respect Spring is an alternative to the
services and components in EJB. Spring emer
ged as a “lighter
-
weight” response to the EJB architecture,
particularly versions 1 and 2. While EJB 3 is much easier to use (and in fact has incorporated many innovations
from Spring), the Spring framework continues to be important, largely because it do
esn’t require full EJB containers
such as JBoss or WebLogic, instead running on Tomcat or even adding value to non
-
web applications.

Spring for Web Applications

In this section, we profile those parts of the Spring library that can be used for building web

applications such as
request dispatchers, form processing, and more, working from the servlet API and the JSP facilities. In this respect
Spring is an alternative to Struts as a frontend, as Struts was the major web framework when Spring was created.
Th
e portion of the framework is called Spring MVC.

Architecture

By comparison, t
he Struts design is based on concrete inheritance, meaning that each custom action has to be in an
inheritance hierarchy of the Struts Action component.

Because Spring controlle
rs are interfaces, any component can
play the role of the controller.

This gives application designers more flexibility in the design of components.


At the framework component level, Struts requires use of Struts
-
specific objects, such as Form Beans (st
atic or
dynamic), Actions, Action Mappings, Action Forwards, and Request Processors.

Spring MVC is more flexible, as
all its major components are defined as interfaces.

No Action Forms

One of the biggest and the most positive differences in the Spring fr
amework is that it has no specialized
ActionForm objects. The framework supports binding of HTTP form values directly into POJOs (Plain Old Java
Objects). This feature greatly simplifies application maintenance by limiting the number of classes to create

and
maintain.

ActionForwards vs. ModelAndView

In Struts ActionMapping, objects are pointers into presentation resources (Actions, JSPs, Tiles, HTML files, etc.).
The closest component in Spring MVC to ActionMapping is the ModelAndView interface. Spring
Controllers return
implementations of the ModelAndView interface, which like a Controller can be custom implemented.

Or, if
appropriate, you can use the ModelAndView implementation supplied by Spring MVC.


As the name implies, ModelAndView objects have M
odel and View components.

Model components contain the
business object to be displayed via the View component.

Depending on the scenario, ModelAndView
implementations may not have any Model components included.

They may simply forward into some form of
an
actual View component (JSP, XSLT, Tiles, HTML, XML, etc.). As with Controller implementations, it is strongly
recommend
ed

that you use Spring MVC
-
supplied implementations of the Model and View interfaces and View
Resolvers.

Custom JSP Tags

Spring MVC
relies on the expressive power of the standard JSP tag libraries. Unlike Struts, Spring MVC does not
supply separate tag libraries for HTML, logic, or bean processing. It offers only a small tag library (Spring) that
Page
3

of
27

enables binding of Command objects in
to Web forms
, and a small tag library (Spring
-
forms) that is useful for
building forms
. You should use standard template libraries (JSTL) for all other tasks.

Resources

“Spring Recipes” by Gary Mak. APress, June 2008
, 752 pages
. List price $49.99, Amazo
n price
$
31.49, used from
$22
.40
. Rated 5 stars on Am
a
zon.com.
Based on Spring 2.5. Considered to be a very practical set of solutions and
examples.



“Pro Spring

2.5
” by
Jan
Machacek
, Jesscia Ditt, and other
s
.
APress,
August 2008
, 806 pages.

Lis
t pri
ce $49.99,
Amazon price $31.4
9
,

used from $26.03
.
The first edition covered Spring 1.2 and was r
ated 4.5 stars

on Amazon,
however, this edition, while updated to Spring 2.5, was
heavily

re
-
written and got only 2 stars on Amazon, as some
reviewers felt tha
t it was poorly written
, compared to the “Spring in Action” second edition book.


“Spring in Action, Second Edition” by Craig Walls with Ryan Briedenbach. Manning Press, August 2007. List
price $49.99, Amazon price $31.99, used from $21.79. This edition

documents Spring 2.0.x. First edition rated 4
stars on Amazon. The first edition got the second
-
highest reviews, and the second edition maintains the quality.
The book covers beans, the persistence approaches, web services, the presentation facilities,

etc. The examples are
quite clear.




Spring: A Developer’s Notebook” by

Bruce Tate, others, 2007
. This is a good hands
-
on informal set of lessons on
using Spring. Be sure to read the revised edition, as there were quite a few typos in the initial prin
ting. The only
way to tell is to check for “Revised edition” label on the front cover.


“Professional Java Development with the Spring Framework” authors include Rod Johnson and Thomas Risberg.
Wrox
, April 2005. Amazon comments for this book indicated t
hat most of what it covers is already on the web site.



J2EE Development without EJB” by Rod Johnson.
Wrox Press,

June
2004. 576 p
a
ges, rated 4.5 stars on Amazon.
Desc
ribes the background for Spring, and wa
s written during 2001
-
2003
, as it was preceded

by a similar book
“J2EE Design and De
velopment”, also by Rod Johnson
.

A very important book when it

came out, but more recent
books provide more current information about Spring.


The
on
-
line
document
“Developing a Spring Framework MVC application step b
y step” by Thomas Risberg, Ma
rch
2003, revised April 2005
, revised sometime in 2007
.
Located at
http://static.springframework.org/docs/Spring
-
MVC
-
step
-
by
-
step/
.

This is a v
e
ry commonly used tutorial
, and is written and maintained by a member of the
Spring framework organization
, SpringSource

(formerly
called
Interface21)
.

We have been through all of the steps,

and added more operations to the code we created from it
.

The Min
imal Set of Libraries

For a non
-
web application:



Spring
-
core



Spring
-
beans



Spring
-
context


Add the following for a web application:



Spring
-
web



Spring
-
webmvc


Add the following for

jdbc
-
based

persistence
:



Spring
-
dao



Spring
-
jdbc


Add the following
for hiberna
te
-
based persistence:



Spring
-
hibernate3


Page
4

of
27

Add the following for Aspect Oriented Programming
:



Spring
-
aop


As of Java 1.5, the only other libraries which believe are needed include: commons
-
logging.

Spring
Concepts

Beans and Contexts

A bean is synonymous with

a “component”. The term “bean” is used in the same sense as “Enterprise Java Bean”.


Two of the most elementary and
important packages in Spring are the
org.springframework.beans

and
org.springframework.context

packages.


Code in these packages provides
the basis for Spring's
Inversion
of Control

(alternately called
Dependency Injection
) features. The
BeanFactory

provides an advanced
configuration mechanism capable of managing beans (objects) of any nature, using potentially any kind of storage
facility.

The
ApplicationContext

builds on top of the
BeanFactory

(it's a subclass) and adds other
functionality such as easier integration with Springs AOP features, message resource handling (for use in
internationalization), event propagation, declarative mecha
nisms to create the
ApplicationContext

and
optional parent contexts, and application
-
layer specific contexts such as the
WebApplicationContext
, among
other enhancements.


In short,
the
BeanFactory

provides the configuration framework and basic functionalit
y, while the
ApplicationContext

adds enhanced capabilities to it, some of them perhaps more J2EE and enterprise
-
centric.
In general, an
ApplicationContext

is a complete superset of a
BeanFactory
, and any description of
BeanFactory

capabilities and behavio
r should be considered to apply to
ApplicationContext

as well.


Users are sometimes unsure whether a
BeanFactory

or an
ApplicationContext

are best suited for use in a
particular situation. Normally when building most applications in a J2EE
-
environment,
th
e best option is to use the
ApplicationContext
, since it offers all the features of the BeanFactory and adds on to it in terms of features, while
also allowing a more declarative approach to use of some functionality, which is generally desirable. The main

usage scenario when you might prefer to use the BeanFactory is when memory usage is the greatest concern (such as
in an applet where every last kilobyte counts), and you don't need all the features of the ApplicationContext
.


The configuration reader that

instantiates the beans also resolves references from one bean to another, by an ID
string.

Application Context Configuration File

The applicationConfig.xml file, or a file similar to it, defines the set of beans that are to be resident in the container.


Each bean has the following information:



an id String



the Java class to instantiate (which must have default constructor, except as shown below)



property values for the beans



references from one bean to another, using the target bean’s id string.


The file

is typically written in a containing XML element called <beans>. Here is an example:


<beans>


<bean id=”mod1” class=”com.incra.module.BaseModule”>


<property name=”name”><value>Locations</value></property>


<property name=”img”><value>Location.gif<
/value></property>


</bean>


<bean id=”mod2” class=”com.incra.module.BaseModule”>


<property name=”name”><value>Organizations</value></property>


<property name=”img”><value>Organization.gif</value></property>

Page
5

of
27


</bean>

</beans>


This is one of the s
implest cases. The classes are fully specified, and the ids are present.


The
<property/>

element s
specifies

a property or constructor argument as a human
-
readable string
representation.


As mentioned previously
, JavaBeans
PropertyEditors

a
re used to con
vert their
values

(as
given in the
<value>

elements)

from a
String

to the actual type of the property or argument.


It is also possible initialize to a list of values, by using the
<list>

element around the
<value>

elements.


Other information can be speci
fied include the constructor arguments, and the destroy method. The former is used
when the bean doesn’t have
a default c
onstructor:


<bean id=
"
example
"

class=
"
com.incra.ComplexClass
"
>


<constructor
-
arg
value=
"
12
"
/>


<constructor
-
arg
value=
"
Testing
"
/>

</bean>


Note that the syntax doesn’t provide for indicating the names of the constructor arguments, mostly because Java
reflection doesn’t provide such. Hence the order is important.


Putting it all together, we have examples such as:


<bean id="myDat
aSource" class="org.apache.commons.dbcp.BasicDataSource"


destroy
-
method="close">




<!
--

results in a
setDriverClassName(String)

call
--
>


<property name="driverClassName">


<value>com.mysql.jdbc.Driver</value>


</property>


<property name="
url">


<value>jdbc:mysql://localhost:3306/mydb</value>


</property>


<property name="username">


<value>root</value>


</property>


<property name="password">


<value>masterkaoli</value>


</property>

</bean>


The
<property/>

and
<constructor
-
a
rg/>

elements also support the use of the
'value'

attribute, which
can lead to much more succinct configuration.

When using the
'value'

attribute, the above bean definition reads
like so:


<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSo
urce"


destroy
-
method="close">




<!
--

results in a
setDriverClassName(String)

call
--
>


<property name="driverClassName" value="com.mysql.jdbc.Driver"/>


<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>


<property name="username"

value="root"/>


<property name="password" value="masterkaoli"/>

</bean>


The Spring team generally prefer the attribute style over the use of nested
<value/>

elements.

You

can also
configure a
java.util.Properties

instance like so:


Page
6

of
27

<bean
id="mappings"


class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">




<!
--

typed as a
java.util.Properties

--
>


<property name="properties">


<value>


jdbc.driver.className=com.mysql.jdbc.Driver


jdbc.
url=jdbc:mysql://localhost:3306/mydb


</value>


</property>

</bean>


Can you see what is happening?

The Spring container is converting the text inside the
<value/>

element into a
java.util.Properties

instance using the JavaBeans
PropertyEditor

mech
anism.

This is a nice
shortcut, and is one of a few places where the Spring team do favor the use of the nested
<value/>

element over
the
'value'

attribute style.

Application Contexts

The
article
on Spring
by Bruce Tate in early 2004

described

the layers of
an
application that is built with Spring.
Here are some of the things that might go into an application context:




Data sources:


Java classes that manage connections,
usually in a pool



DAO objects: these provide isolation of your data access code from the rest of the application



Persistence managers: these would include session objects and session managers.



Transaction policies and managers: these can configure the t
ransaction sets.



Validation logic: this include validation checkers



Views and view controllers: these include screen definitions and view resolution facilities.


You might also split up the application contexts into ones for business logic, data layer, a
nd user interface. Each
would be in a separate XML file.

These can be combined through the “import” facility in the application context
config file, or through loading multiple such files.


The domain model contains the business relationships of objects
that represent the real world, for instance, Products,
Orders, LineItems, etc.

Factory Beans

If you create a bean definition for which the target class implements in the BeanFactory interface, then the bean
definition is naming a factory instance, and when

you get the bean, from the application content, you will get the
result of the factory, not the factory itself.


T
here is sometimes a need to ask a container for an actual
FactoryBean
instance itself, not the bean it

produces.

This may be achieved by pre
pending the bean id with
'&'
(sans quotes) when calling the
getBean

method of the
BeanFactory
(including
ApplicationContext
).


So for a given
FactoryBean
with an id of

myBean
,
invoking
getBean("myBean")

on the container will return the product of the
Facto
ryBean
, but

invoking
getBean("&myBean")
will return the
FactoryBean
instance itself
.

Bean Parents

Parents refer to a bean having the configuration property values of another, “parent” bean, and hence
reducing

the
number of common properties that must be
gi
ven values.

A child bean definition is a bean definition that inherits
configuration data from a parent definition.

It is then able to override some values, or add others, as needed.


Using
parent and child bean definitions can potentially save a lot of
typing.

Effectively, this is a form of templating.

Here
is an example:


<bean id="inheritedTestBean" abstract="true"


class="org.springframework.beans.TestBean">

Page
7

of
27


<property name="name" value="parent"/>


<property name="age" value="1"/>

</bean>


<bean id="inheritsWithDifferentClass"


class="org.springframework.beans.DerivedTestBean"


parent="inheritedTestBean"
init
-
method="initialize">


<property name="name" value="override"/>


<!
--

the age property value of 1 will be inherited from
parent
--
>

</bean>


Note that the parent has been marked as abstract=”true”, just as can be specified in Java class definitions

Bean References

One bean can refer to another with the “ref=” attribute syntax. Here is an example:


<bean id="mySessionFactory
"


class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">


<property name="dataSource" ref="myDataSource"/>

</bean>


In this case, property doesn’t have a scalar value, but has a reference to the bean whose id is “myDataSource”. This
is the preferred way to inject dependencies.


Specifying the target bean by using the
bean

attribute of the
<ref/>
tag is the most general form, and will allow
creating a reference to any bean in the same container (whether or not in the same XML file), or

parent container.
The value of the
'bean'

attribute may be the same as either the
'id'

attribute of the target bean, or one of the
values in the
'name'

attribute of the target bean.


<ref bean="someBean"/>


Specifying the target bean by using the
local

at
tribute leverages the ability of the XML parser to validate XML id
references within the same file.

The value of the
local

attribute must be the same as the
id

attribute of the target
bean.


The XML parser will issue an error if no matching element is fou
nd in the same file.

As such, using the local
variant is the best choice (in order to know about errors as early as possible) if the target bean is in the same XML
file.


<ref local="someBean"/>


The following example creates a parent
-
children linkage, an
d can be used for Module instances within the
Application instance:


<bean id=
"
application
" class="com.incra.MetroApplication"
>


<property name=
"modules"
>


<list>


<ref local="SalesOrder"
/>


<ref local="
PurchaseOr
der"
/>


</list>


</property>

</bean>


In the Application class, you would have a setter such as “public void setModules(List<Module>)”.


The application content will build the beans in network dependency order. That is, it will first bean the bean or
bean
s

with no pri
or dependencies, such as the application object. Then it will build e
ach referred
-
to bean, then their

references, etc.


Page
8

of
27

Circularities cannot occur because before building each reference target, the container determines if a bean with that
id has already b
een

built
.


There is also a facility called “autowire”, which will example the properties of a bean, and search for beans of a
matching class. If there is

only one such, it will be injected in, just as if it was explicitly specified.

However, you
are cau
tioned not to rely on the autowire too much, because what if your initial configuration does only have one
each of a specific class, but sometime later a second bean is added. The changes to the configuration will be hard to
locate.

Checking D
ependencies

The Spring IoC container also has the ability to check for the existence of unresolved dependencies of a bean
deployed into the container.

These are JavaBeans properties of the bean, which do not have actual values set for
them in the bean definition, or
alternately provided automatically by the autowiring feature.



When using XML
-
based configuration metadata, this is specified via the 'dependency
-
check' attribute in a bean
definition, which may have the following values
:




N
one
:

No dependency checking.

Properties of the bean which have no value specified for them are simply
not set.



S
imple
: Dependency checking is performed for primitive types and collections (everything except

collaborators).



O
bject
: Dependency checking is performed for collaborators o
nly.



A
ll
: Dependency checking is done for collaborators, primitive types and collections
.


The default is to
not
check dependencies.

Managing the Application Context

Using multiple application contexts: see the following article


http://72.14.253.104/search?q=cache:Amu4WiQSRUwJ:www.onjava.com/pub/a/onjava/excerpt/BFLJava_chap8/in
dex.html+spring+application+contexts&hl=en&ct=clnk&cd=3&gl=us


It can often be useful to split up container definitions into multiple XML files. One way to then load an application
context which is configured from all these XML fragments is to use the ap
plication context constructor which takes
multiple
Resource

l
ocations. With a bean factory, a bean definition reader can be used multiple times to read
definitions from each file in turn.


Generally, the Spring team prefers the above approach, since it ke
eps container configuration files unaware of the
fact that they are being combined with others. An alternate approach is to use one or more occurrences of the
<import/>

element to load bean definitions from another file (or files). Any
<import/>

elements

must be placed
before
<bean/>

elements in the file doing the importing.


A bean can access its ApplicationContext if it implements ApplicationContextAware. This will cause the bean’s
setApplicationContext method to be called during init time.


Given an a
pplication contex
t, a program can find a bean by id, or find a set of beans by class.

This latter approach is
used to our code to introspect across the module configuration specialized
-
list.


In a Tomcat web application, the
context

will be loaded at
weba
pp
init time by containing th
e following in its
web.xml file (this works for Servlet 2.3 specification
-
based servers):


<listener>


<listener
-
class>


org.springframework.web.context.ContxtLoaderListener


</listener
-
class>

Page
9

of
27

</listener>


As far as we can

tell, there no facility to add to an application context, only to create one by reading from a source,
such as an XML file.


There is a facility to create parent
-
child linkages of applicationContexts, by using the setParent and getParent
routines. This w
ill cause a getBean() method against the child application context to fetch in the parent if no bean
with th specified name (or name/class) is present in the initial application context.


In general, the approach is to create two distinct applicationContex
ts, then setParent on one to be the other. The
built
-
in facilities for applicationContext don’t seem to create trees of applicationContexts, though perhaps this is
provided in some add
-
on software packages.

Enterprise Spring

Enterprise

Spring

is defined a
s

server
-
side framework code

that is built on the above concepts, and also provides
typical enterprise operations such as data persistence, security, and web services.

These facilities are similar in
intent to their EJB counterparts, but are more flexible
.

Hibernate
Integration

Spring introduces a DAO exception hierarchy, applicable to any data access strategy. For direct JDBC, the
JdbcTemplate

class mentioned in a previous section cares for connection handling, and for proper conversion of
SQLException

t
o the
DataAccessException

hierarchy, including translation of database
-
specific SQL error
codes to meaningful exception classes. It supports both JTA and JDBC transactions, via respective Spring
transaction managers
.


If you use the spring
-
hiberate.jar li
brary, it provides two important classes:



HibernateDaoSupport



HibernateTemplate

Hibernate Configuration

To avoid tying application objects to hard
-
coded resource lookups, Spring allows you to define resources like a
JDBC
DataSource

or a Hibernate
SessionFa
ctory

as beans in an application context.

Application objects
that need to access resources just receive references to such pre
-
defined instances via bean references (the DAO
definition in the next section illustrates this).

The following excerpt from an

XML application context definition
shows how to set up a JDBC
DataSource

and a Hibernate
SessionFactory

on top of it:


<beans>


<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"


destroy
-
method="close">


<property name="dri
verClassName" value="org.hsqldb.jdbcDriver"/>


<property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>


<property name="username" value="sa"/>


<property name="password" value=""/>


</bean>


<bean id="mySessionFactory"


class="org.
springframework.orm.hibernate3.LocalSessionFactoryBean">


<property name="dataSource" ref="myDataSource"/>


<property name="mappingResources">


<list>


<value>product.hbm.xml</value>


</list>


</property>


<property name="hiber
nateProperties">


<value>


hibernate.dialect=org.hibernate.dialect.HSQLDialect


</value>

Page
10

of
27


</property>


</bean>

</beans>


Note that switching from a local Jakarta Commons DBCP
BasicDataSource

to a JNDI
-
located
DataSource

(usually manage
d by an application server) is just a matter of configuration
:


<beans>


<bean id="myDataSource"


class="org.springframework.jndi.JndiObjectFactoryBean">


<property name="jndiName" value="java:comp/env/jdbc/myds"/>


</bean>

</beans>

Coding the D
AO

public

class

AccountDAOImpl
extends

HibernateDaoSupport
implements

AccountDAO {




public

void

saveAccount(Account account) {



getHibernateTemplate().save(account);




}




public

Account getAccountInfo(Account template) {



Account acc =
null
;



List
list = getHibernateTemplate().find




(
"from Account account where account.accountName = ?"
,





template.getAccountName());






if

(list.size() > 0) {




acc = (Account) list.get(0);



}






return

acc;





}




public

List<Account> getAllAccounts() {



List list = getHibernateTemplate().find(
"from Account account"
);







return

list;


}

}


In this case the bean configuration file specifies that a AccountDAOImpl is to be made, and the session factory
(called “mySessionFactory”) is inserted into it. Us
ing IOC.


The
HibernateTemplate

class provides many methods that mirror the methods exposed on the Hibernate
Session

interface, such as save(), insert(), find(), etc.


HibernateTemplate

will ensure that
Session

instances are properly opened and closed, and

automatically
participate in transactions. The template instances are thread
-
safe and reusable, they can thus be kept as instance
variables of the surrounding class. For simple single step actions like a single find, load, saveOrUpdate, or delete
call,
HibernateTemplate

offers alternative convenience methods that can replace such one line callback
implementations.


In this case the HibernateTemplate class is a proxy for the Hibernate session, and the HibernateDaoSupport class is
providing getter and sett
er for SessionFactory.


The
HibernateDaoSupport

base class offers methods to access the current transactional
Session

and to
convert exceptions in such a scenario; similar methods are also available as static helpers on the
SessionFactoryUtils

class.

No
te that such code will usually pass '
false
' as the value of the
Page
11

of
27

getSession(..)

methods '
allowCreate
' argument, to enforce running within a transaction (which avoids the
need to close the returned
Session
, as its lifecycle is managed by the transaction).

Us
ing the Hibernate Template findByExample method


public List findByExample(final Object exampleEntity,


final int firstResult, final int maxResults)


throws DataAccessException {



Assert.notNull(exampleEntity, "Example entity mus
t not be null");


return (List) execute(new HibernateCallback() {



public Object doInHibernate(Session session) throws HibernateException {




Criteria executableCriteria =


session.createCriteria(exampleEntity.getClass());




executableCriteria.add(Example.create(exampleEntity));




prepareCriteria(executableCriteria);




if (firstResult >= 0) {





executableCriteria.setFirstResult(firstResult);




}




if (maxResults > 0) {





executableCriteria.setMaxResults(maxResults);




}




return executableCriteria.list();



}


}, true);

}


We’ve added in this code fragment, because there are quite a few findByExample methods in our code, which need
to have the sortCriteria applied. Unfortunately, the HibernateTemplate class provides
convenience methods that are
slightly too high level for us to use directly.

Transaction Management

You can specify the transaction boundaries of the operations in the beans.xml file.


Where to put this: in the transaction property factory bean. This bean

has several specification modes, including:


PROPAGATION_REQUIRED
. This attribute is equivalent to
TX_REQUIRED

with respect to the EJB container. You use
PROPAGATION_REQUIRED

if you want the methods to always run in a transaction. If a transaction is al
ready running,
the bean method will join in that transaction or the Spring lightweight transaction manager will start one for you. If
you want a new transaction to always begin when the component services were called, you would use the
PROPAGATION_REQUIRE
S_NEW

attribute.


Here is an example:


<bean id="customerDAOTransControl"


class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">


<property name="transactionManager"><ref local="transactionManager"/>


</property>


<proper
ty name="target"><ref local="customerDAOTarget"/>


</property>


<property name="transactionAttributes">


<props>


<prop key="addCustomer">PROPAGATION_REQUIRED</prop>


</props>


</property>


</bean>


In this case CustomerDAOTarget is the
DAO implementation object itself. We called those myCustomerDAO.


Page
12

of
27

The object also has a reference to the transaction manager.


The transaction attributes are specified here.


In our case, the insert, update, and delete methods would need a transaction.

Sp
ring Web Services

Spring 2.5 fully supports JAX
-
WS 2.0/2.1, as included in Java 6 and Java EE 5.

JAX
-
WS is the successor of

JAX
-
RPC, allowing access to WSDL/SOAP
-
based web services as well as JAX
-
WS style exposure of web services.


Spring has support for:



Exposing services using JAX
-
RPC



Accessing web services


In addition to stock support for JAX
-
RPC in Spring Core, the Spring portfolio also features
Spring Web

Services
, a solution for contract
-
first, document
-
driven web services. Last but not least,
XFir
e
also allows you to
export Spring
-
managed beans as a web service.


Spring has a convenience base class for JAX
-
RPC servlet endpoint implementations
-

ServletEndpointSupport
.


To expose our
AccountService

we extend Spring's
ServletEndpointSupport

class and

implement our business logic here, usually delegating the call to the
business layer.


Spring has two factory beans to create web service proxies, namely
LocalJaxRpcServiceFactoryBean
and
JaxRpcPortProxyFactoryBean
.

The former can only return a JAX
-
RPC s
ervice class for us to work with.
The latter is the full fledged version that can return a proxy that implements our business service interface. In this
example we use the latter to create a proxy for the
AccountService

endpoint we exposed in the previ
ous
paragraph.


Spring has great support for web services requiring little coding efforts
-

most of the setup is done in the
Spring configuration file as usual:


<bean id="accountWebService"



class="org.springframework.remoting.jaxrpc.JaxRpcPortProxy
FactoryBean">


<property name="serviceInterface" value="example.RemoteAccountService"/>


<property name="wsdlDocumentUrl"



value="http://localhost:8080/account/services/accountService?WSDL"/>


<property name="namespaceUri"


value="htt
p://localhost:8080/account/services/accountService"/>


<property name="serviceName" value="AccountService"/>


<property name="portName" value="AccountPort"/>

</bean>

Client
-
Side Spring for
Web Applications

Web applications us
e the Spring Web MVC facili
ties, which include a dispatcher servlet, a set of Controller classes,
a set of View classes
, and a resolver facility
. The model classes are the Persistent objects described above under
data persistence (if using Hibernate Annotations, these can be identi
fied by their @Entity annotation).


Like Struts, Spring MVC is a request
-
based framework.


The framework defines
strategy

interfaces for all
responsibilities that have to be handled by a modern request
-
based framework.

The responsibility of each interface

is sufficiently simple and clear that it's easy for Spring MVC users to write their own implementations if they choose
to.


All interfaces are tightly coupled to the
Servlet API

to offer the full power of this API.

This tight coupling to the
Servlet API

is seen by some as a failure on the part of the Spring developers to offer a high
-
level abstraction for
web
-
based applications.

However, this coupling makes sure that the features of the Servlet API remain available to
developers while offering a high ab
straction framework to ease working with said API.

Page
13

of
27


The
DispatcherServlet

class is the
front controller

of the framework and is responsible for delegating control to the
various interfaces during the execution phases of an
HTTP request
.


The most important

interfaces defined by Spring MVC, and their responsibilities, are listed below:



HandlerMapping
:

selecting objects that
handle incoming requests (handlers) based on any attribute or
condition internal or external to those requests



HandlerAda
pter
:

execution of objects that handle incoming requests



Controller
:

comes between Model and View to manage incoming requests

and redirect to proper response.



View
:

responsible for returning a response to the client



ViewResolver
:

selecting a
View

based on a logical name f
or the view (use is not strictly required)



HandlerInterceptor
:

interception of incoming requests comparable but

not equal to
Servlet

filters (use is
optional and not controlled by
DispatcherServlet
).



LocaleResolver
:

resolving and
optionally saving of the
locale

of an individual user



MultipartResolver
:

facilitate working with file uploads by
wrapping incoming requests


Each
strategy

interface above has an important responsibility in the overall framework.

The abstractions offered by
these interfaces are sufficiently powerful to allow for a wide set of variations in their implementations.

Sp
ring MVC
ships with implementations of all these interfaces and together offers a powerful feature set on top of the
Servlet
API
.

However, developers and vendors are free to write other implementations. Spring MVC uses the Java
java.util.Map

interface as
a data
-
oriented abstraction for the
Model

where keys are expected to be string
values.


The ease of testing the implementations of these interfaces is one important advantage of the high level of
abs
traction offered by Spring MVC.
Because Spring MVC uses
the Spring container for configuration and
assembly, web
-
based applications can take full advantage of the Inversion of Control features offered by the
container.


Spring's web MVC framework is, like many other web MVC frameworks, a request
-
driven web MVC
framework,
designed around a servlet that dispatches requests to controllers and offers other functionality facilitating the
development of web applications
. Spring's
DispatcherServlet

however, does more than just that. It is
completely integrated with t
he Spring ApplicationContext

and allows you to use every other feature Spring has.


The notion of a controller is part of the MVC design pattern.

Controllers define application behavior, or at least
provide access to the application behavior.

Controllers

are defined by implementing the Controller interface, and

interpret user input and transform the user input into a sensible model which will be represented to the user by the
view.

Spring has implemented the notion of a controller in a very abstract way
enabling a wide variety of different
kinds of controllers to be created.

Spring contains
AbstractController, AbstractCommandController,
Simple
FormController,

controllers that execute wizard
-
style logic, and more.

Tags in Web applications

You can use the J
STL tags such as c:out followed by an expression, or with JSP 2.0 you can use the expressions
without the c:out tags.


For instance, the following are equivalent:

<c:out value=”$pageCount” />

$pageCount


Where do the expressions get their values? From th
e page context:
k
eep in mind that when using an identifier (like
book
, for example) with the EL, it is the same thing as if you had done
PageContext.findAttribute(identifier)
.

The identifier itself can reside in any of the known JSP
scopes.

This include
s
page
,
request
,
session
, or
application

scope.


If the identifier isn't found in any
scope, then a
null

value is returned.


Page
14

of
27

The most important note about using the JSTL tags is that you can access a bean property (using getter), but you
cannot run methods

that require arguments. As a way around this, you typically
develop

custom tags.

Controllers in Web Applications

Spring's
CommandControllers

are a fundamental part of the Spring MVC package.

Command controllers provide a
way to interact with data object
s and dynamically bind parameters from the
HttpServletRequest

to the data
object specified.

They perform a similar role to Struts' ActionForm, but in Spring, your data objects don't have to
implement a framework
-
specific interface.


This means that you do
n’t spend a great time of time writing Java code that moves information from the request into
Java objects, or vice versa.


To build a simple controller, implement the following method which is in the Controller
interface
:



public

ModelAndView handleReque
st(

HttpServletRequest request,


HttpServletResponse response)

throws

ServletException, IOException;


A typical return looks like:


r
eturn new ModelAndView(“viewName”, “model”, model);


In order to get context into the controller object, you use DI from t
he bean initialization file.


The most interesting
example

is the FormController.
Here is a breakdown of the facilities it supports:




Initial data display method: there is formView which is configured. There is a method in the controller
class called fo
rmBackingObject, which is given the HTTP request. That would gather information to
display on the form, storing it in a model object or other ad
-
hoc display object



There is a validate method in the validation/backing object, that is run as part of a submi
t. That either adds
to a list of errors or doesn’t. This is part of the “P” actions that check the input information. If there are no
errors, then the onSubmit method is run.



onSubmit method: the controller calls this on a submit. The method is similar

to the part of the “P” actions
that write data. The onSubmit method typically calls a redirect to redisplay the modified information. This
is done by
returning

new ModelAndView(new RedirectView(getSuccessView()))
. T
his
allows the success view to be con
figurable.



If, instead, th
ere are errors, then
the form view is shown again, with the error messages called out.


In a typical example, you will override formBackingObject and onSubmit from the SimpleFormController class.
The configuration typically looks

like:


<
bean
id
=
"productEditForm"
class
=
"action.ProductEditFormController"
>


<
property
name
=
"sessionForm"
><
value
>
true
</
value
></
property
>


<
property
name
=
"commandName"
><
value
>
productEdit
</
value
></
property
>


<
property
name
=
"commandClass
"
><
value
>
bus.Product
</
value
></
property
>


<
property
name
=
"validator"
><
ref
bean
=
"productEditValidator"
/></
property
>


<
property
name
=
"formView"
><
value
>
productEdit
</
value
></
property
>


<
property
name
=
"successView"
><
value
>
productList.do
</
val
ue
></
property
>


<
property
name
=
"productManager"
>


<
ref
bean
=
"prodMan"
/>


</
property
>

</
bean
>


What is really interesting is that there is a control
ler

for wizards
. We

have covered that in more detail below.

Page
15

of
27

Themes in Web Applicati
ons

The
theme

support provided by the Spring web MVC framework enables you to further enhance the user experience
by allowing the look and feel of your application to be
themed
.


A theme is basically a collection of static resources
affecting the visual st
yle of the application, typically style sheets and images.


When you want to use themes in your web application you'll have to set up a
org.springframework.ui.context.ThemeSource
.

The
WebApplicationContext

interface
extends
ThemeSource

but delegates its r
esponsibilities to a dedicated implementation.

By default the delegate
will be a
org.springframework.ui.context.support.ResourceBundleThemeSource

that loads
properties files from the root of the classpath. If you want to use a custom
ThemeSource

implemen
tation or if
you need to configure the basename prefix of the
ResourceBundleThemeSource
, you can register a bean in
the application context with the reserved name "themeSource".

The web application context will automatically
detect that bean and start usi
ng it.


When using the
ResourceBundleThemeSource
, a theme is defined in a simple properties file.

The properties
file lists the resources that make up the theme.

Here is an example:


styleSheet=/themes/cool/style.css

background=/themes/cool/img/coolBg.jp
g


The keys of the properties are the names used to refer to the themed elements from view code.


For a JSP this would
typically
be done using the
spring:theme

custom tag, which is very similar to the
spring:message

tag.


The
following

JSP fragment uses th
e theme defined above to customize the look and feel:


<%@
taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<html>


<head>


<link rel="stylesheet" type="text/css"


href="<spring:theme
code="styleSheet"/>"
/>


</head>


<bo
dy background="<spring:theme code="background"/>">


...


</body>

</html>


By
default, the
ResourceBundleThemeSource

uses an empty basename prefix.

As a result the properties files
will be loaded from the root of the classpath, so we'll have to put
our
cool.properties

theme definition in a
directory at the root of the classpath, e.g. in
/WEB
-
INF/classes
.

Note that the
ResourceBundleThemeSource

uses the standard Java resource bundle loading mechanism, allowing for full
internationalization of themes.

The WizardFormController class

This is very useful, and we now use it in several places
. The class name is
AbstractWizardFormController.


Within the controller class, you typically override: handleRequest, formBackingObject and onSubmit. The
configurati
on typically looks like:


<
bean
id
=
"productEditWizard
"
class
=
"action.ProductEditWizard
Controller"
>


<
property
name
=
"sessionForm"
><
value
>
true
</
value
></
property
>


<
property
name
=
"commandName"
><
value
>
productEdit
</
value
></
property
>


<
prope
rty
name
=
"commandClass"
><
value
>
bus.Product
</
value
></
property
>


<
property
name
=
"validator"
><
ref
bean
=
"productEditValidator"
/></
property
>


<
property
name
=
"
pages
"
>
<list>


<
value
>
productEdit
1
</
value
>


<
value
>
productEdit
2
</
value
>

Page
16

of
27



</list>
</
property
>


<
property
name
=
"successView"
><
value
>
productList.do
</
value
></
property
>



<
property
name
=
"productManager"
>


<
ref
bean
=
"prodMan"
/>


</
property
>

</
bean
>


When the controller emits the model that is

be used in view, it will probably want to have page information in it.
This is can be found through API calls on the Controller such as: int getCurrentPage
()

and int getPageCount
()
. You
can also get the view name by calling getViewName(request, command,

pageNumber);

Re
quest Processing L
ifecycle of Spring Web A
pplications

These are the steps carried out by the default Dispatcher Servlet, URLHandlerMapping, and ViewResolver objects.


1. Browser sends request, received by DispatcherServlet


DispatcherServl
et is set in war/WEB
-
INF/web.xml.


<servlet>


<servlet
-
name>springapp</servlet
-
name>


<servlet
-
class>org.springframework.web.servlet.DispatcherServlet</servlet
-
class>


<load
-
on
-
startup>1</load
-
on
-
startup>

</servlet>


<servlet
-
mapping>


<servlet
-
name>spring
app</servlet
-
name>


<url
-
pattern>*.htm</url
-
pattern>

</servlet
-
mapping>


All the requests having the name of *.htm will be handled by springapp, which is a DispatcherServlet.


2. Determine which controller to use


<bean id="urlMapping"



class="or
g.springframework.web.servlet.handler.SimpleUrlHandlerMapping">


<property name="mappings">


<props>


<prop key="/hello.htm">springappController</prop>


<prop key="/priceincrease.htm">priceIncreaseForm</prop>


</props>


</property>

</bean>


This spec
ification in war/
WEB
-
INF/springapp
-
servlet.xml specifies a

mapping

of

/hello.htm and /priceincrease.htm
to two specific controller objects.


3. Dispatcher server requests Controller, controller returns ModelAndView object


In src/web/SpringappController.ja
va


public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse
response)

throws ServletException, IOException {


String now = (new java.util.Date()).toString();

logger.info("returning hello view with " + now);


Map myModel = new Hash
Map();

Page
17

of
27

myModel.put("now", now);

myModel.put("products", getProductManager().getProducts());


return new ModelAndView("hello", "model", myModel);

}


The controller returns a ModelAndView object whose viewName is "hello", modelName is "model" and model
objec
t is a Map object named as myModel.


4. If ModelAndView contains logical name for a View, DispatcherServlet queries ViewResolver for the View
object that will render the response


<bean id="viewResolver"


class="org.springframework.web.servlet.view.I
nternalResourceViewResolver">


<property name="viewClass">


<value>org.springframework.web.servlet.view.JstlView</value>


</property>


<property name="prefix"><value>/WEB
-
INF/jsp/</value></property>


<property name="suffix"><value>.jsp</value></prop
erty>

</bean>


This specification will add prefix and suffix to the viewName of ModelAndView object, in this example, hello will
be fixed as /WEB
-
INF/jsp/hello.jsp . The view class is JstlView, which is a wrapper for a JSP. The contents of the
model are
added to the pageContext object, at the page scope.


5. DispatcherServlet requests the View Object. /WEB
-
INF/jsp/hello.jsp will be shown on browser.


This is a function of the view facilities. In general, a model object is created in the controller’s busi
ness logic, and
all of the parts of the output jsp file will be driven from that object. In fact, the model object must be populated so
comprehensively that only getter methods will be needed to fetch and format the data, since JSTL expressions
cannot run

methods other than getter methods.


With appropriate reconfiguration, the viewing technologies for Java Server faces and others can be integrated.

The Spring T
ag Library

One of the view technologies you can use with the Spring Framework is Java Server Pag
es (JSPs).


To help you
implement views using Java Server Pages the Spring Framework provides you with some tags for evaluating errors,
setting themes and outputting internationalized messages.


Please note that the various tags generated by this form tag
library are compliant with the
XHTML
-
1.0
-
Strict
specification

and attendant
DTD
.


The Spring tag library is described in the reference guide, and includes tags such as:



b
ind
: provides BindStatus object for the given bind path



escapeBody
: escapes its encl
osed body content, applying HTML escaping and/or JavaScript escaping



hasBindErrors
: provides Errors instance in case of bind errors



message
: retrieves the message with the given code, or text if code isn't resolvable



n
estedPath
: sets a nested path to be

used by the bind tag's path.



theme:

retrieves the theme message with the given code, or text if code isn't resolvable



transform:


provides transformation of variables to Strings, using an appropriate custom PropertyEditor
from BindTag


In general, thes
e tags are not about the visual layout of the page, or replacements for the HTML tags, but are about
linking the page behavior to the context managed by Spring, typically the error messages from validation. For page
layout, you might use other presentatio
n tag sets.

Page
18

of
27

Test Cases and the Mock Objects Library in Spring

The Spring Framework uses EasyMock extensively in its test suite
.
The library spring
-
mock.jar contains the
following packages


The
Spring Framework provides first class support for integration
testing in the form of the classes that are packaged
in the
spring
-
mock.jar

library.

Please note that

these test classes are JUnit
-
specific.


This library in turn relies upon easymock.jar


This includes mock
-
httprequest, mock
-
httpresponse, mock
-
servlet, e
tc.

Using Spring through the Spring IDE

This is not a full IDE, but is a plug
-
in for Eclipse that provides a tool for viewing, writing, and verifying the
application configuration XML file.


For instance, the editor will allow you to create new beans using

a template
-
based approach that is like creating a
new Java class. The editor will provide a visual overview of the structure of your configuration file.

Here is an
example:


Most importantly, the editor will carry out verification that all classes refer
red to in your file exist in the Java
project, and that all names are unique, and that all references are to valid names.


The installation steps are

(these are for Eclipse 3.3, the menus and dialogs are different for Eclipse 3.4)
:



Startup Eclipse



Select H
elp
-
>Software Updates
-
>Find and Install



Select “Search for new features to install”, click Next



Click “New Remote Site”



Enter “Spring IDE updatesite” for the Name



Enter
http://springide.org/updatesite

for th
e URL



Click OK



Check the box marked “Sping IDE updatesite”, and click Finish



Check the box for the Spring IDE. Ignore the integrations unless you need them, as they can stop the
install from working



Accept terms, click Next, click Finish, and click Instal
l All



Restart the workbench when asked.

U
sing the IDE

Create a Spring project, or add the Spring aspect to the project by right
-
clicking on the project and choose Spring
Tools > Add Spring Project Nature.


Then create a Bean configuration file, or have the

project manage an existing one by right
-
clicking on the project,
choosing Properties, then Spring properties, then Spring Bean support, and adding the name of the bean
configuration file to the list.


The result is that

your bean configuration file will b
e verified upon Save by the IDE.


You can now show the bean configuration for the projects with Spring aspect in the Spring Explorer.

In the
Explorer, you can open a bean source
file, or view the graph for a bean
, as shown below:


Page
19

of
27



The graph always star
ts in the upper left with the target bean, and then follows references downwards and to the
right. Do not try to open the bean definition file itself in the Beans Graph, or Eclipse will go into an infinite loop

Using Spring through MyEclipse

A good place
to start is the MyEclipse tools. Starting with MyEclipse 5.5.1, they incorporated Spring 2.0.5, and in
MyEclipse 6.0.1, they incorporated Spring 2.0.7.


In MyEclipse 5.5.1, the usage guide has been completely re
-
written and is quite complete. There is a
Spring
-
Hibernate tutorial. Plus, the pages of the Spring Framework guide are useful. They are based on the contents of the
Spring web site.


We created a J2EE Web application, and then added Spring capabilities.


Also, we noticed that the set of Spring
l
ibraries linked in by MyEclipse are far from the minimal set. But we were able to pare it down quickly.

Spring Examples

SP1: Example using Spring Container, plus Hibernate for Persistence

This shows how to use the container, and have the beans which are
defined include all of the elements of the
Hibernate persistence configuration, as well as a set of Module definition beans. At the moment, these are not used
for anything except to show that they can be queried from the container (by class), and iterated
over to form a list or
menu. There is no web application in this program.


All of the database access is done through Hibernate, and Hibernate annotations are used in each of mapping
configuration files. The database configuration is pooled through C3PO,

and the bean definition configuration data
is read from a properties file, such that, for instance, the database connection string information can be altered
without having to make a change in the primary bean definition file.


The data model has two clas
ses, with a one
-
to
-
many relationship between then, and cascading of saves.

SP2: Example based on the Thomas Risberg tutorial

This is a web application that shows how to set up the controller, view, and data handling facilities, The example
displays and e
dits a list of products.

Page
20

of
27


We are using the DispatcherServlet which is invoking operations in an application context.


There is a Product class, a ProductManager class, and a ProductDAO, which implements a IProductDAO interface.
The database interaction is

directly through JDBC.


Next, we added JDBC support into the example, by using MappingSqlQuery and SqlUpdate objects. We also set up
ProductEdit, so that it can also create a new Product, thus placing what would have been the set of (Edit, EditP,
New, Ne
wP) actions into one Controller.


There are three action
-
like classes, which are subclasses of Controller. Two are subclasses of FormController. For
the priceIncreaseFormController, there is a model class called PriceIncrease, which holds the working sto
rage for
the priceIncreaseForm. For the productEditFormController, the model class is a Product object itself.


The ProductEdit facility using a multi
-
page wizard.


There are validation classes for PriceIncrease and for ProductEdit. These include checkin
g for required values,
numeric entries, numbers in a range, etc., and display error messages.


This example also shows testing facilities. There is a MockProductDAO, a configuration file which wires this into
place instead of the real ProductDAO, and a se
t of JUnit test cases which use the revised configuration. The tests
coverage includes the DAO and the ProductManager.

SP3: Complex E
xample

This example was the most complex development at the end of 2007. It includes a subset of the Incra data model,
a
nd has a module reader that uses Apache Digester. There are modules for UserManager, ContentManagement, and
PresentationManagement, plus updated versions of the Trading and Forum modules developed in OGame. There is
an example of an Ajax
-
based update to
fetch configuration data for a display.


Several parts of this example are being stripped down as of December 2008, since we are starting to use Wicket for
the presentation now, and also because the persistent classes (e.g., User) don’t yet use Hibernate A
nnotations.

Open Questions and Things to Try

Spring transactions need more detail.


Spring web services need more detail.

Appendix
A
:

Organization of book “Spring i
n Action”


Part 1: Springing into Action

Chapter
1
: Springing into Action


This chapter d
escribes some of the important concepts in spring, such as how components are organized, the role of
Dependency Injection, the use of Aspect
-
Oriented
-
Programming, and how these can help in both development and
testing of a complex application. It defines
bean as being synonymous with component, and how the goal of Spring
is promote loose coupling between such beans for architectural flexibility.


The chapter contains a Spring

jump start


application, which is a non
-
web application that uses the container,

creates a bean and runs a method on it.


Then it contains a set of examples about the use of AOP.

Page
21

of
27

Chapter 2: Basic bean wiring

Containing your beans

Creating beans

Injecting into bean properties

Autowiring

Controlling bean creation

Chapter 3: Adva
nced bean wiring

Declaring parent and child beans

Applying method injection

Injecting non
-
Spring beans

Registering custom property editors

Working with Spring’s special beans

Scripting beans

Chapter 4: Advising beans

Introducing AOP

Creating clas
sic Spring aspects

Autoproxying

Declaring pure
-
POJO aspects

Injecting AspectJ aspects

Part 2: Enterprise Spring

Chapter 5: Hitting the database

Learning Spring’s data access philosophy

Configuring a data source

Using JDBC with Spring

Integrating

Hibernate with Spring

Spring and the Java Persistence API

Spring and iBATIS

Caching

Chapter 6: Managing transactions

Understanding transactions

Choosing a transaction manager

Programming transactions in Spring

Declaring transactions

Chapter 7:
Securing Spring

Introducing Spring Security

Authenticating users

Controlling access

Securing web applications

View
-
layer security

Securing method invocations

Chapter 8: Spring and POJO
-
based remote services

An overview of Spring remoting

Working
with RMI

Remoting with Hessian and Burlap

Page
22

of
27

Using Spring’s HttpInvoker

Spring and web services

Chapter 9: Building contract
-
first web services in Spring

Introducing Spring
-
WS

Defining the contract (first!)

Handling messages with service endpoints

Wi
ring it all together

Consuming Spring
-
WS web services

Chapter 10: Spring messaging

A brief introduction to JMS

Using JMS with Spring

Creating message
-
driven POJOs

Using message
-
based RPC

Chapter 11: Spring and Enterprise JavaBeans

Wiring EJBs in
Spring

Developing Spring
-
enabled EJBs (EJB 2.x)

Spring and EJB3

Chapter 12: Accessing enterprise services

Wiring objects from JNDI

Sending email

Scheduling tasks

Managing Spring beans with JMX

Part 3: Client
-
side Spring

Chapter 13: Handling web

requests

Getting started with Spring MVC

Mapping requests to controllers

Handling requests with controllers

Handling exceptions

Chapter 14: Rendering web views

Resolving views

Using JSP templates

Laying out pages with Tiles

Working with JSP alte
rnatives

Generating non
-
HTML output

Chapter 15: Using Spring Web Flow

Getting started with Spring Web Flow

Laying the flow groundwork

Advanced web flow techniques

Integrating Spring Web Flow with other frameworks

Chapter 16: Integrating with other

web frameworks

Using Spring with Struts

Page
23

of
27

Working Spring into WebWork 2/Struts 2

Integrating Spring with Tapestry

Putting a face on Spring with JSF

Ajax
-
enabling applications in Spring with DWR


There are appendices on setting up Spring, and on testin
g with and without Spring


There are several additional chapters on the web, including building portlet applications, Spring XML configuration
reference, Spring JSP tag library reference, Spring Web Flow definition reference, and customizing Spring
configu
ration.

Appendix B
:


12 Best Practices f
or Spring XML Configurations

Spring

is a powerful Java application framework, used in a wide range of Java applications. It provides enterprise
services to Plain Old Java Objects (POJOs). Spring uses dependency inj
ection to achieve simplification and
increase testability. Spring beans, dependencies, and the services needed by beans are specified in configuration
files, which are typically in an XML format. The XML configuration files, however, are verbose and unwie
ldy.
They can become hard to read and manage when you are working on a large project where many Spring beans are
defined.


Here are 12 best practices for Spring XML configurations. Some of them are more
necessary

practices than best
practices. Note that

other factors, such as domain model design, can impact the XML
configuration, but this
discussion

focuses on the XML configuration's readability and manageability.

1.

Avoid using autowiring

Spring can autowire dependencies through introspection of the be
an classes so that you do not have to explicitly
specify the bean properties or constructor arguments.

Bean properties can be autowired either by property names or
matching types.

Constructor arguments can be autowired by matching types.


You can even sp
ecify the autodetect
autowiring

mode, which lets Spring choose an appropriate mechanism.

As an example, consider the
following:



<bean id="orderService"


class="com.lizjason.spring.OrderService"


autowire="byName"/>


The property names o
f the
OrderService

class are used to match a bean instance in the container. Autowiring
can potentially save some typing and reduce clutter. However, you should not use it in real
-
world projects because it
sacrifices the explicitness and maintainability of

the configurations. Many tutorials and presentations tout autowiring
as a cool feature in Spring without mentioning this implication. In my opinion, like object
-
pooling in Spring, it is
more a marketing feature. It seems like a good idea to make the XML c
onfiguration file smaller, but this will
actually increase the complexity down the road, especially when you are working on a large project where many
beans are defined. Spring allows you mix autowiring and explicit wiring, but the inconsistency will make
the XML
configurations even more confusing.

2.

Use naming conventions

This is the same philosophy as for Java code.

Using clear, descriptive, and consistent name conventions across the
project is very helpful for developers to understand the XML configur
ations.

For bean ID, for example, you can
follow the Java class field name convention.


The bean ID for an instance of
OrderServiceDAO

would be
orderServiceDAO
.

For large projects, you can add the package name as the prefix of the bean ID.

3.

Use shortc
ut forms

The shortcut form is less verbose, since it moves property values and references from child elements into attributes.
For example, the following:

Page
24

of
27



<bean id="orderService"


class="com.lizjason.spring.OrderService">


<property name
="companyName">


<value>lizjason</value>


</property>


<constructor
-
arg>


<ref bean="orderDAO">


</constructor
-
arg>


</bean>


can be rewritten in the shortcut form as:



<bean id="orderService"


class
="com.lizjason.spring.OrderService">


<property name="companyName"


value="lizjason"/>


<constructor
-
arg ref="orderDAO"/>


</bean>


The shortcut form has been available since version 1.2.

Note that there is no shortcut form for

<ref
local="...">
.

The shortcut form not only saves you some typing, but also makes the XML configuration files
less cluttered.

It can noticeably improve readability when many beans are defined in a configuration file.

4.

Prefer type over index for con
structor argument matching

Spring allows you to use a zero
-
based index to solve the ambiguity problem when a constructor has more than one
arguments of the same type, or value tags are used.

For example, instead of:



<bean id="billingService"


class="com.lizjason.spring.BillingService">


<constructor
-
arg index="0" value="lizjason"/>


<constructor
-
arg index="1" value="100"/>


</bean>


It is better to use the
type

attribute like this:



<bean id="billingService"


class="
com.lizjason.spring.BillingService">


<constructor
-
arg type="java.lang.String"


value="lizjason"/>


<constructor
-
arg type="int" value="100"/>


</bean>


Using
index

is somewhat less verbose, but it is more error
-
prone and hard to

read compared to using the
type

attribute.

You should only use
index

when there is an ambiguity problem in the constructor arguments.

5.

Reuse bean definitions, if possible

Spring offers an inheritance
-
like mechanism to reduce the duplication of configu
ration information and make the
XML configuration simpler.

A child bean definition can inherit configuration information from its parent bean,
which essentially serves as a template for the child beans.


This is a must
-
use feature for large projects.

All

you
need to do is to specify
abstract=true

for the parent bean, and the
parent

reference in the child bean. For
example:


Page
25

of
27


<bean id="abstractService" abstract="true"


class="com.lizjason.spring.AbstractService">


<property name="companyNa
me"


value="lizjason"/>


</bean>



<bean id="shippingService"


parent="abstractService"


class="com.lizjason.spring.ShippingService">


<property name="shippedBy" value="lizjason"/>


</bean>


The
shippingService

bean

inherits the value
lizjason

for the
companyName

property from the
abstractService

bean. Note that if you do not specify a class or factory method for a bean definition, the
bean is implicitly abstract.

6.

Prefer assembling bean definitions through
Appli
cationContext

over
imports

Like imports in
Ant

scripts, Spring
import

elements are useful for assembling modularized bean definitions. For
example:



<beans>


<import resource="billingServices.xml"/>


<import resource="shippingServices.xml
"/>


<bean id="orderService"


class="com.lizjason.spring.OrderService"/>


<beans>


However, instead of pre
-
assembling them in the XML configurations using imports, it is more flexible to configure
them through the
ApplicationContext
.

Using
ApplicationContext

also makes the XML
configurations easy to manage.

You can pass an array of bean definitions to the
ApplicationContext

constructor as follows:



String[] serviceResources =


{"orderServices.xml",


"billingServices.
xml",


"shippingServices.xml"};


ApplicationContext orderServiceContext = new


ClassPathXmlApplicationContext(serviceResources);

7.

Use
id
s as bean identifiers

You can specify either an
id

or
name

as the bean identifier.

Using
id
s will n
ot increase readability, but it can
leverage the XML parser to validate the bean references.

If
id
s cannot be used due to XML IDREF constraints,
you can use
name
s as the bean identifiers.

The issue with XML IDREF constraints is that the
id

must begin wit
h
a letter (or one of a few punctuation characters defined in the
XML specification
) followed by letters, digits,
hyphens, underscores, colons, or full stops.

In reality, it is very rare to run into the XML ID
REF constraint problem.

8.

Use dependency
-
check at the development phase

You can set the
dependency
-
check

attribute on a bean definition to a value other than the default
none
,
such as
simple
,
objects
, or
all
, so that the container can do the dependency v
alidation for you.

It is useful
when all of the properties (or certain categories of properties) of a bean must be set explicitly, or via autowiring.



<bean id="orderService"

Page
26

of
27


class="com.lizjason.spring.OrderService"


dependency
-
check="o
bjects">


<property name="companyName"


value="lizjason"/>


<constructor
-
arg ref="orderDAO"/>


</bean>


In this example, the container will ensure that properties that are not primitives or collections are set for the
orderServi
ce

bean.


It is possible to enable the default dependency check for all of the beans, but this feature
is rarely used because there can be beans with properties that don't need to be set.

9.

Add a header comment to each configuration file

It is preferred
to use descriptive
id
s and names instead of inline comments in the XML configuration files.

In
addition, it is helpful to add a configuration file header, which summarizes the beans defined in the file.
Alternatively, you can add descriptions to the
descr
iption

element. For example:



<beans>


<description>


This file defines billing service


related beans and it depends on


baseServices.xml,which provides


service bean templates...


</descriptio
n>


...


</beans>


One advantage of using the
description

element is that it is easy to for tools to pick up the description from
this element.

10.

Communicate with team members for changes

When you are refactoring Java source code, you need to
make sure to update the configuration files accordingly and
notify team members.

The XML configurations are still code, and they are critical parts of the application, but they
are hard to read and maintain.

Most of the time, you need to read both the XM
L configurations and Java source
code to figure out what is going on.

11.

Prefer setter injection over constructor injection

Spring provides three types of dependency injection: constructor injection, setter injection, and method injection.
Typically we o
nly use the first two types.



<bean id="orderService"


class="com.lizjason.spring.OrderService">


<constructor
-
arg ref="orderDAO"/>


</bean>



<bean id="billingService"


class="com.lizjason.spring.BillingService">


<pr
operty name="billingDAO"


ref="billingDAO">


</bean>


In this example, the
orderService

bean uses constructor injection, while the
BillingService

bean uses
setter injection. Constructor injection can ensure that a bean cannot be constructed
in an invalid state, but setter
injection is more flexible and manageable, especially when the class has multiple properties and some of them are
optional.

Page
27

of
27

12.

Do not abuse dependency injection

As the last point, Spring
ApplicationContext

can create Java
objects for you, but not all Java objects
should be created through dependency injection.

As an example, domain objects should not be created through
ApplicationContext
.

Spring is an excellent framework, but, as far as the readability and manageability a
re
concerned, the XML
-
based configuration can become an issue when many beans are defined.

Overuse of
dependency injection will make the XML configuration more complicated and bloated.


Remember, with powerful
IDEs, such as
Eclipse

and
IntelliJ
, Java code is much easier to read, maintain, and manage than XML files!

Conclusion

XML is the prevailing format for Spring configurations. XML
-
based configuration can become verb
ose and
unwieldy when many beans are defined. Spring provides a rich set of configuration options.

Appropriately using
some of the options can make the XML configurations less cluttered, but other options, like autowiring, may reduce
readability and maint
ainability. Following good pra
ctices discussed above
may help you to create clean and
readable XML configuration files!