Notes on Spring Framework, version 3

grapedraughtSoftware and s/w Development

Dec 2, 2013 (3 years and 10 months ago)

85 views

Page
1

of
25

Notes on
Spring

Framework
, version 3

Created 08/2
1/10

Updated 09/09/10
,
Updated 10/01/10
, Updated 01/24/11
, Updated 02/03/11
,
Updated 02/28/11
,
Updated 03/11/11
,
Updated 03/17/11
,
Updat
ed 04/05
/11
, U
pdated 04/13/11
, U
pdated 04/25
/11
,
Updated 05/15
/11
, Upda
ted 06/02
/11

Updated 06/11/11
, U
pdated 07/29/11
, Updated 08/10/11
, Updated 09/12/11
,
Updated 09/28/11
,
Updated 11/18/11

Updated 11/22/11
, Updated 12/31/11
, Updated 03/12/12, Updated 09/22/12,

Updated 05/02/13, Updated 06/14
/13


These are
development notes

regarding Spring 3:

intended mostly to deal with web
applications and the Spring
MVC library

in particular. Many other Spring concepts are skipped

unless they
are key in web apps

or distributed
apps
.

Also there is discussion about Eclipse WTP and other
tools to support Tomcat/Hibernate/Spring applications.

Introduction

The Spring Framework is one of the most commonly used web application frameworks. It is considered to be an
improvement over Struts and EJB 2, particularly as it also 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 layers and their component
s.


Spring consists
of
a framework that handles initialization, configuration, web
-
servlet action dispatching, validation,
a tag library, and database access. Spring has been under development and use since about 2002.


There are
four

primary versions of
Spring: the 3
.
1.x/3.2.x series is the newest
, released in late 2011,

and 3.2.3

is the
current version. The 3.0.x series was f
irst released in 2009, and 3.0.7

was the final version, released in early 2012.
The Spring 3.0.x versions introduce extensive su
pport for using Annotations to configure a web applicatio
n

(this
completely changes the role of Controller classes, for example)
. The Spring 2.5.x series was an interim step toward
an Annotation
-
driven system.
The 2.0.x series was released in 2006 throug
h 2008, with the final 2.0.8 release in
October 2008.



Page
2

of
25


Sprin
g is composed of the above six

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 r
eader. The next most important
is Spring Context, which defines the runtime context for an application, and supporting tools such as email, JNDI,
etc. Other pieces supply the persistence facilities, and the web tools including parsing HttpRequests, conne
ction to
presentation 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 ea
sy extension.


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 pro
vide services 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. S
pring emerged 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 bec
ause it doesn’t require full EJB containers
such as JBoss or WebLogic, instead running on Tomcat or even adding value to non
-
web applications.

Resources

The best reference document is the online manual, which is a
n

804
-
page PDF, located at

http://static.springsource.org/spring/docs/3.0.x/spring
-
framework
-
reference/pdf/spring
-
framework
-
reference.pdf


“Spring in Practice”

by Wille W
heeler and Joshua White. Manning Press, May 2013, 560 pages. List price $44.99,
Amazon price $31.95. Not yet rated on Amazon.com. Looks very useful, contains complete examples.


“Spring in Action, Third Edition” by Craig Walls. Manning Press,
June

201
1, 424 pages. List price $49.99
,
Am
azon price $36.22, used from $33.22.

Rated 3.5 stars on Amazon.com
. This

is a well
-
written overview of
Spring, but doesn’t attempt to dig into the details. The most useful chapters were the ones on MVC and on
WebServi
ces, but these were only an intro compared to some of the notes we have compiled here based on trying
examples and reviewing materials from SpringSource presentations.


“Spring Dynamic Modules in Action” by
Arnaud Cogoluegnes

and
Thierry Templier
. Manning

Press, September
2010, 548 pages. Presents the fundamental concepts of OSGi
-
based apps and maps them to the familiar ideas of the
Spring framework. Then, it teaches the techniques and concepts required to develop stable, flexible enterprise apps


“S
pring Enterprise Recipes” by Gary Mak, Danial Rubino, and Josh Long. APress, September 2010, 1104

pages.
List price $59.99, Amazon price $33.49, used from $22.40. Rated 4.5 stars on Amazon.com. This book is based on
Spring 3 (there was an earlier one for Spring 2.5). Considered to be a very practical set of solutions and examples.


“Spring Securit
y 3” by
Peter Mularien
.

Packt Pubishing, 2010. Rated 3 stars on Amazon.com.


“Pro Spring 2.5” by
Jan
Machacek
, Jesscia Ditt, and

others
.
APress, August 2008
, 806 pages.

Lis
t price $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 that 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, A
mazon 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 app
roaches, web services, the presentation facilities, etc. The examples are
quite clear.

However, large parts are out of date, and the XML configuration
-
based approach is no longer strongly
used. Manning
is now giving away the download

of this edition to
people who buy the third edition.

Page
3

of
25

Organization of the

Spring in Action


Book

(third edition)

Part I: Core Spring




1.

Springing into action



2.

Wiring beans



3.

Minimizing Spring configura
tion XML



4.

Aspect
-
oriented Spring



Part 2 Spring application

essentials




5.

Hitting the Database



6.

Managing transactions



7.

Building web

applications with Spring MVC



8.

Spring Web

Flow



9.

Securing Spring


Part 3 Integrating Spring


10.

Working with remote services

11.

Giving Spring some REST

12.

Messagin
g in Spring

13.

M
anaging Spring beans with JMX

14.

Odds and ends

Core Spring

Beans and Configuration Contexts

Basic concepts of beans haven’t changed, but the ability to configure
them
has.

Dependency injection is introduced
here.

XML Configuration

This c
hapter of the book is quite complete, and discusses the use of the bean tag, the p namespace, the reference
system, and the ability to set up bean properties which are scalar, collections, etc. There is also a discussion about
the bean scopes, and the fac
tory beans.


The chapter ends with a discussion of the
Spring Expression Language
, which is new 3.0 and provides a way to
describe dynamic expressions as value to bean configuration. However, we are not sure when would we use this.

Minimizing Spring Confi
guration using XML/Autow
ir
ing

Autowiring is based on qualified searches of the bean pool.

Aspect
-
Oriented Spring

Aspects help to modularize cross
-
cutting concerns. In short, a crosscutting concern can be described as any
functionality that affects multiple

points of an application. Security, for example, is a cross
-
cutting concern, in that
many methods in an application can have security rules applied to them.


Spring AOP is a subset of full AOP, such as that provided by AspectJ.


Important definitions:

Adv
ice defines both the
what
and the
when
of an aspect. In addition to describing the job that an aspect will
perform, advice addresses the question of when to perform the job. Should it be applied before a method is
invoked? After the method is invoked?
Both before and after method invocation? Or should it only be applied if a
method throws an exception? Spring aspects can work with five kinds of advice:


Before

t
he advice functionality takes place before the advised method is invoked.

Page
4

of
25


After

t
he advice functionality takes place after the advised method completes, regardless of the outcome.

