Professional Documents
Culture Documents
Introduction To The Spring Framework: by Mumbai Academics
Introduction To The Spring Framework: by Mumbai Academics
Spring Framework
By Mumbai Academics
Advantages of Spring Framework Architecture
There are many advantages of Spring Framework. They are as
follows:
Lightweight: Spring framework is lightweight because of its
POJO implementation. The Spring Framework doesn't force
the programmer to inherit any class or implement any
interface. That is why it is said non-invasive, Enable you to
write powerful, scalable applications using POJOs.
Easy to develop JavaEE application: The Dependency
Injection feature of Spring Framework and it support to
various frameworks makes the easy development of JavaEE
application.
Easy to test: The Dependency Injection makes easier to
test the application. The EJB or Struts application require
server to run the application but Spring framework doesn't
require server.
Loose Coupling: The Spring applications are loosely
coupled because of dependency injection and handles
injecting dependent components without a component
knowing where they came from (IoC).
Powerful abstraction: It provides powerful abstraction to
JavaEE specifications such as JMS, JDBC, JPA and JTA.
Declarative support: It provides declarative support for
caching, validation, transactions and formatting.
Portable :can use server-side in web/ejb app, client-side in
swing app, business logic is completely portable.
Cross-cutting behavior : Resource Management is cross-
cutting concern, easy to copy-and-paste everywhere.
Configuration information: Spring provides one consistent
way of configuring everything, separate configuration from
application logic, varying configuration.
Lifecycle : Responsible for managing all your application
components, particularly those in the middle tier container
sees components through well-defined lifecycle: init(),
destroy()
Spring
A popular and stable Java application framework for
enterprise development
Ubiquitous for Java development
Well established in enterprise Java apps
Time tested and proven reliable
A primary purpose is to reduce dependencies and
even introduce negative dependencies
Different from almost every other framework out
there
Part of the reason it has been adopted so quickly
Spring code base is proven to be well structured
(possibly the best)
139 packages
No dependency cycles
Spring
A lightweight framework that addresses each tier in a
Web application.
Presentation layer – An MVC framework that is most similar
to Struts but is more powerful and easy to use.
Business layer – Lightweight IoC container and AOP support
(including built in aspects)
Persistence layer – DAO template support for popular ORMs
and JDBC
Simplifies persistence frameworks and JDBC
Complimentary: Not a replacement for a persistence framework
Helps organize your middle tier and handle typical
J2EE plumbing problems.
Solutions to typical coding busywork
JDBC ,LDAP,Web Services
Reduces code and speeds up development
Current Version is 3.0
Spring (continued)
Do I have to use all components of Spring?
Spring is a non-invasive and portable framework that
allows you to introduce as much or as little as you
want to your application.
Promotes decoupling and reusability
POJO Based
Allows developers to focus more on reused business
logic and less on plumbing problems.
Reduces or alleviates code littering, ad hoc
singletons, factories, service locators and multiple
configuration files.
Removes common code issues like leaking
connections and more.
Built in aspects such as transaction management
Most business objects in Spring apps do not depend
on the Spring framework.
Why Did I choose Spring?
Introduced to Spring by way of Hibernate
Spring is an open source layered Java/J2EE
application framework
The Spring Framework is licensed under the terms of
the Apache License
Originally wanted Spring to provide a way to simplify
DAO objects and provide declarative transaction
support to our non-EJB applications.
Needed a solution to loosely couple business logic in
a POJO fashion.
Wanted to build portable applications that provided
clearer separation of presentation, business, and
persistence logic.
Easily integrated with our existing frameworks
Great documentation and community support
Spring Mission Statement
J2EE should be easier to use
It's best to program to interfaces, rather than classes. Spring
reduces the complexity cost of using interfaces to zero.
JavaBeans offer a great way of configuring applications
OO design is more important than any implementation
technology, such as J2EE
Checked exceptions are overused in Java. A framework
shouldn't force you to catch exceptions you're unlikely to be
able to recover from.
Testability is essential, and a framework such as Spring
should help make your code easier to test
Spring should be a pleasure to use
Your application code should not depend on Spring APIs
Spring should not compete with good existing solutions, but
should foster integration. (For example, JDO and Hibernate
are great O/R mapping solutions. Don't need to develop
another one).
Simplify your code with Spring
Enables you to stop polluting code
No more custom singleton objects
Beans are defined in a centralized configuration file
No more custom factory object to build and/or locate other
objects
DAO simplification
Consistent CRUD
Data access templates
No more copy-paste try/catch/finally blocks
No more passing Connection objects between methods
No more leaked connections
POJO Based
Refactoring experience with Spring
Caution Spring is addictive!
Modules of the Spring Framework
The Spring Framework can be considered as a collection
of frameworks-in-the-framework:
Core - Inversion of Control (IoC) and Dependency
Injection.
AOP :- These modules support aspect oriented
programming implementation where you can use Advices,
Pointcuts etc. to decouple the code.
DAO - Data Access Object support, transaction
management, JDBC-abstraction
ORM - Object Relational Mapping data access, integration
layers for JPA, JDO, Hibernate, and iBatis
MVC - Model-View-Controller implementation for web-
applications
Context-This module supports internationalization (I18N),
EJB,Remote Access, Authentication and Authorization,
Remote Management like RMI,HTTP Invoker,Hessain,
Messaging Framework, Web Services, Email, Testing, …
Modules of the Spring Framework
Expression Language:- It is an extension to the EL
defined in JSP. It provides support to setting and getting
property values, method invocation, accessing collections
and indexers, named variables, logical and arithmetic
operators, retrieval of objects by name etc.
Overview of the Spring Framework
<listener>
<listener-class>
org.springframework.web.context.ContextLoader
Listener
</listener-class>
</listener>
Configuring an XMLWebApplicationContext
<context-param>
<param-name>contextConfigLocation</param-
name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoader
Servlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
Spring AOP
Spring AOP
Framework that builds on the aopalliance interfaces.
Aspects are coded with pure Java code. You do not
need to learn pointcut query languages that are
available in other AOP implementations.
Separates the core business code from the aspects
we wrap around it: security, transaction management,
monitering,logging…
Spring aspects can be configured using its own IoC
container.
Objects obtained from the IoC container can be
transparently advised based on configuration
Spring AOP has built in aspects such as providing
transaction management, performance monitoring
and more for your beans
Spring AOP is not as robust as some other
implementations such as AspectJ.
However, it does support common aspect uses to solve
Spring AOP
Attempts to separate concerns, increase
modularity, and decrease redundancy
Separation of Concerns (SoC)
Break up features to minimize overlap
Don’t Repeat Yourself (DRY)
Minimize code duplication
Cross-Cutting Concerns
Program aspects that affect many others (e.g. logging)
AspectJ is the top AOP package
Spring AOP
Supports the following advices:
method before
method after returning
throws advice
around advice (uses AOPAlliance MethodInterceptor directly)
Spring allows you to chain together interceptors and
advice with precedence.
Aspects are weaved together at runtime. AspectJ uses
compile time weaving.
Spring AOP also includes advisors that contain advice
and pointcut filtering.
ProxyFactoryBean – sources AOP proxies from a Spring
BeanFactory
IoC + AOP is a great combination that is non-invasive
Through AOP, we add transversal functionalities to
objects (ie not directly related to the code it contains)
2. Spring principles: AOP
Without AOP
With AOP
2. Spring principles: AOP
Useful for automatic handling of transaction
with Hibernate
Useful for Acegi (automatic credentials
checking before executing some methods)
Code smaller, easier to read (not polluted
by transversal aspects not directly relevant)
Spring Database Components
Consistent Abstract Classes for DAO Support
Extend your DAO classes with the proper xxxDAOSupport class
that matches your persistence mechanism.
JdbcDaoSupport
Super class for JDBC data access objects.
Requires a DataSource to be set, providing a JdbcTemplate based
on it to subclasses.
HibernateDaoSupport
Super class for Hibernate data access objects.
Requires a SessionFactory to be set, providing a
HibernateTemplate based on it to subclasses.
JdoDaoSupport
Super class for JDO data access objects.
Requires a PersistenceManagerFactory to be set, providing a
JdoTemplate based on it to subclasses.
SqlMapDaoSupport
Supper class for iBATIS SqlMap data access object.
Requires a DataSource to be set, providing a SqlMapTemplate
Spring DAO Templates
Built in code templates that support JDBC, Hibernate,
JDO, and iBatis SQL Maps
Simplifies data access coding by reducing redundant
code and helps avoid common errors.
Alleviates opening and closing connections in your
DAO code.
No more ThreadLocal or passing Connection/Session
objects.
Transaction management is handled by a wired bean
You are dropped into the template with the resources
you need for data access – Session,
PreparedStatement, etc.
Code only needs to be implemented in callback
methods.
doInXXX(Object)
Optional separate JDBC framework
Ex: Code without a template
public class OrderHibernateDAO implements IOrderDAO {
public Order saveOrder(Order order) throws
OrderException{
Session s = null;
Transaction tx = null;
try{
s = ... // get a new Session object
tx = s.beginTransaction();
s.save(order);
tx.commit();
} catch (HibernateException he){
// log, rollback, and convert to OrderException
} catch (SQLException sqle){
// log, rollback, and convert to OrderException
} finally {
s.close(); // needs a try/catch block
}
return order;
}
Ex: Spring DAO Template Example
public class OrderHibernateDAO extends HibernateDaoSupport
implements IOrderDAO {
...
public Order saveOrder(final Order order) {
return (Order) getHibernateTemplate().execute(new
HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
session.save(order);
return order;
}
});
}
...
}
Consistent Exception Handling
Spring has it’s own exception handling hierarchy for DAO logic.
No more copy and pasting redundant exception logic!
Exceptions from JDBC, or a supported ORM, are wrapped up
into an appropriate, and consistent, DataAccessException and
thrown.
This allows you to decouple exceptions in your business logic.
These exceptions are treated as unchecked exceptions that you
can handle in your business tier if needed. No need to try/catch
in your DAO.
Define your own exception translation by subclassing classes
such as SQLErrorCodeSQLExceptionTranslator
Spring and Testing
Easier test driven development (TDD)
Integration testing
Can use a standalone Spring configuration
with mock objects for testing.
Consider XMLApplicationContext or
FileSystemApplicationContext.
Unit testing
Allows you to test outside the container
without using the Spring container.
Easy to test POJOs
Spring MVC Framework
MVC Framework
Clear separation of roles: controller, validator, form object,
Dispatch servlet, View resolver, …
Extensible and adaptable
Several views of a result (pdf, excel, html, …)
Can be wired (possible to use transparently the IoC pattern).
Spring Annotation Based Controllers
Spring 2.5 introduced support for annotation based MVC
controllers. @RequestMapping, @RequestParam,
@ModelAttribute are some of the annotations provided for this
implementation.
Can be used with other frameworks: JSF, Struts,
Tapestry, Webwork
Completely transparent: no need to change anything in
what is done by these other frameworks
Benefits of the Spring Web
MVC Framework
The Spring Web MVC Framework is a robust, flexible, and
well-designed framework for rapidly developing web
applications using the MVC design pattern.The benefits
achieved from using this Spring module are similar to
those you get from the rest of the Spring Framework
Easier testing—This is a common theme you will find
across all the Spring classes.The fact that most of Spring’s
classes are designed as JavaBeans enables you to inject
test data using the setter methods of these classes. Spring
also provides mock classes to simulate Java HTTP objects
(HttpServletRequest, for example), which makes unit
testing of the web layer much simpler.
Benefits of the Spring Web
MVC Framework
Bind directly to business objects—Spring MVC does not
require your business (model) classes to extend any
special classes; this enables you to reuse your business
objects by binding them directly to the HTML forms fields. In
fact, your controller classes are the only ones that are
required to extend Spring classes (or implement a Spring
controller interface).
Clear separation of roles—Spring MVC nicely separates
the roles played by the various components that make up
this web framework. For example, when we dis-cuss
concepts such as controllers, command objects, and
validators, you will begin to see how each component
plays a distinct role.
Benefits of the Spring Web
MVC Framework
Simple but powerful tag library—Spring's tag library is
small, straightforward, but powerful. For example. Spring
uses the JSP expression language (EL) for arguments
to the <spring :bind> tag.
Web Flow—This module is a subproject and is not bundled
with the Spring core distribution. It is built on top of Spring
MVC and adds the capability to easily write wizard like
web applications that span across several HTTP requests
(an online shopping cart, for example).
Benefits of the Spring Web
MVC Framework
View technologies and web frameworks—Although we
are using JSP as our view technology. Spring supports
odier view technologies as well, such as Apache Velocity
and FreeMarker.This is a powerful concept because
switching from JSP to Velocity is a matter of configura-
tion. Furthermore, Spring provides integration support for
Apache Struts.
■ Lighter-weight environment—As I mentioned in die
previous chapter. Spring enables you to build enterprise-
ready applications using FOJOs; the environment
setup can be simpler and less expensive because you
could develop and deploy your application using a lighter-
weight servlet container.
Features of Spring Web MVC
Spring's web module provides a wealth of unique web support
features, including:
Clear separation of roles - controller, validator, command
object, form object, model object, DispatcherServlet, handler
mapping, view resolver, etc. Each role can be fulfilled by a
specialized object.
Powerful and straightforward configuration of both framework
and application classes as JavaBeans, including easy
referencing across contexts, such as from web controllers to
business objects and validators.
Adaptability, non-intrusiveness. Use whatever controller
subclass you need (plain, command, form, wizard, multi-action,
or a custom one) for a given scenario instead of deriving from a
single controller for everything.
Reusable business code - no need for duplication. You can use
existing business objects as command or form objects instead of
mirroring them in order to extend a particular framework base
Features of Spring Web MVC