Title: Spring: Whats it all about
1SpringWhats it all about?
2Topics
- Aims of Spring
- Enabling technologies
- Core Spring modules
- Common concepts
- Spring architectures
- What's next?
- The Spring community
3Aims of Spring
- Starting goal of Spring (from 2002) was to help
to reduce the complexity of J2EE development - To provide simplification without sacrificing
power - To facilitate best practices that were otherwise
difficult to follow - Simple things should be simple and complex things
should be possible - Alan Kay
- Unless simple things are simple, complex things
are impossible
4Aims of Spring
- Solidity of core abstractions has since seem
Spring demonstrate value in a wide range of
environments - Strategic adoption in many enterprises moving
away from traditional costly, inefficient J2EE
approaches
5Aims of Spring Technical
- Enable applications to be coded from POJOs
- Offer sophisticated configuration capabilities
that scale to real-world complexity - Allow enterprise services to be applied to those
POJOs in a declarative, non-invasive way - Examples
- POJOs can be made transactional without the need
to know about transaction APIs - POJOs can be exposed for management via JMX
without the need to implement an MBean interface
6POJO development
- POJO stands for Plain Old Java Object
- A POJO is not bound to any environment
- No imports of classes that bind it to a specific
environment - Only uses framework classes that offer good
abstraction like Springs persistence framework - Not dependent on a particular lookup mechanism
- Collaborating instances are injected using plain
Java constructors or setter methods - True POJOs are testable in isolation
7Applying services to POJOs declaratively
- Decouples your application objects from their
environment - Brings leverage, enables reuse
- Actually more powerful than traditional invasive
component models - Lets you scale up or down without rewriting
application code - Examples
- Switch to global transactions over JTA
- Export your business objects in different
environments - Switch between SLSB, web service, write/take from
JavaSpace etc.
8Enabling technologies The Spring Triangle
Power to the POJO
Portable service abstractions
AOP
IOC
9Core Spring modules
- Core Lightweight Container
- The heart of Spring
- Aspect-Oriented Programming (AOP) framework
- Modularizes behavior that would otherwise be
scattered through different methods - Decorates your POJOs with cross-cutting behavior
in a transparent manner
10The Core Lightweight Container
- Facilitates
- Full-stack POJO-based application development
- Within any environment
- Servlet, Portlet, EJB, Integration Test,
Standalone, Rich Client - By providing
- A powerful object factory that manages the
instantiation, configuration, decoration, and
assembly of your business objects
11The Spring Container in Action
- As a sophisticated object factory
Your Business Objects (POJOs)
The Spring Lightweight Container
Configuration Metadata
produces
Magic Happens Here
Fully configured system Ready for Use
12Key architectural enablers
- Lets you view your application as a set of
components - Each component is a POJO focused on solving your
domain problem - Each component is testable in isolation
- Each component has minimal dependencies
- And dependencies can be easily mocked
- The container manages the glue code required
for component configuration and assembly - The container leverages advanced techniques for
decorating your components at runtime
13Realized benefits
- Portability
- Your core business logic is implemented once and
runs anywhere - Leverage
- Your core code is decoupled from volatile
infrastructure - Business logic represents key asset
- Should have a long life
- Consistency
- Common configuration strategy everywhere
- Productivity
- Enables parallel, test-driven development
- Dont need to reinvent your own infrastructure
14(No Transcript)
15Core Spring Modules (continued)
- Next set of core modules are Java/J2EE support
libraries focused on developer ease-of-use - Build on lower-level APIs like JDBC and JTA to
- Capture best practice usage
- Eliminate boilerplate code
- Provide consistency
- Provide choice
- Spring is not monolithic
- You use just what you need
16Spring modules (2)
- Data access abstraction
- Enables consistent architectural approach to data
access - Delivers on JDBC simplification
- Integrates with all leading O/R mapping
frameworks - Transaction management abstraction
- Supports global transactions over JTA (managed
by an application server) - Supports local transactions over a single data
source (with JDBC, Hibernate, JDO, OJB or custom
data access API)
17Spring modules (3)
- Lightweight remoting
- POJO-based remoting over a range of protocols
- Includes support for RMI, IIOP, Hessian, Burlap,
Axis, and other web services protocols - JMX support
- Supports JMX-enabled management of your
application objects
18Spring modules (4)
- JMS support
- Provides support for sending and receiving JMS
messages in a much simpler way than provided
through standard J2EE. - Comprehensive testing strategy for application
developers - Dependency Injection facilitates unit testing
- Unique solution for integration testing outside
an application server
19Spring modules (5)
- MVC web framework
- Request-based MVC web framework
- Event-driven Web Flow framework
- All other Spring features can also be used with
other web frameworks such as Struts or JSF - Integration
- Spring is an increasingly important integration
technology - Quartz (Spring)
- Jasper Reports (Spring)
- OSWorkflow / XFire / Cayenne (other project)
- Provides a strong, general component model
- Core concepts applicable in many areas
20Common concepts
- IOC / Dependency Injection
- AOP
- The template pattern
- Exception hierarchies
21Dependency Injection
- A specialization of Inversion of Control
- A Dependency Injection container manages
application objects, taking care of wiring (how
objects locate collaborators) - Container instantiates objects and injects
dependencies on collaborating objects and
configuration properties through Java methods - Hollywood Principle
- Dont call me, Ill call you
22Setter Injection
- public class ServiceImpl implements Service
- private int timeout
- private AccountDao accountDao
- public void setTimeout(int timeout)
- this.timeout timeout
-
- public void setAccountDao(AccountDao
accountDao) - this.accountDao accountDao
-
- // Business methods from Service
-
- ltbean id"service" class"com.mycompany.service.Se
rviceImpl"gt - ltproperty name"accountDao" ref"accountDao"/gt
- ltproperty name"timeout" value"30" /gt
- lt/beangt
23Constructor Injection
- public class ServiceImpl implements Service
- private int timeout
- private AccountDao accountDao
- public ServiceImpl(int timeout, AccountDao
accountDao) - this.timeout timeout
- this.accountDao accountDao
-
- // Business methods from Service
- ltbean id"service" class"com.mycompany.service.Se
rviceImpl"gt - ltconstructor-arg value"30" /gt
- ltconstructor-arg ref"accountDao" /gt
- lt/beangt
24Dependency Injection Summary
- Dependencies are expressed in pure Java
- Push configuration (container injects
dependencies) is much better than pull
configuration (objects look up dependencies) - No ad hoc lookup
- Code is self-documenting, describing its own
dependencies - Can apply consistent management strategy
everywhere - Easy to test
- No JNDI to stub, properties files to substitute,
RDBMS data to set up
25Dependency Injection in Practice
- Simple (configuration) or object properties
- Configuration (timeout)
- Dependencies on collaborators (accountDao)
- Configuration properties are also important
- Can run many existing classes unchanged
- Autowiring
- Trivial to test or reuse application classes
outside the container - Value adds such as hot swapping, instance pooling
(with AOP)
26Dependency Injection in Practice
- public class MyClient
- public void setWeatherService(WeatherService
ws) - this.weatherService ws
-
- ...
- ltbean id"weatherService"
- class"spring...SimpleRemoteStatelessSessionProxy
FactoryBean" gt - ltproperty name"businessInterface"
- value"...WeatherService" /gt
- ltproperty name"jndiName" value"ejb/weatherSer
vice" /gt - lt/beangt
- ltbean id"myClient" class"...MyClient"
- autowire"autodetect" /gt
27Switch to Local POJO
- ltbean id"weatherService"
- class"...DefaultWeatherService"gt
- ltproperty name"countryCode"
- value"1" /gt
- ltproperty name"dataSource"
- ref"dataSource" /gt
- lt/beangt
- Change to a single bean definition
- No change to Java code
28Switch to Web Service
- ltbean id"weatherService" classspring...HessianP
roxyFactoryBean"gt - ltproperty name"serviceUrl"
- value " http//server8080/weather" /gt
- ltproperty name"businessInterface"
- value"...WeatherService" /gt
- lt/beangt
- Again, change is localized
- Callers simply work with the business interface
- Zero plumbing code
29Implications for testability
- public void testForMyClient()
- MyClient mc new MyClient()
- mc.setWeatherService(myMockService)
- // Test mc
-
- Imagine how much harder testing would be if we
hadnt use DI to factor out the JNDI lookup and
EJB API calls
30Advanced Dependency Injection
- Management of lists, maps or sets, with arbitrary
nesting - Creation of objects using new or from factory
methods - Object instances can be shared or non-singleton
(per user) - Method Injection
- Container can override abstract or concrete
methods at runtime - Can use to avoid dependence on Spring container
- Override moves dependency on Spring API from code
to configuration - Nearly any existing Java object can be used in a
Spring context - Leverages standard JavaBeans PropertyEditor
machinery - Register custom property editors
- Many hooks to customize container behaviour
31Why AOP?
- Dependency Injection takes us a long way, but is
not quite enough on its own - AOP complements IoC to deliver a non-invasive
framework - Externalizes crosscutting concerns from
application code - Concerns that cut across the structure of an
object model - Objects in the account
- AOP offers a different way of thinking about
program structure to an object hierarchy
32Why Not Just Interception?
- EJB 2 interception is conceptually similar in
some ways, but not extensible and imposes too
many constraints on components - Cant define new aspects
- No real pointcut model
- Methods on the component interface, with basic
wildcarding - Definition required per EJB
- EJB 3 interception is an improvement compared to
EJB 2, but is essentially 2003-vintage, "AOP
lite" technology - Still no real pointcut model
- Every method or class (via annotation or
corresponding XML deployment descriptor) needs to
be changed to define new crosscutting behaviour - Fails to deliver a new structural way of thinking
- Fails to achieve core goal of AOP of preventing
crosscutting - You still need to go and change in many places to
make one logical change (such as introduce
auditing) - Concerns pile up as you have more and more
annotations or interceptor definitions - Maintainability issues likely
- Classes know about the interceptors that apply to
them - Wrong way around
33AOP is More than Interception
- Interception is an implementation strategy for
AOP - It is not a complete conceptual model of AOP
- Spring 2.0 aligns on AspectJ semantics
- (but of course is still wholly backward
compatible) - Allows far more sophisticated constructs
- Pointcuts are a first-class construct
- Allows option of compiling aspects or using
AspectJ load-time weaving, preserving the same
programming model - Again, no conflict between simplicity and power
- Less powerful, less general mechanisms are
simplistic, rather than simple
34AOP Example Introduction
- _at_Aspect
- public class MakeLockable
-
- _at_DeclareParents(value "com.ourbank.swaps.servic
e..", - defaultImplDefaultLockable.class)
- public static Lockable mixin
-
- _at_Before(value"execution(void set())
this(mixin)", argNames"mixin") - public void checkNotLocked(
- Lockable mixin) // Bind to arg
- if (mixin.locked())
- throw new IllegalStateException()
-
-
-
35How does an interceptor chain work?
Control flows back through interceptor chain to
return result to caller
Caller invokes proxy, not target
Proxy invokes interceptors
Forward processing of interceptor chain concludes
with invocation of method on target object
36AOP
- Using a pointcut we can apply this advice to many
methods - Code that would otherwise appear in many places
appears just once - Modularization avoids duplication and helps
maintainability - Integration of DI and AOP allows aspects to be
configured by Dependency Injection
37How are pointcuts expressed?
- Spring provides a Java interface and a number of
convenient implementations - Often use a pointcut expression language to
express pointcuts in String form - In Spring 2.0, the recommend pointcut expression
language is AspectJs - Also can use _at_AspectJ annotation syntax
- Pointcuts provide the real innovation of AOP
38Usages of AOP
- Out-of-the box aspects
- Declarative transaction management for POJOs
- Acegi Security for Spring
- Spring remoting (built on AOP)
- Custom aspects
- Auditing
- Exception handling
- Performance monitoring
-
39Common concepts
- IOC / Dependency Injection
- AOP
- The template pattern
- Exception hierarchies
40The Template Pattern
- Another form of Inversion of Control
- Moves control into the framework through a
callback - Solves problems common to many APIs
- Resource acquisition/release
- Exception translation
- Provides convenience methods for many APIs
- Avoid the evil TCFTC
- try/catch/finally try/catch
41Templates in a nutshell
- int userCount
- jdbcTemplate.queryForInt(
- "SELECT COUNT(0) FROM USER")
- Where is connection acquired and released?
- What happens in event of exceptions?
- Enables developer to focus on expressing intent
(in this case, SQL)
42Templates (2)
- public Collection findRequestsEligibleForReminder(
) - throws DataAccessException
- return getJdbcTemplate().query(
- "SELECT NAME, DATE, ...
- FROM REQUEST WHERE ORIGINATOR Rod",
- new RowMapper()
- public Object mapRow(
- ResultSet rs, int
rowNum)
- throws SQLException
- Request r new Request()
- r.setName(rs.getString("NAME"))
- r.setDate(rs.getDate("DATE"))
- return r
-
- )
-
Callback
Compiler picks up errors
43Templates add value to
- JDBC
- TopLink / Hibernate / JDO / other ORM
- JMS
- JavaMail
- JNDI
-
- Powerful concept leveraged consistently for many
APIs
44Templates work with Spring exception hierarchies
(1)
- Framework exceptions like SQLException are
translated to a common exception hierarchy. - Provides context information for debugging
- Keeps stack trace intact
- Translation mechanism is configurable and
extensible - Converts checked exceptions into unchecked
exceptions - Catching checked framework exceptions doesnt add
value, errors are usually unrecoverable - Same exception hierarchy regardless of framework
you choose - Data access exception hierarchy is the same for
all persistence tools (JDBC, Hibernate, JDO, )
45Templates work with Spring exception hierarchies
(2)
DataRetrievalFailureException
46Spring-based architectures (1)
- Adopt a layered architecture
- Layering is typically logical
- May not be physical
- Fowlers First Law of Distributed Objects
- Dont distribute your objects
- If you need distribution, see Spring Remoting
47Spring-based architectures (2)
Views JSP, Velocity,
Endpoints for remote clients SOAP, RMI,
Remote exporters
Presentation tier
Java MVC controllers
Middle tier definitions
Spring AOP AspectJ features
Transactional boundaries
Remote clients
Service objects / Business Facades (analogous to
SLSBs)
Domain objects
Spring web-tier context
DAO interfaces
DAO implementations
Spring DAO
RDBMS
JDBC/ ORM
48Spring-based architectures (3)
- Lightweight Container Architecture
- J2EE without EJB (Johnson/Hoeller, 2004)
- Spring is designed to allow choice
- Can reuse classes from each layer in different
architectures - Dependency Injection / AOP available within each
layer as well as between architectural layers
49Working with Spring
- No need to code for Dependency Injection
- Follow good OO practice
- The container exists to make the right thing easy
to do - Merely avoid working against the container
- Ask not what you can do for your IoC container,
ask what your IoC container can do for you
50Spring is not about
- Replacing J2EE services
- Provides a good alternative to EJB component
model in most cases - J2EE ! EJB
- Throwing away your legacy code
- Can introduce Spring incrementally
- Introduce Spring to address pain points
- Can use Spring to simplify EJB-based projects
51Spring is about
- Spring is about POJOs
- The most complete realisation of the now
universally accepted goal of POJO-based
development - Spring is about reuse
- Spring is about choice
- Spring enables you to make choices
- Spring offers something whatever your
environment, from Java 1.3 and above - Spring is about consistency
- Spring enables you to focus on your business
domain - Question code that does not relate to your domain
52Where Next Spring 2.0
- March 2006
- Now at 2.0 M2
- Themes
- Simplicity
- Make things easier to do
- Power
- Make more things possible
- 100 backward compatible
- Contrast to traditional frameworks and
specifications
53Many enhancements and new features
- Closer AspectJ integration
- Spring allows use of AspectJ pointcut expression
language in Spring's own AOP framework - Can even use _at_AspectJ aspects in Spring AOP, with
a proxy-based runtime - Spring AOP AspectJ together provide a solution
for all AOP requirements, from conservative
adopters to power users - XML configuration extensibility mechanism
- Ability to define new XML tags in additional to
Spring's generic tags - Uses XSD, amenable to tooling
- Used in the framework to simplify common tasks
- Allows large users and third parties to build
libraries of tags to simplify common tasks
54Spring 2.0 Enhancements (2)
- Additional scoping options for beans
- Backed by HttpSession etc.
- Pluggable backing store
- Not tied to web tier
- Used by Sony (major Spring users)
- Customizable task execution framework for
asynchronous task execution - CommonJ TimerManager implementation
- Great for WebLogic/Websphere users
- Portlet MVC framework
55Spring 2.0 Enhancements (3)
- Message-driven POJOs
- Support for asynchronous reception of JMS
messages - Full support for XA-transactional receive
- Usual Spring value proposition
- Works in J2EE and J2SE
- Closes off one of the remaining corner cases
justifying EJB usage - Ability to define any Spring bean in one of a
number of scripting languages - Groovy
- JRuby
-
56And Beyond
- Spring 2.1
- Further features for manageability in large
customers - Additional configuration management options,
backed by database and Java code - Allow cluster-wide reconfiguration in real time
- OSGi integration
- Exploring potential for versioning, hot redeploy
etc
57Adopting Spring Common Scenarios
- Servlet application
- Improve architecture
- Introduce more structure to middle tier
- Establisher cleaner separation between web tier
and middle tier - Introduce comprehensive solution for transaction
management - Programmatic and declarative transaction
management without EJB - Facilitate testing
- Testing demo
- Configure Struts actions or other web tier
objects using Dependency Injection - Offer portable programming model
- No need to rework existing code to migrate to an
application server
58Adopting Spring
- Existing EJB application
- Eliminate client-side Service Locators and
Business Delegates - Less code to write
- Client code is much easier to test, decoupled
from EJB API - Simplify implementation and testing of EJBs by
facilitating delegation to POJOs behind EJB
façade - Support super classes for EJBs
- Simplify data access
- First step
- Replace entity beans with ORM solution
59Adopting Spring
- All application types
- Dramatic simplification of JDBC and other data
access code - Increase portability between environments
- Application server
- Web container
- Integration test
- Facilitate unit testing and parameterization of
code - Allow easy addition of management capability
60Project Information
61The Spring Community
- Apache 2.0 License
- Liberal, non-viral, commercially friendly license
- 28 developers
- 10,000 users registered on Spring mailing lists
and forums, and growing rapidly - Many more regularly use forums as guests
- Helpful, courteous community
- Numerous books, and more coming out
- Best are
- Professional Spring Development (Wrox)
- Pro Spring (Rob Harrop)
62Interface21 and Spring
- Interface21 is devoted to offering Spring
services from the source - 20 employees and growing rapidly
- Offices in UK, US and Europe
- 9 most active Spring developers employed by
Interface21, including project leads of Spring
(Rod Johnson, Juergen Hoeller) and AspectJ
(Adrian Colyer)
63Interface21 Key Individuals
- Rod Johnson (UK)
- Spring founder
- Juergen Hoeller (Austria)
- Co-lead of Spring
- Lead developer of Spring
- Rob Harrop (UK)
- Core Spring developer
- Active member of JMX expert group
- Adrian Colyer (UK)
- AspectJ lead
- The leading AOP practitioner
- Now also an active Spring developer
- Keith Donald (US)
- Core Spring developer
- Founder, Spring Web Flow
- Colin Sampaleanu (Canada)
- Core Spring developer
- North American business manager
64Interface21 Services
- Training
- Public and onsite training
- Professional services
- Mentoring
- Architecture reviews
- Commercial support
- Direct or in partnership with other vendors
- Why is this more than just a plug?
- Because successful open source projects need a
viable economic model behind them, as well as a
flourishing community - Spring has both
65Business Partnerships
- Spring is naturally agnostic as to environment
and, hence, application servers - Thus both Spring and Interface21 are well placed
to partner with major industry players - Increases project viability
- Safeguards your investment in Spring
- Recent partnerships
- BEA
- Promising discussions with Oracle around
integration with Oracle middleware products - The Geronimo kernel is likely to be rearchitected
on Spring - More on the way