After
-
returning

t
he advice functionality takes place after the

advised method successfully completes.


After
-
throwing

t
he advice functionality takes place after the advised method throws an exception.


Around

t
he advice wraps the advised method, providing some functionality before and after the advised method
is
invoked.


A
join point
is a point in the execution of the application where an aspect can be plugged in. This point could be a
method being called, an exception being thrown, or even a field being modified. These are the points where your
aspect’s code can

be inserted into the normal flow of your application to add new behavior.


Pointcuts
help nar
row down the join points advised by an aspect.


If advice defines the
what
and
when
of aspects,
then pointcuts define the
where
.


An
aspect
is the merger of advic
e and pointcuts


Weaving
is the process of applying aspects to a target object to create a new proxied object. The aspects are woven
into the target object at the specified join points. The weaving can take place at several points in the target object’s
li
fetime:


Compile time

Aspects are woven in when the target class is compiled. This requires a special compiler.
AspectJ’s weaving compiler weaves aspects this way.


Classload time

Aspects are woven in when the target class is loaded into the
JVM
. This requires
a special
ClassLoader
that enhances that target class’s byte
-

code before the class is introduced into the application.
AspectJ 5’s
load
-
time weaving (
LTW
)
support weaves aspects in this way.


Runtime

Aspects are woven in sometime during the execution of

t
he applica
tion.


Typically, an
AOP
container
will dynamically generate a proxy object that will delegate to the target object while weaving in the aspects.

This is
how Spring
AOP
aspects are woven.


In 2005, the AspectWerkz project merged with AspectJ,
marking the last significant activity in the
AOP
world and
leaving us with three dominant
AOP
frameworks:


AspectJ (
http://eclipse.org/aspectj
)


JBoss
AOP
(
http://www.jboss.org/jbossaop
)


Spring
AOP
(
http://www.springfr
amework.org
)


Since this is a Spring
document
, we’ll focus on Spring
AOP
.

Even so, there’s a lot of synergy between the Spring
and AspectJ projects, and the
AOP
support in Spring borrows a lot from the AspectJ project.

Spring’s support for
AOP
comes in

four flavors:


Classic Spring proxy
-
based
AOP


@AspectJ annotation
-
driven aspects


Pure
-
POJO
aspects


Injected AspectJ aspects (available in all versions of Spring)


The first three items are all variations on Spring’s proxy
-
based
AOP
. Consequently, Spring’s
AOP

support is limited
to method interception.

If your
AOP
needs exceed simple method interception (constructor or property interception,
for example), you’ll want to consider implementing aspects in AspectJ, perhaps taking advantage of Spring
DI
to
inject S
pring beans into AspectJ aspects.


The most important thing to know about AspectJ pointcuts as they pertain to Spring
AOP
is that Spring only supports
a subset of the pointcut designators available in AspectJ.

Recall that Spring
AOP
is proxy
-
based and cer
tain pointcut
expressions aren’t relevant to proxy
-
based
AOP
.


The table below lists the AspectJ pointcut designators that are
supported in Spring
AOP
.


Page
5

of
25



The
AOP
configuration elements are summarized in table 4.2.




Here is an example:

Page
6

of
25



So far, our a
spects have been simple, taking no parameters.

The only exception is that the
watchPerformance()
method that we wrote for the around advice example took a
ProceedingJoinPoint
as a parameter.

Other than
that, the advice we’ve writ
-

ten hasn’t bothered to
look at any parameters passed to the advised methods.

That’s
been okay, though, because the
perform()
method that we were advising didn’t take any parameters.
Nevertheless, there are times when it may be useful for advice to not only wrap a method, but al
so inspect the values
of the parameters passed to that method


Section 4.4 of the book describes how to place this information in to annotations on the Java classes.

Focus on Web Applications

The Spring MVC support has improved greatly over the last two re
leases. Now it is mostly annotation
-
driven, and
much easier to set up. SpringSource has taken many concepts from Rails and Grails.


http://vi
ralpatel.net/blogs/2010/06/tutorial
-
spring
-
3
-
mvc
-
introduction
-
spring
-
mvc
-
framework.html


http://www.infoq.com/presentations/Mastering
-
Spring
-
MVC
-
3

Database Connections and Template
s

Spring supplies several level
s

of classes to aid in managing database
-
base persistence.


No matter what technology we’re using, certain data access steps are required.

For example, we always need to
obtain a connection to our data store and clean up res
ources when we’re done.

These are the fixed steps in a data
access process.

But each data access method we write is slightly different.


We query for different objects and
update the data in different ways.

These are the variable steps in the data acces
s process.


Spring separates the fixed and variable parts of the da
ta access process into two dis
tinct classes:
templates
and
callbacks
.

Templates manage the fixed part of the process, whereas your custom data access code is handled in the
callbacks.


F
igure 5.2 shows the responsibilities of both of these classes.

As you can see in figure 5.2, Spring’s template classes
handle the fixed parts of data access

controlling transactions, managing resources, and handling exceptions.


Meanwhile, the specifics o
f data access as they pertain to your application

creating statements, binding parameters,
and marshaling result sets

are handled in the call
-

back implementation.

In practice, this makes for


Page
7

of
25

For example, if your application
DAO
subclasses
JdbcDaoSupport
, then you only need to call
getJdbcTemplate()
to get a
JdbcTemplate
to work with.

Plus, if you need access to the underlying
persistence platform, each of the
DAO
support classes provides access to whatever class it use
s to communicate with
the data
base.


For instance, the
JdbcDaoSupport
class contains a
getConnection()
method for dealing
directly with the
JDBC
connection.

Just as Spring provides several data access templat
e implementations, it also
pro
vides several
DAO
support classes

one for each templ
ate.

DataSources

DataSources are your way of managing connections. You define them as beans in the application configuration file.


Pooling is provided for connections.

JDBC

We will start with JDBC level persistence.


For this, use SimpleJdbcTemplate


The
n there are classes that are superclasses for your DAOs

Higher
-
level T
ools (ORM)

Several frameworks are available that provide these services.

The general name for these services is
object
-
relational mapping (
ORM
)
. Using an
ORM
tool for your persistence
layer can save you literally thousands of lines of
code and hours of development time. This lets you switch your focus from writing error
-
prone
SQL
code to
addressing your application requirements. Spring provides support for several persistence framewor
ks, including
Hibernate, i
BATIS
, Java Data Objects (
JDO
), and the Java Persistence
API
(
JPA
).


As with Spring’s
JDBC
support, Spring's support for
ORM
frameworks provides integration points to the frameworks
as well as some additional services:


Integrat
ed support for Spring declarative transactions


Transparent exception handling


Thread
-
safe, lightweight template classes


DAO
support classes


Resource management


Next, we move on to using Hibernate
. In this case, we focus on the HibernateSessio
n, and the template is mostly
invisible.


Finally, we cover using Java
Persistence (JPA)


Final thoughts: How did we end up with services as DAO? Did I start that? What was the example that I worked
from?

Using HibernateTemplate

