1. August 17, 2005 DEGT Realtime Apps
The Spring Framework
The Lightweight Framework for Enterprise.
-Shankar Nair.
2. August 17, 2005 DEGT Realtime Apps
Introduction
Introduction
Why Spring?
Architectural benefits
Why is Spring unique
Spring Essentials
Overview of the Spring framework
Inversion of control
Wiring Beans using the IoC Container
Creating Aspects
Spring in the Business Layer
Persistence Model
Transaction Management
Remoting
Spring in the Web Layer
Building the Web Layer
Summary
Spring Distilled
References
3. August 17, 2005 DEGT Realtime Apps
Why Spring?
Some specific causes of complexity / problems in J2EE applications.
J2EE applications tend to contain excessive amounts of “plumbing” code.
JNDI lookup code, Transfer Objects, try/catch blocks to acquire and release JDBC resources.
Many J2EE applications use a distributed object model where this is inappropriate.
Using distributed semantics like how much data to be returned with each serialized object - should we traverse associations, and if so
till what depth, or maybe a discontinuity in an Business Object at the point of remote invocation etc. adds complexity in otherwise
simple applications.
The EJB component model is unduly complex.
EJB was conceived as a way of reducing complexity when implementing business logic in J2EE applications; not so in practice.
EJB is overused.
EJB was essentially designed for internally distributed, transactional applications. While nearly all non-trivial applications are
transactional, distribution should not be built into the basic component model.
J2EE applications are hard to unit test.
The J2EE APIs, and especially, the EJB component model, were defined before the agile movement took off. Thus their design does
not take into account ease of unit testing.
Yet unit testing outside an application server is essential to achieve high test coverage and to reproduce many failure scenarios, such
as loss of connectivity to a database. It is also vital to ensuring that tests can be run quickly during the development or maintenance
process, minimizing unproductive time waiting for redeployment.
Certain J2EE technologies have simply failed.
Example: Entity beans, which have proven little short of disastrous for productivity and in their constraints on object orientation.
There are much better alternatives like JDO / Hibernate or in many cases JDBC
4. August 17, 2005 DEGT Realtime Apps
Architectural benefits
Spring can effectively organize the middle tier objects, whether or not you choose to use EJB.
Spring takes care of plumbing.
And while it is perhaps most valuable in the middle tier, Spring's configuration management services can be used in any architectural
layer, in whatever runtime environment.
Spring helps you solve many problems without using EJB.
For example, Spring can use AOP to deliver declarative transaction management without using an EJB container; even without a JTA
implementation, if you only need to work with a single database.
Spring can make the use of EJB an implementation choice, rather than the determinant of application architecture.
You can choose to implement business interfaces as POJOs or local EJBs without affecting calling code.
Spring can eliminate the proliferation of Singletons seen on many projects.
Having too many Singletons can reduce testability and object orientation.
Spring can eliminate the need to use a variety of custom properties file formats
By handling configuration in a consistent way throughout applications and projects.
Spring can facilitate good programming practice
Program to interfaces, rather than classes.
Spring is designed so that applications built with it depend on as few of its APIs as possible.
Most business objects in Spring applications have no dependency on Spring.
Applications built using Spring are very easy to unit test.
Spring provides a consistent framework for data access
whether using JDBC / JDO / O/R mapping product (TopLink, Hibernate).
Spring provides a consistent, simple programming model in many areas, making it an ideal architectural "glue."
Internal consistency is a core feature of the Spring approach (e.g. JDBC, JMS, JavaMail, JNDI and many other important APIs. )
Spring is essentially a technology dedicated to enabling you to build applications using POJOs.
This desirable goal requires a sophisticated framework, which conceals much complexity from the developer.
5. August 17, 2005 DEGT Realtime Apps
What is Spring?
Spring is a lightweight, inversion of control and aspect-oriented container framework.
Unlike single-tier frameworks such as Struts or Hibernate, Spring aims to help structure whole applications in a consistent,
productive manner, pulling together best-of-breed single-tier frameworks to create a coherent architecture.
Lightweight
Lightweight in both size and overhead (single Jar file just over 1mb)
Processing overhead is negligible
Spring is non-intrusive: objects in a Spring-enabled application don’t depend on Spring-specific classes
Inversion of Control (IoC)
Objects are passively given their dependencies instead of creating / looking for dependencies themselves
Promotes loose coupling of objects through Inversion of Control
JNDI in reverse: instead of an object looking for dependencies from the container, the container gives the dependencies to the
object at instantiation without waiting to be asked
Aspect-oriented
Spring has rich support for Aspect-oriented programming
Enables cohesive development by separating business logic from system services
Container
Spring is a container in the sense that it contains and manages the lifecycle and configuration of application objects
Configure the way objects are to be created – either create one single instance of your bean or produce a new instance every
time one is needed based on a configuration prototype
Framework
Spring makes it possible to configure and compose complex applications from simpler components, declaratively in XML
Provides infrastructure functionality (transaction management, persistence framework integration, etc) leaving the development
of application logic to us.
6. August 17, 2005 DEGT Realtime Apps
Spring Essentials
Introduction
Why Spring?
Architectural benefits
Why is Spring unique
Spring Essentials
Overview of the Spring framework
Inversion of control
Wiring Beans using the IoC Container
Creating Aspects
Spring in the Business Layer
Persistence Model
Transaction Management
Remoting
Spring in the Web Layer
Building the Web Layer
Summary
Spring Distilled
References
7. August 17, 2005 DEGT Realtime Apps
Overview
Spring’s Inversion of Control container
Enables sophisticated configuration management for POJOs.
Manages services for fine or coarse grained POJOs
Spring uses its AOP framework to
deliver important out-of-the-box services like declarative transaction
management.
implement custom code that would otherwise be scattered between
application classes.
Its data access abstraction
encourages a consistent approach to data access
provides a unique and powerful abstraction to implement it.
simplifies working with JDBC
Spring’s Transaction Management provides
consistent programming model in a wide range of environments
both declarative / programmatic approaches
It’s request-based MVC web framework
is more flexible, and
integrates seamlessly with the Spring IoC container.
Spring promotes Lightweight Remoting
Supports POJO-based remoting over a range of protocols
8. August 17, 2005 DEGT Realtime Apps
Inversion of Control
and Dependency Injection
Example 1
9. August 17, 2005 DEGT Realtime Apps
Inversion of Control
and Dependency Injection
Example 1
10. August 17, 2005 DEGT Realtime Apps
Inversion of Control
and Dependency Injection
Example 2
11. August 17, 2005 DEGT Realtime Apps
Benefits of Dependency Injection
Dependencies are explicit and evident in constructor or JavaBean properties
Because components don't need to look up collaborators at runtime, they're much simpler to write and maintain
The EJB equivalent would be a JNDI lookup, which requires the developer to write code that makes environmental assumptions.
Application code is much easier to test
JavaBean properties are simple, core Java and easy to test
A good IoC implementation preserves strong typing
Using IoC, framework is responsible for type casts.
Type mismatches will be raised as errors when the framework configures the application. No class cast exceptions in code
Most business objects don't depend on IoC container APIs.
Spring’s IoC container isn't invasive: using it won't invade your code with dependency on its APIs.
12. August 17, 2005 DEGT Realtime Apps
Spring’s IoC Container
Two types of containers
BeanFactory
Create and dispense beans
create associations between collaborating objects as they are instantiated
when a bean factory hands out objects, those objects are fully configured, are aware of their collaborating objects, and are
ready to use
a bean factory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods, if those
methods are defined.
Singletons are lazy loaded, deferring bean creation until getBean() is called
ApplicationContext provides application framework services such as
the ability to resolve textual messages from a properties file and
the ability to publish application events to interested event listeners.
A generic way to load file resources, such as images
A bit smarter and pre-loads all Singletons upon context loadup – thus, app wont have to wait for them to be created.
14. August 17, 2005 DEGT Realtime Apps
Beans Lifecycle in the IoC Container
Instantiation
The container finds the bean’s definition and instantiates
the bean.
Using dependency injection, Spring populates all of the
properties as specified in the bean definition.
If the bean implements the BeanNameAware interface,
the factory calls setBeanName() passing the bean’s ID.
If the bean implements the BeanFactoryAware interface,
the factory calls setBeanFactory(), passing an instance of
itself.
If there are any BeanPostProcessors associated with the
bean, their post-ProcessBeforeInitialization () methods will
be called.
If an init-method is specified for the bean, it will be called.
Finally, if there are any BeanPostProcessors associated
with the bean, their postProcessAfterInitialization()
methods will be called.
Removal
If the bean implements the DisposableBean interface, the
destroy() method is called.
If a custom destroy-method is specified, it will be called.
15. August 17, 2005 DEGT Realtime Apps
Creating Aspects
View the system as a series of
multiple (and usually crosscutting)
concerns
Business Logic
Transaction Management
Performance
Security
Persistence
Logging
Debugging
Introduction to AOP
Aspect
JoinPoint
Advice
PointCut
Introduction
Target
Proxy
Weaving
16. August 17, 2005 DEGT Realtime Apps
Example of AOP
Possible Issues with this code
What if we add more methods requiring
exception logging?
We need a distinct catch block for every
checked exception subclass
What if business requirements change, so that
exception notification is not required, or a
completely different strategy is required?
Impact
Issues are likely to be magnified many times,
as the exception notification policy will need to
be enforced across the entire code base
Serious problem for code quality and
maintainability, which pure OO cannot resolve.
17. August 17, 2005 DEGT Realtime Apps
An example of AOP
Create an “aspect class” that implements the exception
notification policy:
Apply this advice to multiple objects.
As normal practice, define the advice itself as an object
in a Spring IoC, using Dependency Injection
Apply the advice to any number of other objects
managed by the Spring container
Remove crosscutting code in the AccountManagerImpl
concerned with exception notification
Aspect Class
AppContext.xml
18. August 17, 2005 DEGT Realtime Apps
Spring in the Business Layer
Introduction
Why Spring?
Architectural benefits
Why is Spring unique
Spring Essentials
Overview of the Spring framework
Inversion of control
Wiring Beans using the IoC Container
Creating Aspects
Spring in the Business Layer
Persistence Model
Transaction Management
Remoting
Spring in the Web Layer
Building the Web Layer
Summary
Spring Distilled
References
19. August 17, 2005 DEGT Realtime Apps
Persistence Model
Spring’s DAO Philosophy
Data Access Object - DAOs exist to provide a
means to read and write data to the database
Expose this through the interface
Can be easily tested
Data access tier is accessed in a
technology-agnostic manner
Consistent DAO Support
Templates and Callbacks
Spring provides a single DataAccessException
This is a runtime exception. Thus, clients are not
forced to handle them
Spring classifies the exceptions into more
meaningful abstractions.
Spring provides integration with JDO, and ORM
frameworks like Hibernate, Apache OJB, and iBATIS
SQL Maps.
Spring’s support for each of these technologies is not
as extensive as its JDBC support.
With the ORM tool doing most of the actual persistence,
Spring provides integration points to these frameworks,
Integrated transaction management
Exception handling
Thread-safe, lightweight template classes
Convenience support classes
Resource management
20. August 17, 2005 DEGT Realtime Apps
Persistence Model (JDBC)
Main aim of Spring’s JDBC framework is
leverage the features of JDBC that work well
and to abstract away problem areas such as
Connection and exception handling.
Uses the Exception classification mentioned before
to translate SQLExceptions into more meaningful
exceptions
Spring’s JDBC framework cleans up JDBC code by
handling resource management and error handling
Leaves us free to manage the queries and writing
statements
Spring’s Data access framework incorporates a
Template class – JDBCTemplate
22. August 17, 2005 DEGT Realtime Apps
Persistence Model
Benefits of Spring’s persistent model :
O/R mapping integration
Spring integrates out of the box with Hibernate, JDO, TopLink and other ORM products.
Session management.
Spring can transparently create and bind a Hibernate / TopLink session to the current thread, using either a declarative, AOP
method interceptor approach, or by using an explicit, "template" wrapper class at the Java code level.
Resource management.
Spring application contexts can handle the location and configuration of Hibernate SessionFactories, JDBC datasources, and
other related resources.
Integrated transaction management.
Spring allows you to wrap your ORM code with either a declarative, AOP method interceptor, or an explicit 'template' wrapper
class at the Java code level.
Its possible to use and swap various transaction managers, without ORM-related code being affected.
Exception wrapping, as described above.
Spring’s DataAccessException
To avoid vendor lock-in.
Spring's abstraction of Transactions and Exceptions, along with its IoC approach allow ease of swapping various mapper / DAO
objects implementing data-access functionality,
Ease of testing.
Spring's inversion of control approach makes it easy to isolate and test each piece of persistence-related code in isolation.
23. August 17, 2005 DEGT Realtime Apps
Transaction Management
Spring’s Transaction Management model
Abstracts away transaction implementation from transaction code
Does not need a JTA implementation unless a transaction requirement spans multiple resources (in
which case it can support distributed (XA) transactions using a third party JTA implementation)
Uses the transactional support offered by the persistence mechanism for Apps using only a single
persistent resource.
Makes it easy to reconfigure Spring to use JTA / JDBC / Hibernate transaction strategies.
Note: this is a configuration change, and not a code change!
Enables us to write applications that can scale down as well as up
Spring’s Transaction Managers act as a façade to platform-specific transaction implementations
24. August 17, 2005 DEGT Realtime Apps
Transaction Management
Transaction Managers
Spring does not manage transactions.
Instead it delegates responsibility for transaction management to a platform-specific
transaction implementation provided by either JTA or the persistence mechanism.
Can be enabled by just wiring it up in the Spring container
25. August 17, 2005 DEGT Realtime Apps
Transaction Management
Spring has two approaches to Transaction Management
Programmatic approach
Complete control over transaction code (fine-
grained control)
Intrusive and invasive
Not typically used
Declarative Approach
Decouples an operation from its transaction rules
Spring’s declarative transactions go beyond
CMT’s by defining two addtional transaction
attributes - isolation levels and timeouts.
Very convenient
J2EE provides CMT for EJBs, but Spring
expands on this by providing its own version for
POJOs.
Same basic features as CMT, but with more fine-
grained control on when the transactions can be
rolled back
Significant feature of Spring because no longer
need to use complex and heavy weight EJBs just
to use atomic transactions
Implemented using the AOP framework and the
TransactionProxyFactoryBean (designed for
declarative transactions
27. August 17, 2005 DEGT Realtime Apps
Remoting
Remoting
A conversation between a client application and a
service
Spring’s Remoting model
Spring supports remoting for five RPC models
28. August 17, 2005 DEGT Realtime Apps
Spring’s Remoting model
Services can be configured into the app as Spring-managed beans
Spring’s proxy handles java.rmi.RemoteException and rethrows it as an unchecked
org.springframework.remoting.RemoteAccessException.
Optional for the client to handle, because its rare that anything can be done about the exception itself
On the service side, the functionality of any Spring- managed bean can be exposed as a remote service using
any of the models in listed in table (except for EJB and JAX-RPC)
Working with remote services in Spring is purely a matter of configuration
You won’t have to write any Java code to support remoting.
Your service beans don’t have to be aware that they are involved in an RPC (although any beans passed
to or returned from remote calls may need to implement java.io.Serializable).
Remote Services are proxied, so they can be
wired into client code as a regular bean
Spring-managed beans can be exported as
remote services using RemoteExporter
29. August 17, 2005 DEGT Realtime Apps
Remoting (Spring & RMI)
Issues with writing a service using traditional RMI
The payServiceURL will need to be set to the address for the service
Clients will need to call the lookupPaymentService () every time to get a
reference to the service
The lookupPaymentService() is a direct violation of the Inversion of
Control as the client is aware of where the service is located and also that
it is an RMI service
Traditional RMI lookups could throw either RemoteException,
NotBoundException, MalformedURLException) that must be handled.
Handling the MalformedURLException would probably result in
recompiling and reconfiguring the code
No try / catch block can recover from it gracefully, so why be
forced to handle it anyway
30. August 17, 2005 DEGT Realtime Apps
Spring and RMI
Using Spring, we can rewrite / reconfigure the service:
• Define the PaymentService as a Spring-managed bean.
•This enables us to wire it as a collaborator into another bean just as any
other nonremote bean.
• What’s great about accessing an RMI service in this way is that
StudentServiceImpl doesn’t even know that it’s dealing with an RMI
service.
• It simply receives a PaymentService object via injection, without any
concern for where it comes from.
• The proxy catches any RemoteExceptions that may be thrown by the service and
rethrows them as runtime exceptions so that it can be safely ignored.
•This makes it possible to swap out the remote service bean with another
implementation of the service—perhaps a different remote service or
maybe a mock implementation used when unit-testing.
31. August 17, 2005 DEGT Realtime Apps
Spring in the Web Layer
Introduction
Why Spring?
Architectural benefits
Why is Spring unique
Spring Essentials
Overview of the Spring framework
Inversion of control
Wiring Beans using the IoC Container
Creating Aspects
Spring in the Business Layer
Persistence Model
Transaction Management
Remoting
Spring in the Web Layer
Building the Web Layer
Summary
Spring Distilled
References
32. August 17, 2005 DEGT Realtime Apps
Building the Web Layer
A basic overview of how a request is processed in Spring MVC
DispatcherServlet receives a request whose URL pattern
is “/home.htm”.
DispatcherServlet consults BeanNameUrlHandlerMapping
to find a controller whose bean name is “/home.htm”,
finding the HomeController bean.
DispatcherServlet dispatches the request to
HomeController for processing.
HomeController returns a ModelAndView object with a
logical view name of home.
DispatcherServlet consults its view resolver (configured as
InternalResourceViewResolver) to find a view whose
logical name is home. Internal-ResourceViewResolver
returns the path to /WEB-INF/jsp/home.jsp.
DispatcherServlet forwards the request to the JSP at
/WEB-INF/jsp/home.jsp to render the home page to the
user.
The following list of steps defines the bare minimum that you
must do to build the homepage in Spring MVC:
Write the controller class that performs the logic behind
the homepage.
Configure the controller in the DispatcherServlet’s context
configuration file (training-servlet.xml).
Configure a view resolver to tie the controller to the JSP.
Write the JSP that will render the homepage to the user.
33. August 17, 2005 DEGT Realtime Apps
Summary
Introduction
Why Spring?
Architectural benefits
Why is Spring unique
Spring Essentials
Overview of the Spring framework
Inversion of control
Wiring Beans using the IoC Container
Creating Aspects
Spring in the Business Layer
Persistence Model
Transaction Management
Remoting
Spring in the Web Layer
Building the Web Layer
Summary
Spring Distilled
References
34. August 17, 2005 DEGT Realtime Apps
Key Spring Values
Spring's main aim is to make J2EE easier to use and promote good programming practice.
It does this by enabling a POJO-based programming model that is applicable in a wide range of environments.
Spring does not reinvent the wheel.
Despite its broad scope, Spring does not introduce its own solution in areas such as O/R mapping where there are already good
solutions. Similarly, it does not implement its own logging abstraction, connection pool, distributed transaction coordinator, remoting
protocols, or other system services that are already well-served in other products or application servers.
Spring promotes architectural choice at each layer.
While Spring provides an architectural backbone, Spring aims to facilitate replaceability of each layer.
Spring does aim to make existing technologies easier to use.
For example, although we are not in the business of low-level transaction coordination, we do provide an abstraction layer over JTA or
any other transaction strategy.
Spring doesn't directly compete with other open source projects unless it provides something new.
Spring is portable between application servers.
Avoids anything platform-specific or non-standard in the developer's view, and supports users on WebLogic, Tomcat, Resin, JBoss,
Jetty, Geronimo, WebSphere and other application servers.
Spring's non-invasive, POJO, approach takes advantage of environment-specific features without sacrificing portability.
Spring is a non-invasive framework.
Migration to future versions of Spring is easier.
Spring provides a consistent programming model, usable in any environment.
Provides an option to let many web applications running on a web container such as Tomcat or Jetty, instead of on expensive, high-
end, application servers.
Spring provides a programming model that makes code less dependent on its runtime context.
Spring aims to promote code reuse.
Spring enables you to defer architectural choices, potentially delivering benefits such as the need to purchase an application server
license only when you know exactly what your platform requirements are, following tests of throughput and scalability.
Spring aims to facilitate good programming practice, such as programming to interfaces, rather than classes.
Spring Apps are easy to test
35. August 17, 2005 DEGT Realtime Apps
References
Books
J2EE Design and Development
Rod Johnson
J2EE Design and Development without EJBs
Rod Johnson
Professional Java Development with the Spring Framework
Rod Johnson, et al.
Spring in Action
Craig Walls, Ryan Breidenbach
Introduction to the Spring Framework
www.theserverside.com/articles/article.tss?l=SpringFramework
www.springframework.org