Java Reference
In-Depth Information
Managing transactions with Spring
There are several lightweight mechanisms for making
POJO
s transactional. One
very popular framework that provides this capability is Spring. Spring is a power-
ful
J2EE
application framework that makes it significantly easier to develop enter-
prise Java applications. It provides a large number of features, and I'm only going
to provide a brief overview of a few of them in this chapter. For more information
see
Spring in Action
[Walls 2005].
The Spring framework provides an extremely easy-to-use mechanism for mak-
ing
POJO
s transactional that works in a similar way to container-managed transac-
tions. Spring will automatically begin a transaction when a
POJO
method is
invoked and commit the transaction when the method returns. It can also roll
back a transaction if an error occurs. Spring can manage transactions using the
application server's implementation of the Java Transaction
API
(
JTA
) if the appli-
cation accesses multiple resources such as a database and
JMS
. Alternatively,
Spring can manage transactions using the persistence framework or
JDBC
transac-
tion management
API
s, which are simpler and easier to use because they do not
require an application server.
When using the Spring framework, we can make a
POJO
transactional by defin-
ing it as a Spring bean, which is simply an object that is instantiated and managed
by Spring. Defining a Spring bean requires only a few lines of
XML
. The
XML
is
similar to a deployment descriptor and configures Spring's lightweight container,
which is a sophisticated factory for constructing objects. Each entry in the
XML
file defines the configuration of a Spring bean, which includes its name, its
POJO
implementation class, and a description of how to instantiate and initialize it. An
application obtains a bean by calling the Spring bean factory with the name and
expected type of the bean:
BeanFactory beanFactory = …
TransferFacade tf = (TransferFacade)
beanFactory.getBean("TransferFacade", TransferFacade.class);
This code fragment calls the
BeanFactory.getBean()
method with
Transfer-
Facade
as the name of the bean and
TransferFacade
as the expected class. The
bean factory will throw an exception if a bean with that name does not exist or is
of a different type.
As well as being a highly configurable way to instantiate objects, a Spring bean
factory can be configured to return a proxy instead of the original object. A
proxy, which is also known as an interceptor, is an object that masquerades as the
original object. It executes arbitrary code before and after invoking the original
Search WWH ::
Custom Search