One of the responsibiliti
es of
HibernateTemplate
is to manage Hibernate
Session
s.

This involves opening
and closing sessions as well as ensuring one session per transaction.

Without
HibernateTemplate
, you’d have
no choice but to clutter your
DAO
s with boilerplate session managem
ent code.

The downside of
HibernateTemplate
is that it’s somewhat intrusive.

When we use Spring’s
HibernateTemplate
in a
DAO
(whether directly or through
HibernateDaoSupport
), the
DAO
class is coupled to the Spring
API
.

Although this
may not be of much
concern to some developers, others may find Spring’s intrusion into their
DAO
code
undesirable.


Each HibernateTemplate manages one datasource. The methods include:



saveOrUpdate
(<object>)

Page
8

of
25



find(<queryString>,
<object definining parameter>
)

o

find("from " +
VEHICLE + " where state = ? and plateNumber = ?", new Object[]
{state, plateNumber});



load(<class>, id);


In Grails Datasources plugin, you can use the convenience method

DatasourcesUtils.newHibernateTemplate(String dsName)

to create a
HibernateTemplate

co
nfigured with the
SessionFactory

for the named datasource.


/**



* Create a HibernateTemplate using the specified data source.



*
@param

dsName the ds name
-

if null return the default data source



*
@return

the template



*/


static

HibernateTemplate

newHibernateTemplate
(String dsName =
null
) {



String name = dsName ?
"sessionFactory_$dsName"

:
'sessionFactory'



return

new

HibernateTemplate(
applicationContext
.getBean(name))


}

Transactions

Spring, like
EJB
, provides support for both programmatic and

declarative transaction management. But Spring’s
transaction management capabilities exceed those of
EJB
. Spring’s support for programmatic transaction
management differs greatly from that of
EJB
. Unlike
EJB
, which is coupled with a Java Transaction
API
(
JTA
)
implemen
tation, Spring employs a callback mechanism that abstracts away the a
ctual transac
tion implementation
from the transactional code. In fact, Spring’s transaction management support doesn’t even require a
JTA
implementation.


If your applicatio
n uses only a single persistent resource, Spring can use the transactional support offered by the
persistence mechanism.

This includes
JDBC
, Hibernate, and the Java Persistence
API
(
JPA
).

But if your application
has transaction requirements that span mul
tiple resources, Spring can support distributed (
XA
) transactions using a
third
-
party
JTA
implementation.


We’ll discuss Spring’s su
pport for programmatic transac
tions in section 6.3.

Where programmatic transaction
management affords you flexibility in p
recisely defining transaction boundaries in your code, declarative
transactions (which are based on Spring
AOP
) help you decouple an operation from its transaction rules.


Spring’s support for declarative transactions is reminiscent of
EJB
’s
container
-
man
aged transactions (
CMT
s)
.

Both
allow you to define transaction boundaries declaratively.

But Spring’s declarative transactions go beyond
CMT
s b
y
allowing you to declare addi
tional attributes such as isolation level and timeouts.


Declare a transaction ma
nager in your application Context. But you don’t need to have one.


The most common approach is to use <tx:annotation
-
driven> to define the configuration. This will cause a scan for
the classes with the @Transactional annotiation.

Using
the
@Controller a
nnotation

This will cause a controller to be
defined
,
and found when the component search step is done. At that point, a
specified part of the source tree (or the whole tree) will be searched. The

RequestMapping
-
annotated methods
registered.

The search/
loader method will check for consistency across the RequestMappings, i.e. no duplicates.


An action in a controller

falls into
one of
two categories:



One that
returns a ModelAndView



One that
return
s

a string which is the name
of the
view, and adds content
to the model provided in the
method parameters
.


Page
9

of
25

To make this work, you must specify two pieces in your configuration:

1.

the component
scanner, e.g.,
<context:component
-
scan base
-
package=
"com.incra.controllers"

/>

2.

the declaration that MVC is annotation drive
n, i.e.,
<mvc:annotation
-
driven />

Basic configuration for using MVC

At the heart of Spring
MVC
is
DispatcherServlet
, a servlet that functions as Spring
MVC
’s front controller.
Like any servlet,
DispatcherServlet
must be configured in the web application’s

web.xml file.

So the first
thing we must do to use Spring
MVC
in our application is to place the following
<servlet>
declaration in the
web.xml file:


<servlet>


<servlet
-
name>spitter</servlet
-
name>


<servlet
-
class>
org.springframework.web.servlet.Dis
patcherServlet</servlet
-
class>


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

</servlet>



The
<servlet
-
name>
given to the servlet is significant. By default, when
DispatcherServlet
is loaded,
it’ll load the Spring application context from an
XML
file whose name

is based on the name of the servlet. In this
case, because the servlet is named
spitter
,
DispatcherServlet
will try to load the application context from a
file named spitter
-
servlet.xml (located in the application’s
WEB
-
INF
directory).


Next, we map this

server to the URL pattern “/”. The book gives some explanation as to why this is a good pattern.


<servlet
-
mapping>


<servlet
-
name>spitter</servlet
-
name>


<url
-
pattern>/</url
-
pattern>

</servlet
-
mapping>


If it concerns you that
DispatcherServlet
will

be handling those kinds of requests, then hold on for a bit. A
handy configuration trick frees you, the developer, from having to worry about that detail much. Spring’s
mvc
namespace includes a new
<mvc:resources>
element that handles requests for static
content for you. All you
must do is configure it in the Spring configuration.

Request mapping

and handling requests

Spring provides about 5
-
6 different approaches for defining RequestMappings. These range from configuration
-
driven (used in earlier release
s), to bean
-
name driven, to class
-
name driven, to annotation driven. We will focus on
the latter here.


Although small, the
<mvc:annotation
-
driven>
tag packs a punch. It registers several features, including
JSR
-
303
validation support, message conversion,

and support for field formatting.


Mappings c
an be expressed at the class level or method level. Method
-
level mappings

can further refine the
mapping.


There are also ways to express request dispatching that handles the presence of headers, request data,

etc.

This
wasn’t covered well in the reference manual, but was in the Spring MVC video.


To handle the request, we typically return a ModelAndView object.


ModelMap

subclasses
LinkedHashMap
, and provides some additional conveniences to make it a bit easi
er to use
by controllers


addAttribute

can be called with just a value, and the map key is then inferred from the type.


The
addAttribute

methods all return the
ModelMap
, so you can chain method called together, e.g.
modelMap.addAttribute('x', x).addAttri
bute('y',y)

Page
10

of
25


The
addAttribute

methods checks that the values aren't null


The generic type of
ModelMap

is fixed at
Map<String, Object>
, which is the only one that makes sense for
a view model.


So nothing earth
-
shattering, but enough to make it a bit nicer

than a raw
Map
. Spring will let you use either one.


You can also use the
Model

interface, which provides nothing other than the
addAttribute

methods, and is
implemented by the
ExtendedModelMap

class which it
self adds further conveniences.

Resolving V
iews


The last thing that must be done in the course of handl
ing a request is rendering out
put to the user.

This job falls to
some view implementation

typically JavaServer Pages (
JSP
), but other view technologies such as Velocity or
FreeMarker may be used.

I
n order to figure out which view should handle a given request,
DispatcherServlet
consults a view resolver to exchange the logical view name returned by a controller for an actual view that should
render the results.


In reality, a view resolver’s job is t
o map a logica
l view name to some implementa
tion of
org.springframework.web.servlet.View
.

But it’s sufficient for now to think of a view resolver as
something that maps a view name to a JSP, as that’s effectively what it does.


A lot of Spring
MVC
embrace
s a convention
-
over
-
configuration approach to development.


InternalResourceViewResolver
is one such convention
-
oriented element. It resolves a logical view name
into a
View
object that delegates rendering responsibility to a tem
-
plate (usually a
JSP
) loc
ated in the web applica
-

tion’s context.


There are others that are used by Tiles.

Handing Input

Notes from
section

7.3 should go here.

Processing

Forms

Notes from section 7.4 should go here.


This section also explains the Spring forms tags

Handling File
Uploads

Notes from section 7.5 should go here

Implementing Flash S
cope

This is a concept first developed in Grails. Here we discuss how to implement it in spring 3.0. There will be native
support for flash scope in Spring 3.1.


http://mrather.blogspot.com/2010/02/flash
-
scope
-
alternative
-
in
-
spring
-
mvc.html


http
://blog.smartkey.co.uk/2011/01/implementing
-
flash
-
scope
-
in
-
java
-
web
-
applications/

Summary of MVC Concepts

At this point, we can see why Spring is considered so flexible


you can tailor the request dispatching, and tailor the
view resolution. The view re
solution technologies include views in JSP, FreeMarker, etc.


In turn, there are facilities to handle forms of various complexities, and perform validation.

Page
11

of
25


Although the views developed in this chapter were written in
JSP
to produce
HTML
output, there’s n
o reason why
the model data produced by the controllers couldn’t be rendered in some other form, including machine
-
readable
XML
or
JSON
.


We’ll see how to turn the Spitter application’s web layer into a
powerful web
-
based API in chap
ter
11 when we explore
Spring’s
REST
support further.


You can also see why all of the prior Controller class facilities were deprecated!


You also can’t mix them!

Examples of Basic Controllers for CRUD operations

The list method

Returns a ModelAndView

Th
e

show and edit methods


@RequestMapping
(value =
"/organization/show/{id}"
, method = RequestMethod.
GET
)


public

String show(
@PathVariable

Long id, Model model) {


pageFrameworkService
.setCurrentModule(
this
);



Organization organization =
organizationService
.findOrganizati
onById(id);



model.addAttribute(
"modules"
,
pageFrameworkService
.getModules());


model.addAttribute(organization);


return

"organization/show"
;


}



@RequestMapping
(value =
"/organization/edit/{id}"
, method = RequestMethod.
GET
)


public

ModelAnd
View edit(
@PathVariable

Long id) {


pageFrameworkService
.setCurrentModule(
this
);



Organization organization =
organizationService
.findOrganizationById(id);



ModelAndView modelAndView =
new

ModelAndView(
"organization/edit"
);


modelAndView.addO
bject(
"modules"
,
pageFrameworkService
.getModules());


modelAndView.addObject(
"command"
, organization);


return

modelAndView;


}

The save
and delete
method
s

We used save for both save (for create) and update (for edit)


@RequestMapping(value = "/sale
sOrder/save", method = RequestMethod.
POST
)


public

String save(@ModelAttribute("salesOrder") SalesOrder salesOrder,


BindingResult result, HttpSession session) {



try

{


salesOrderService.save(salesOrder);


}
catch

(RuntimeException re) {


pageFrameworkService.setFlashMessage(session, re.getMessage());


pageFrameworkService.setIsRedirect(session, Boolean.
TRUE
);


return

"redirect:/salesOrder/list";


}


return

"redirect:/salesOrder/list";


}



@RequestMapping(value = "
/salesOrder/delete/{id}", method = RequestMethod.
GET
)


public

String delete(@PathVariable Long id, HttpSession session) {



SalesOrder salesOrder = salesOrderService.findSalesOrderById(id);

Page
12

of
25


if

(salesOrder !=
null
) {


try

{


salesOrderSe
rvice.delete(salesOrder);


}
catch

(RuntimeException re) {


pageFrameworkService.setFlashMessage(session, re.getMessage());


pageFrameworkService.setIsRedirect(session, Boolean.
TRUE
);


return

"redirect:/salesOrder/show/" + id;



}


}
else

{


pageFrameworkService.setFlashMessage(session,


"No salesOrder with that id");


pageFrameworkService.setIsRedirect(session, Boolean.
TRUE
);


}



return

"redirect:/salesOrder/list";


}

Note that this code also take
s care of exception handling, which the examples in the book and tutorials don’t.

Other methods in a controller

These

are the basic ones for CRUD
-
oriented controllers.
In our experience
, about 60% of the app is CRUD
-
oriented
controllers, and the rest are
special cases.

Other Controller Annotations

Ses
sion
Attribute annotation [fill in]


ModelAttribute annotation [fill in]

Resource
Caching

There is a new tag called “resources” in 3.0.5


This enables a resource
servlet

to be set up, which will provide rapid s
ervice for resources such as images and css
files.

Generating Responses

when using Spring MVC

There are several options:



Return a pojo annotated with a RequestBody annotation.



Return a ResponseEntity object

(headers, status code)



Return a JSON object

(usin
g Jackson)

o

You can customize the way that object serialization works



Return a .jsp
-
based view


The typical used case is

.jsp.
The view rendering code is a subsystem within Spring MVC.
Other approaches

include other template engines such as velocity or Fr
eeMarker, or different presentation
tool libraries such as Wicket
(s
ee our document “Notes on Wicket”).

How to write th
e

.

jsp files

What parts are like Grails?


${expr}



this evaluates an expression.


<c:
forEach
>

--

this is an iterator.


<c:if>
--

there
is no <else>

Page
13

of
25


Include?



use jsp:include for this

Forms

The form tag library comes bundled in
spring.jar
. The library descriptor is called
spring
-
form.tld
.


To use the tags from this library

(only in our edit screens)
, add the following directive to the to
p of your JSP page:


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


... where
form

is the tag name prefix you want to use for the tags from this library.


The form

tag renders an HTML 'form' tag and exposes a binding path to in
ner tags for binding.

It puts the command
object in the
PageContext

so that the command object can be accessed by inner tags.

All the other tags in this
library are nested tags of the
form

tag
.


Let's assume we have a domain object called
User
.

It is a

JavaBean with properties such as
firstName

and
lastName
.

We will use it as the form backing object of our form controller which returns
form.jsp
.

Below is
an example of what
form.jsp

would look like:


<form:form>


<table>


<tr>


<t
d>First Name:</td>


<td><form:input path="firstName" /></td>


</tr>


<tr>


<td>Last Name:</td>


<td><form:input path="lastName" /></td>


</tr>


<tr>


<td colspan="3">


<
input type="submit" value="Save Changes" />


</td>


</tr>


</table>

</form:form
>


The preceding JSP assumes that the variable name of the form backing object is
'command'
.


If you have put the
form backing object into the model under a
nother name (definitely a best practice), then you can bind t
he form to the
named variable
.

Using Tiles 2

More details in our document “Notes on Java Templating”

Using Themes

A theme is a collection of static resources, typically style sheets and images, t
hat affect the visual style of the
application.

We can apply Spring Web MVC framework themes to set the overall look
-
and
-
feel of application,
thereby enhancing user experience.

To use themes in your web application, you must set up an implementation of t
he
org.springframework.ui.context.ThemeSource interface.

The WebApplicationContext interface extends
ThemeSource but delegates its responsibilities to a dedicated implementation.

By default the delegate will be an
org.springframework.ui.context.support.R
esourceBundleThemeSource implementation that loads properties files
from the root of the classpath.

To use a custom ThemeSource implementation or to configure the base name prefix
of the ResourceBundleThemeSource, you can register a bean in the applicatio
n context with the reserved name
themeSource.

The web application context automatically detects a bean with that name and uses it.

Page
14

of
25

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

The properties file
lists the res
ources that make up the theme.

Here is an example
:


Our goal is to change the Hello World Spring 3 MVC and add Theme support to it.

User will have option to select
theme from 3 predefined themes (default, black and blue).


For this we will add following
code into spring
-
servlet.xml file.

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<
bean

id="themeSource"


class="org.springframework.ui.context.support.ResourceBundleThemeSource">


<property

name="basenamePrefix"

value="theme
-
"

/>

</bean>



<!
--

Theme Change Interceptor and Resolver definition
--
>

<bean

id="themeChangeInterceptor"


class="org.springframework.web.servlet.theme.ThemeChangeInterceptor">


<property

name="paramName"

value="theme"

/>

</bean>

<bean

id="themeResol
ver"


class="org.springframework.web.servlet.theme.CookieThemeResolver">


<property

name="defaultThemeName"

value="default"

/>

</bean>



<bean

id="handlerMapping"


class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMappi
ng">


<property

name="interceptors">


<list>


<ref

bean="localeChangeInterceptor"

/>


<ref

bean="themeChangeInterceptor"

/>


</list>


</property>

</bean>


I
n the above configuration, first we have added
themeSourc
e

bean.

Notice that this bean is an instance of class
ResourceBundleThemeSource

and we also have specified a property
basenamePrefix

with value
“theme
-

.
ResourceBundleThemeSource class will load the property files containing theme definition starting wit
h prefix
“theme
-
”.

Thus, if we have defined 3 new themes in our project (default, black and blue) then we will create 3
property files while will have certain configuration properties.

Also these files will be placed under the project
classpath.


Next,
we defined an interceptor bean themeChangeInterceptor which is an instance of class
org.springframework.web.servlet.theme.ThemeChangeInterceptor
. Also note here that we
have specified a property
paramName

with value
theme
. This interceptor is invoked whene
ver a request is made
with parameter “theme” with different values.


Once the themeChangeInterceptor intercepts the change in the theme, the changes are then stored in the cookies
using class
org.springframework.web.servlet.theme.CookieThemeResolver
.

We
have
configured this class in our spring
-
servlet.xml configuration file.

Also note that we have specified default theme
name with this bean.


To cause the theme to be used by the app’s JSP’s, add the following:


<link rel="stylesheet" href="<spring:theme

code="css"/>" type="text/css"/>


We are almost done with the changes and last bit that is remaining is to add a functionality for user to select the
theme from UI. For this we will change the header.jsp file and add 3 links with different themes. User c
an click on
any of this link and change the theme of webapplication.


01

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

Page
15

of
25

02

03

04

05

06

07

08

09

10

11

12

13

14


<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>



<h3><spr
ing:message

code="label.title"/></h3>



<span

style="float: right">


<a

href="?lang=en">en</a>


|


<a

href="?lang=de">de</a>

</span>



<span

style="float: left">


<a

href="?theme=default">def</a>


|


<a

href="?theme=black">blk</a>


|



<a

href="?theme=blue">blu</a>

</span>


Notice that in above JSP changes we created 3 links with argument “?theme=”.

Thus whenever user will click these
links, a new parameter will be passed in the request with the appropriate theme.

The request inter
ceptor of Spring
will fetch this value and change the theme accordingly.

Property Management and Conversion

This is from
http://www.theserverlabs.com/
blog/2009/04/30/select
-
lists
-
with
-
validation
-
in
-
spring
-
mvc/


What we need to do therefore, is register some kind of converter that is capable of c
onverting a Department to an Id

which can be associated with a value in a <form:select> list and, once submit
ted, doing the rev
erse conversion on a
supplied Id

to obtain the original Department object.

In JSF, an object that performs this conversion is called a
Converter.

Spring uses the Java convention and calls it a Property Editor.


The DepartmentEditor is
shown below.

public

class

DepartmentEditor
extends

PropertyEditorSupport {




private

final

DepartmentDao departmentDao;




public

DepartmentEditor(DepartmentDao departmentDao) {


this
.departmentDao = departmentDao;


}




@Override


p
ublic

void

setAsText(String text)
throws

IllegalArgumentException {


setValue(departmentDao.findById(Integer.parseInt(text)));


}




@Override


public

String getAsText() {


Department s = (Department) getValue();


if

(s ==
nul
l
) {


return

null
;


}
else

{


return

s.getId().toString();


}


}

}

The basic convention for implementing a PropertyEditor is:

1.

E
xtend the standard Java class PropertyEditorSupport to make life easier

2.

O
verride the setAs
Text(String text) method and in the body, call setValue() with the object that
corresponds to the text as arguments

3.

O
verride the getAsText() method and in the body, returning a string that represents the object that you
obtain when you call getValue()


Page
16

of
25

In
DepartmentEditor,
pass a DepartmentDao impleme
ntation in the constructor so it can fetch the possible values
.

Registering the Property Editor

You have to associate a Property Editor with the class that it is capable of converting. There are various ways t
o do
this but I find the easiest way (for early experiments anyway) is to register it in the controller using the @InitBinder
annotation.

Below is the code used to register DepartmentEditor with the UserController.


Note that I pass in the
Department DAO
implementation in the constructor.



@InitBinder


public

void

initBinder(WebDataBinder dataBinder) {


dataBinder.registerCustomEditor(com.tsl.springmvc.bom.Department.
class
,
new

DepartmentEditor(departmentDao));


}

Same thing, Another Perso
n’s Approach

http://www.mkyong.com/spring
-
mvc/spring
-
mvc
-
dropdown
-
box
-
example/

Another one

http://forum.
springsource.org/showthread.php?t=35719

Handling Dates

Similar to the above, we need to register converters.


http://www.stpe.se/2008/07/date
-
fields
-
in
-
forms
-
using
-
s
pring
-
and
-
appfuse/

Validation

Similar to Hibernate
-
based validations or JSF validations.


Annotation
-
driven.


What is the difference between BindResults and Errors?

Exception H
andling

Similar to how Struts support
s

the declaration of global exception hand
lers.

Wizards

Fortunately, Spring MVC provides
AbstractWizardFormController
to help out.
AbstractWizardFormController
is the most powerful of the controllers that come with Spring. As
illustrated in figure 13.9, a wizard form controller is a special type o
f form controller that collects form data
from multiple pages into a single command object for processing.


Let’s see how to build a multipage registration form using
AbstractWizardFormController
.


See example at
http://www.mkyong.com/spring
-
mvc/spring
-
mvc
-
handling
-
multipage
-
forms
-
with
-
abstractwizardformcontroller/


However, this class is deprecated. See the discussion at

http://stackov
erflow.com/questions/4623667/abstractwizardformcontroller
-
using
-
annotated
-
controllers

Page
17

of
25

Services

Indicated with the @Service annotation. This makes the service injectable by name/class

Transaction Management


<!
--

enable the configuration of transactional b
ehavior based on annotations
--
>

<tx:annotation
-
driven transaction
-
manager="txManager"/>


All public service methods are wrapped in a transacti
on if @Transactional is present on the Service class or the
specific method. The values for transaction propagat
ion type are (in Seam):



REQUIRED

(the default). If a transaction isn’t active, Seam will start one.



SUPPORTS



MANDATORY



NEVER


Also, in the methods, don’t catch the exception, propagate it so that the transaction will be rolled back.


In proxy mode (which
is the default), only external method calls coming in through the proxy are intercepted. This
means that self
-
invocation, in effect, a method within the target object calling another method of the target object,
will not lead to an actual transaction at ru
ntime even if the invoked method is marked with
@Transactional
.


The
@Transactional

annotation is metadata that specifies that an interface, class, or method must have
transactional semantics; for example, “
start a brand new read
-
only transaction when this

method is invoked,
suspending any existing transaction
”.

The default
@Transactional

settings are as follows:




Propagation setting is
PROPAGATION_REQUIRED.



Isolation level is
ISOLATION_DEFAULT.



Transaction is read/write.



Transaction timeout defaults to th
e default timeout of the underlying transaction system, or to none if
timeouts are not supported.



Any
RuntimeException

triggers rollback, and any checked
Exception

does not.


These default settings can be changed; the various properties of the
@Transaction
al

annotation are
summarized in the following table:

Table

10.3.

@Transactional

properties

Property

Type

Description

value

String

Optional qualifier specifying the
transaction manager to be used.

propagation

enum:
Propagation

Optional propagation setting.

isolation

enum:
Isolation

Optional isolation level.

readOnly

boolean

Read/write vs. read
-
only transaction

ti
meout

int (in seconds granularity)

Transaction timeout.

rollbackFor

Array of
Class

objects, which must be
derived from
Throwable.

Optional array of exception classes
that
must

cause rollback.

rollbackForClassname

Array of class names. Classes must be
der
ived from
Throwable.

Optional array of names of exception
classes that
must

cause rollback.

noRollbackFor

Array of
Class

objects, which must be
derived from
Throwable.

Optional array of exception classes
that
must not

cause rollback.

noRollbackForClassna
me

Array of
String

class names, which
must be derived from
Throwable.

Optional array of names of exception
classes that
must not

cause rollback.

Page
18

of
25


Currently you cannot have explicit control over the name of a transaction, where 'name' means the transaction

name
that will be shown in a transaction monitor, if applicable (for example, WebLogic's transaction monitor), and in
logging output. For declarative transactions, the transaction name is always the fully
-
qualified class name + "." +
method name of the tr
ansactionally
-
advised class. For example, if the
handlePayment(..)

method of the
BusinessService

class started a transaction, the name of the transaction would be:
com.foo.BusinessService.handlePayment
.

Repository Annotation

What does @Repository do?

Prelo
ading the D
atabase

The standard approach is to use the import.sql file, which the Hibernate loaders will read.


We have written a method for loading.

Spring Remoting

Several remoting technologies are available to you, as a Java developer, including
:



Remote

Method Invocation (
RMI
)



Caucho’s Hessian and Burlap



Spring’s own
HTTP
-
based remoting



Web services with
JAX
-
RPC
and
JAX
-
WS


Regardless of which remoting technology you choose, Spring provides broad support for accessing and creating
remote services with

several different technologies.


Remoting
is a conversation between a client application and a service. On the client side, some functionality is
required that isn’t within the scope of the application. So the application reaches out to another system th
at can
provide the functionality. The remote application exposes the functionality through a remote service.


Likewise, a local method call is one where execution flow is exchanged between two blocks of code within the same
application.


On the other hand
, if you were to pick up the phone to call a client in another city, your conversation
would be conducted remotely ov
er the telephone network.
Simi
larly,
RPC
is when execution flow is handed off
from on
e application to another appli
cation, theoretically o
n a different machine in a remote location over the
network.


Differences between these include:



Page
19

of
25

RMI as an example of remoting

If you’ve ever created an
RMI
service before, you know that it involves the following steps:

1.

Write the service implementation

class with methods that throw
java.rmi .RemoteException
.

2.

Create the service interface to extend
java.rmi.Remote
.

3.

Run the
RMI
compiler (
rmic
) to produce client stub and server skeleton classes.

4.

Start an
RMI
registry to host the services.

5.

Register the ser
vice in the
RMI
registry.


Fortunately, Spring provides an easier way to publish
RMI
services. Instead of writing
RMI
-
specific classes with
methods that throw
RemoteException
, you simply write a POJO that performs the functionality of your service.
Spring
handles the rest.


The simplest way to use
RmiServiceExporter
to expose
SpitterServiceImpl
as an
RMI
service is to
configure it in Spring with the following
XML
:


<bean class="org.springframework.remoting.rmi.RmiServiceExporter" p:service
-
ref="spitterServ
ice"
p:serviceName="SpitterService" p:serviceInterface="com.habuma.spitter.service.SpitterService"/>


Spring’s
RmiProxyFactoryBean
is a factory bean that creates a proxy to an
RMI
ser
-

vice. Using
RmiProxyFactoryBean
to reference an
RMI
SpitterService
is a
s simple as adding the following
<bean>
to the client’s Spring configuration file:


<bean id="spitterService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean"
p:serviceUrl="rmi://localhost/SpitterService"
p:serviceInterface="com.habuma.spitter
.service.SpitterService"/>


The
URL
of the service is set through
RmiProxyFactoryBean
’s
serviceUrl
property. Here, the service is
named
SpitterService
and is hosted on the local machine. Meanwhile, the interface that the service provides is
specified with

the
serviceInterface
property.


@Autowired SpitterServicespitterService;


Then you can invoke methods on it as if it were a local bean:




public List<Spittle>getSpittles(StringuserName){



Spitter

spitter

=

spitterService.getSpitter(userName);



return spitterService.getSpittlesForSpitter(spitter);


}


What’s great about accessing an
RMI
service in this way is that the client code doesn’t even know that it’s dealing
with an
RMI
service. It’s given a
SpitterService
object via injection, wi
thout any concern for where it comes from.
Furthermore, the proxy catches any
RemoteException
s that may be thrown by the service and rethrows them as
unchecked exceptions that you may safely ignore. This makes it possible to easily swap out the remote serv
ice bean
with another imple
-

mentation of the service

perhaps a different remote service or maybe a mock implementation
used when unit testing the client code.


Hessian and Burlap as examples of remoting

Exporting a Hessian service in Spring is remarkably
similar to implementing an
RMI
service in Spring. To expose
the Spitter service bean as an
RMI
service, we had to con
-

figure an
RmiServiceExporter
bean in the Spring
configuration file. In a similar way, to expose the Spitter service as a Hessian service,

we’ll need to configure
another exporter bean. This time it’ll be a
HessianServiceExporter
.

WS
-
RPC

Java and web services have a long history together and several options are available for working with web services
in Java. Many of those options integrate

with Spring in some way. Though it’d be impossible for me to cover every
Page
20

of
25

Spring
-
enabled web service framework and toolkit in this book, Spring itself comes with some capable support for
publishing and consuming
SOAP
web services using the Java
API
for
XM
L
Web Services, or
JAX
-
WS
as it’s
commonly known.


Refer to the book for more details

Implementing REST resources

In recent years,
Representational State Transfer (
REST
)
has emerged as a popular information
-
centric alternative to
traditional
SOAP
-
based web

services. To help Spring developers take advantage of the
REST
architectural model,
Spring 3.0 came packed with first
-
class support for working with
REST
.


The good news is that Spring’s
REST
support builds upon Spring
MVC
, so we’ve already covered much
of what
we’ll need for working with
REST
in Spring. In this chapter, we’ll build upon what we already know about Spring
MVC
to develop control
-
lers that handle requests for
REST
ful resources. We’ll also see what Spring has to offer on
the client side of a
REST
conversation.


Spring has long had some of the ingredients needed for exposing
REST
resources. But with Spring 3 came several
enhancements to Spring
MVC
providing first
-
class
REST
support. Now Spring supports development of
REST
resources in the follo
wing ways:



Controllers can handle requests for all
HTTP
methods, including the four pri
-

mary
REST
methods:
GET
,
PUT
,
DELETE
, and
POST
.



The new
@PathVariable
annotation enables controllers to handle requests for parameterized
URL
s
(
URL
s that have variabl
e input as part of their path).



The
<form:form>
JSP
tag from Spring’s form
-
binding
JSP
tag library, along with the new
HiddenHttpMethodFilter
, make it possible to submit
PUT
and
DELETE
requests from
HTML
forms,
even in browsers that don’t support those
HTT
P
methods.



Resources can be represented in a variety of ways using Spring’s view and view resolvers, including new
view implementations for rendering model data as
XML
,
JSON
, Atom, and
RSS
.



The representation best suited for the client can be chosen using

the new
ContentNegotiatingViewResolver
.



View
-
based rendering can be bypassed altogether using the new
@ResponseBody
annotation and various
HttpMethodConverter
implementations.



Similarly, the new
@RequestBody
annotation, along with
HttpMethodConverter
im
plementations,
can convert inbound
HTTP
data into Java objects passed into a controller’s handler methods.



RestTemplate
simplifies client
-
side consumption of
REST
resources.

Implementation

As mentioned before,
REST
is about the transfer of resource state.

Therefore, we really only need a handful of verbs
to be able to act upon those resources

verbs to transfer the state of a resource. For any given resource, the most
common operations will be to create a resource on the server, retrieve it from the server,

update it on the server, or
delete it from the server. The verbs we’re interested in (
post
,
get
,
put
, and
delete
) correspond directly to four of the
methods as defined by the
HTTP
specification and as summarized below.

Each of the
HTTP
methods is
chara
cterized by two traits: safety and idempotency. A method is considered
safe
if it doesn’t change the state of the
resource.
Idempotent
methods may or may not change state, but repeated requests should have no further side effects
after the first request. B
y definition, all safe methods are also idempotent, but not all idempotent methods are safe.


Page
21

of
25


Using Java Message Services

The Java Message Service (
JMS
) is a standard
API
for asynchronous messaging.
Here w
e’ll look at how Spring
simplifies sending and re
ceiving messages with
JMS
. In addition to basic sending and receiving of messages, we’ll
look at Spring’s support for message
-
driven
POJO
s, a way to receive messages that resembles
EJB
’s message
-
driven
beans (
MDB
s).


For more information see the book. The

examples provided are based on using ActiveMQ as the message broker.


The examples include use of publish
-
subscribe as well as point
-
to
-
point.

Testing

How do you confirm that your mappings are correct?

You can’t run the whole MVC within JUnit.

Deployment

Strategies

and Tools

Rather than developing directly in the Tomcat webapps directory (as we did for the Wicket examples in early 2009),
we are now using Web Tools Project in E
clipse. Other possibilities include the Spring Tools Suite, or MyEclipse.

Sup
port Tools

What is the
WTP Eclipse Web Tools Project
? See
http://www.vogella.de/articles/EclipseWTP/article.html


This indicates that WTP will start Tomcat and deploy to it.

Also
con
tains

tools that aid in creating web services.

The current release is 3.2.
3

and th
at appears to run in Eclipse 3.6
.


WTP even has a tool that will create a war file.

This could be very useful.


See
h
ttp://wiki.eclipse.org/WTP_Tomcat_FAQ

for more information about Tomcat and WTP.


What is the Spring Tool Suite
?

This is an Eclipse
-
based superset of WTP. It is provided for free by SpringSource,
and consists of an Eclipse base, plus tools that specific
ally help with Spring and Grails
-
base programs.


What is MyEclipse? A very comprehensive suite of tools based on Eclipse, which we used from 2005 to 2008. Sold
on an annual subscription basis.

See our document “Notes on MyEclipse”.

Page
22

of
25

How to Generate a Dat
aGrid (simple approach)

Use
http://jakarta.apache.org/taglibs/sandbox/doc/datagrid
-
doc/

Spring Test

Spring Test is a library built on the Spring Core and JUnit that applies the va
lue
-
add of the IoC principle to
unit
testing

and hence creates benefits at several levels for integrat
ion testing of Spring applications. It provides
extensions such as an improved test runner, test execution listeners, tracking of text execution results, and more.
There is also a package of additional asserts for extension of JUnit’s asserts.

Test Runne
r

@RunWith(SpringJUnit4ClassRunner.class)

Quoting the docs: “SpringJUnit4ClassRunner is a custom extension of JUnit4ClassRunner which provides
functionality of the Spring TestContext Framework to standard JUnit 4.4+ tests by means of the
TestContextManager

and associated support classes and annotations.”

Basically this means that tests are going to be able to get hold of instantiated beans as defined in the Spring context
files (see below).

@ContextConfiguration(locations={“daos.xml”})

This is telling the t
est where to get the context files containing the bean definitions. Note that if you do not provide
any arguments to the annotation then a default will be looked for.

For example: If your class is named foo.bar.DaoTests, the context loader will attempt to
load your application
context from “classpath:/foo/bar/DaoTests
-
context.xml”.

@Autowired

This will autowire BY TYPE, beans found in the context. Alternatively you could use @Resource to inject the
dependencies by NAME (useful if several beans are of the sa
me type)

Now it’s simply the case of adding a few annotations and a few imports to be able easily write tests which use
Spring beans. All in all, a very unobtrusive (and fast) process.

Spring TestContext Framework

The
Spring
TestContext

Framework

(located
in the
org.springframework.test.context

package) provides generic, annotation
-
driven unit and integration testing support that is agnostic of the testing
framework in use, whether JUnit 3.8.2, JUnit 4.5+, TestNG 5.10, and so on.

The TestContext framework
also
places a great deal of importance on
convention over configuration

with reasonable defaults that can be overridden
through annotation
-
based configuration.

Spring Test Asserts

The Spring Test library provides an a
ssertion utility class that assists in
validating arguments.

This is u
seful for
identifying programmer errors early and clearly at runtime.


For example, if the contract of a public method states it does not allow
null

arguments, Assert can be used to
validate that contract.


Doing this clear
ly indicates a contract violation when it occurs and protects the class's
invariants.


These are t
ypically used to validate method arguments rather than configuration properties, to check for cases that
are usually programmer errors rather than configurat
ion errors.


In contrast to config initialization code, there is
usually no point in falling back to defaults in such methods.


This class is similar to JUnit's assertion library.

If an argument value is deemed invalid, an
IllegalArgumentException

is

thrown (typically).


One item to note that is different from JUnit: the optional message is the last argument, while in JUnit

it is first.
Also, there is no assert for equals(), you must write an expression and check for true.

Page
23

of
25

Spring Web Flow

A module layered on top of Spring that provides for work
-
flow based sequences of screens and actions. Contains a
“flow language”


The cu
rrent version is 2.3.0, released in early 2011.


We are running an example in the directory called SpringPizza, based on examples in the book.

Spring Social

Spring Social is an extension of the Spring Framework that enables you to connect your Java applica
tions to
Software
-
as
-
a
-
Service (SaaS) providers such as Facebook and Twitter.



Contains implementations of the different social api’s.

For instance, this would be a way to integrate a twitter feed
into an application.


The big 1.0 release

(in September 2
011) included

fixes for all bugs reported since 1.0.0.RC3. See the
change log for
all the details.


To get the software, download the release distribution (
Core

|
Facebook

|
Twitter
) or simply add the
maven artifacts

to your project.


To se
e it live, try out the
quickstart

and fire up the
samples
. Supplement as you go with information
from the
reference manual
.


Spring Social requ
ires Spring Framework 3.0.5 or greater

to run.

Open Q
uestions

How to take all of the white space out of the transmitted
files?

Appendix A: Learning Programs Generated

SP01

Clean example using the following
:

Hibernate, Tiles, form tags, converters, a dedicated servlet for resourc
es, and
Spring and Hibernate annotations. The list of
libraries is minimal and current version
s

(as of early 2011
).


H
as a data
model of customer/product/salesO
rder
/project
, and simple sc
reens and
navigation. The Spring concepts
used are configuratio
n, controllers, JSP’s, and the S
pring tags. The Spring form tags used are form:form,
form:input, f
orm:textarea, form:select. The jQuery calendar popup is used for the dates.


There are converter classes for handling each of the basic entities, and these are used in the select tags.


There are no admin screen functions, hence reference tables such as P
roductType are not managed.


[done] all entities must have show and edit functions

[done
] confirm that the
approach to hashCode() and equals() management is on track.

Yes, this uses the
Object.equals utilities.

[done
] all en
tities must have create methods

[done] currency list is missing on product

[done] integrate example of wizard

[in
-
progress] check that validation is being applied to edit sessions

SP02

Extended version of SP01, with
a similar data model
, plus support for modules and menus

plus Spring Se
curity
.

Based on Maven, with Selenium testing.

Page
24

of
25


[done] load information about countries, states, currencies

[done] create entities for module, command

[done] review Spring Security, find minimal plug
-
in requirements

[
done
] update to include lessons learne
d from getting the edit screens

[done] convert to a Maven project

[done] incorporate Selenium 2.0 for testing

[done] incorporate Highcharts

[done] integrate configurable dashboard

[in progress] implement methods in abstract list page for testing

[in progre
ss] incorporation of ehcache

[in progress] internationalization of messages

SP03

Advanced
version of SP02, with
a data model for environmental management, plus

use of

flex fields and tags
. Also

has second
-
generation permission system, use of JPA 2.0 instead of

Hibernate, incorporation of ehc
ache, and some
support for internationalization of messages.


[done] convert to a Maven project

[done] incorporate Selenium 2.0 for testing

[done] integrate w
izard code

[in progress] migrate project code from other branches

[in progress] pagination and sorting of fetches for list screens

[in progress] optimize fetching of flex fields

[in progress] implement methods in abstract list page for testing

[in progress
] refine the permission system

[in progress] re
-
check all the editing operations

[in progress] review the display of data with custom fields

[in p
rogress] review the cache management

[in progress] translate tag usage manager from Grails to Java/Hibernate

[
possible] transfer to GitHib


Resource and Activity are not
currently
used

Output and ResultValue are
currently
used.

There are several DTO’s that represent OutputValues, but these are not
entities.

SP04

(not yet created, and many aspects are already pres
ent in SP03)
Would

be an e
xtended version of SP02, with su
pport
for forecasts and time segments


[done
] populate time segments

[check this
] integrate the forecast library

[done
] integrate charting of over
-
time data

[done
] convert to a Maven project

[in pro
gress] integrate project code

SP05

(not yet created)
Spring S
ecurity ACL work area

SP06

(not yet created) Upload and download work area.


Upload and download using POI

Page
25

of
25

Upload image files?

QbeFit

(stored in GitHub)
Derived from SP01, in that it
uses Hiberna
te, not JPA. But like SP02, it

contains Spring Security
usage. Contains limited Ajax interactions, needs more. Contains use of Highcharts, but the data fetch is wrong.

Contains a use of Ehcache, but we haven’t reviewed the cache usage.


[done] implemen
t a multi
-
select list page

[done
] put all image files into directory

[done
] add image file names to activity data structure

[done
] render

image files

[not started] integrate the LogEntry facility

[not started] figure out how to implement sorting and filter
ing on the log entry list, then apply that to other lists.

[not started] change front page update logic to Ajax rendering

[not started
] are there shortcuts for some of the tags? Like ones to make links?

[not started] are transactions handled correctly?

[n
ot started] is caching being done correctly?

[unknown] how should the challenge engine be organized?

[not started] data model update for MongoDB