Spring framework goals

Document Sample
Spring framework goals Powered By Docstoc
					The Spring Framework   TM

        Rod Johnson
        Spring framework goals
• Make J2EE easier to use
• Address end-to-end requirements rather than one tier
• Eliminate need for middle tier ―glue‖
• Provide the best Inversion of Control solution
• Provide a pure Java AOP implementation, focused on
  solving common problems in J2EE
• Fully portable across application servers
    – Core container can run in any environment, not only a server
    – Works well in WebSphere
      …Spring framework goals
• ―Non-invasive” framework
    – Application code has minimal or no dependency on Spring APIs
    – Key principal seen throughout Spring’s design
    – More power to the POJO
• Facilitate unit testing
    – Allow effective TDD
    – Allow business objects to be unit tested outside the container
• Facilitate OO best practice
    – We’re used to implementing ―EJB‖ or ―J2EE‖ applications rather than
      OO applications.
    – It doesn’t have to be this way.
• Provide a good alternative to EJB for many applications
• Enhance productivity compared to “traditional” J2EE approaches
Part of a new wave of frameworks
• Big change in how J2EE applications are written
• Less emphasis on EJB
   – EJB has been overused: Often not appropriate
• Not just Spring: PicoContainer, HiveMind and other
  Inversion of Control frameworks
   – EJB 3.0 (2005) programming model looks a lot like
            (Spring IoC – features) + Hibernate
   – EJB still has some unique capabilities for a minority of apps
     (distributed transaction management, RMI remoting)
• These lightweight frameworks are different
• Spring is the most mature, most powerful and most
       Unique Spring capabilities
• Declarative transaction management for POJOs with or without EJB
• Consistent approach to data access, with common exception
     – Simplifies working with JDBC, Hibernate, JDO etc
•   Flexible MVC framework
•   IoC/AOP integration
•   Integration with a wide variety of popular products
•   Gestalt
     – More than the sum of its parts
     – Hard to explain in a snappy phrase, but our users love it
• Solid, robust, works now
• In production in mission-critical apps now
                     Spring focus
• Spring complements application servers like WebSphere
   – Spring comes out of the application space, rather than the server
• Spring avoids the need for costly in-house frameworks
   –   Can produce real savings
   –   Focus your developers on your domain
   –   Well-understood, generic, high-quality solution
   –   Facilitates testability, increase productivity
• Provides a simpler, yet powerful, alternative to the EJB
  component model in many applications
   – But also plays well with EJB if you prefer to stick with EJB
        A layered framework
• Web MVC
• AOP framework
  – Integrates with IoC
• IoC container
  – Dependency Injection
• Transaction management
• Data access
• One stop shop but can also use as modules
                Web MVC
• Most similar in design to Struts
  – Single shared Controller instance handles a
    particular request type
• Controllers, interceptors run in the IoC
  – Important distinguishing feature
  – Spring eats its own dog food
Web MVC: Advantages over Struts
• Allows multiple DispatcherServlets
  – More elegant than even Struts 1.1 solution
  – DispatcherServlets can share an ―application context‖
• More flexible
  – Interface not class-based
• Easier to customize
• Less tied to JSP
  – Velocity, Excel, PDF etc
  – Easy to implement custom Views
Web MVC: Advantages over Struts
• Cleaner MVC separation
  – Cleanly separates controller, model and view
  – Model is not tied to Servlet API or Spring API
• No need for custom ActionForms: can reuse
  domain objects or TOs
• Much easier to unit test web tier, because Spring
  uses interfaces, not classes
• Integrates with middle tier with zero custom
  – No more Service Locators or ad hoc Singletons
            Web tier integration
But I love WebWork/Tapestry/Struts/JSF/whatever
• The customer is always right
• We don’t dictate how to use Spring
   – You can preserve your investment (tools etc)
   – You can refactor to use what parts of Spring you need
• WebWork, Tapestry, Struts integration is seamless
• Support for JSF and Portlet development in Spring 1.1
   – JSF leaders (Ed Burns, David Geary) are working with us on
     Spring/JSF integration
        Spring in the Middle Tier
• Complete solution for managing business objects
   –   Write your business objects as POJOs
   –   Spring handles wiring and lookup
   –   Simple, consistent, XML format (commonest choice)
   –   But the IoC container is not tied to XML
• Application code has few dependencies on the
  container—often no dependencies on the container
   – Spring Pet Store has no dependencies on Spring IoC
   – No magic annotations for IoC: nothing Spring-specific
• Easy unit testing. TDD works!
      Spring in the Middle Tier
• The most complete IoC container
  – Setter Dependency Injection
      • Configuration via JavaBean properties
  – Constructor Dependency Injection
      • Configuration via constructor arguments
      • Pioneered by PicoContainer
  – Dependency Lookup
      • Avalon/EJB-style callbacks
  – I favour Setter Injection, but the Spring philosophy is that you
    make the choice
      • We are not ideological.
      • A good IoC container must provide sophisticated support for both
        injection models to allow use of legacy code
     Middle Tier: Setter 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

<bean id="service" class="com.mycompany.service.ServiceImpl">
   <property name="timeout"><value>30</value></property>
   <property name="accountDao"><ref local="accountDao"/></property>
 Middle Tier: Constructor 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

<bean id="service" class="com.mycompany.service.ServiceImpl">
   <constructor-arg><ref local="accountDao"/></constructor-arg>
Middle Tier: Dependency Injection
• Simple or object properties
    – Configuration (timeout)
    – Dependencies on collaborators (accountDao)
• Configuration properties are also important
• Can run many existing classes unchanged
• ―Autowiring‖
• Trivial to test application classes outside the container,
  without Spring
• Can reuse application classes outside the container
• Hot swapping, instance pooling (with AOP)
    Spring in the Middle Tier
• Advanced IoC features
  – Can manage lists, maps or sets, with arbitrary
  – Leverages standard JavaBeans
    PropertyEditor machinery
    • Register custom property editors
  – ―Post processors‖
                     Why AOP?
• AOP complements IoC to deliver a non-invasive
• Externalizes crosscutting concerns from application code
   – Concerns that cut across the structure of an object model
   – AOP offers a different way of thinking about program structure to
     an object hierarchy
• EJB interception is conceptually similar, but not
  extensible and imposes too many constraints on
• Spring provides important out-of-the box aspects
   – Declarative transaction management for any POJO
   – Pooling
   – Resource acquisition/release
 AOP + IoC: A unique synergy
• AOP + IoC is a match made in heaven
• Any object obtained from a Spring IoC
  container can be transparently advised
  based on configuration
• Advisors, pointcuts and advices can
  themselves be managed by the IoC
• Spring is an integrated, consistent solution
              Custom AOP
• Complements, rather then conflicts with,
  – Email administrator if a particular exception is
  – Apply custom declarative security checks
  – Performance monitoring
  – Auditing
  – Caching
          AspectJ integration
• Coming in Spring 1.1 (August)
• Particularly relevant to WebSphere users given
  IBM’s backing for AspectJ
• Integrates AspectJ aspects into Spring IoC
  – Configure and parameterize aspects in a consistent
• Will allow the use of the AspectJ pointcut
  expression language to target Spring advice
• Can mix Spring and AspectJ aspects within a
  consistent architectural model
                      Spring DAO
• Integrated with Spring transaction management
   – Unique synergy
   – Gestalt again…
• Doesn’t reinvent the wheel.
   – There are good solutions for O/R mapping, we make them easier to use
• Out-of-the-box support for
   –   JDBC
   –   Hibernate
   –   JDO
   –   iBATIS
• Model allows support for other technologies (TopLink etc)
• Consistent DataAccessException hierarchy allows truly
  technology-agnostic DAOs
        Spring DAO:
Consistent exception hierarchy
                 Spring DAO: JDBC
•   Class library offers simpler programming model than raw JDBC
     – Two flavours of usage:
         • Callbacks (JdbcTemplate)
         • JDBC objects: Model queries, updates and stored procedures as objects
•   No more try/catch/finally blocks
•   No more leaked connections
     – Spring will always close a connection: no scope for programmer error
•   Meaningful exception hierarchy
     – No more vendor code lookups
         • Spring autodetects database and knows what Oracle, DB2 error codes mean
         • More portable code
     – More readable code
         • catch (BadSqlGrammarException ex)
•   Stored procedure support
•   Can refactor to clean up JDBC without adopting Spring overall
     – Incremental adoption: Step by step
          Spring DAO: Hibernate
• Manages Hibernate sessions
   –   No more custom ThreadLocal sessions
   –   Sessions are managed within Spring transaction management
   –   Works with JTA if desired
   –   Works within EJB container with CMT if desired
• HibernateTemplate makes common operations easy
   – Simpler, consistent exception handling
   – Many operations become one-liners
   – Less, simpler, code compared to using Hibernate alone
• Portability: Switch between Hibernate, JDO and other transparent
  persistence technologies without changing DAO interfaces
   – Can even switch to JDBC where transparent update is not implied
• Mixed use of Hibernate and JDBC within the same transaction
  HibernateTemplate DAO example
public class MyHibernateDao implements MyDao {

      private HibernateTemplate hibernateTemplate;

      public MyHibernateDao (net.sf.hibernate.SessionFactory sessionFactory) {
                hibernateTemplate = new HibernateTemplate(sessionFactory);

      public Collection getWorkflows() {
                 return hibernateTemplate.find("from Workflow");

<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
      <property name="dataSource"><ref local="dataSource"/></property>
      <property name="mappingResources">
      <property name="hibernateProperties">
                               <prop key="hibernate.dialect">net.sf.hibernate.dialect.HSQLDialect</prop>

<bean id=“myDao" class=“com.mycompany.MyHibernateDao"
          Spring DAO: JDO
• Comparable to Hibernate support
• Mixed use of JDO and JDBC within the
  same transaction
• Will support JDO 2.0 features (detach) and
  vendor extensions in a portable manner
  – All major vendors support similar concepts
             Spring Transaction
• Consistent abstraction
   – PlatformTransactionManager
   – Does not reinvent transaction manager
   – Choose between JTA, JDBC, Hibernate, JDO etc with simple
     changes to configuration not Java code
   – No more rewriting application to scale up from JDBC or
     Hibernate local transactions to JTA global transactions
   – Use the simplest transaction infrastructure that can possibly
• Programmatic transaction management
   – Simpler API than JTA
   – Use the same API for JTA, JDBC, Hibernate etc.
   – Write once have transaction management everywhereTM
          Declarative Transaction
• Most popular transaction management option
• Built on same abstraction as programmatic transaction
• Declarative transaction management for any POJO,
  without EJB: even without JTA (single database)
• More flexible than EJB CMT
   – Declarative rollback rules: roll back on MyCheckedException
   – Non-invasive: Minimizes dependence on the container
      • No more passing around EJBContext
                 Make ServiceImpl POJO
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;

     public void doSomething() throws ServiceWithdrawnException {

<bean id="serviceTarget" class="com.mycompany.service.ServiceImpl">
    <property name="timeout"><value>30</timeout></property>
    <property name="accountDao"><ref local="accountDao"/></property>
Make ServiceImpl transactional
<bean id=―service"
   <property name="target">
         <ref local="serviceTarget"/>
   <property name="transactionManager">
         <ref local="localTransactionManager"/>
   <property name="transactionAttributes">
                    <prop key="do*">
Make ServiceImpl transactional
• Rollback rule means that we don’t need to call
  – Of course Spring also supports programmatic rollback
• Can run this from a JUnit test case
  – Doesn’t depend on a heavyweight container
• Can work with JTA, JDBC, Hibernate, JDO,
  iBATIS transactions…
  – Just change definition of transaction manager
Make ServiceImpl transactional
• Alternative approaches, simpler in large
  – Use ―auto proxy creator‖ to apply similar
    transaction attributes to multiple beans
  – Use metadata or another pointcut approach to
    apply transactional behaviour to multiple
                       Spring J2EE
• No more JNDI lookups
   – JndiObjectFactoryBean
   – Generic proxy for DataSources etc.
• No more EJB API dependencies, even in code calling EJBs
   –   EJB proxies
   –   No more home.create()
   –   No more Service Locators or Business Delegates
   –   Codeless EJB access
        • Callers depend on Business Methods interface, not EJB API
        • Exposed via Dependency Injection (naturally)
• Maximize code reuse by minimizing J2EE API dependencies
• Spring does not prevent you using the full power of J2EE
   – Full power of WebSphere lies under the covers
   – Spring makes it easier to use effectively
                   Spring OOP
• No more Singletons
   – An antipattern as commonly used
• Program to interfaces, not classes
• Facilitates use of the Strategy pattern
   – Makes good OO practice much easier to achieve
• IoC Dependency Injection keeps the container from
  messing up your object model
   – Base object granularity on OO concerns, not Spring concerns
• Combine with transparent persistence to achieve a true
  domain model
           Spring Productivity
•   Less code to develop in house
•   Focus on your domain
•   Reduced testing effort
•   Try it and you won’t look back
•   ―Old‖ J2EE has a poor productivity record
    – Need to simplify the programming model, not
      rely on tools to hide the complexity
                   ―Old‖ J2EE vs Spring
•   Write a SLSB                                •   Implement a Spring object
     –   Home interface                              – Business interface
     –   Component interface                         – Implementation class
     –   ―Business methods‖ interface                – Straightforward XML configuration
     –   Bean implementation class
     –   Complex XML configuration
     –   POJO delegate behind it if you
         want to test outside the container          – The first two steps are necessary
                                                       in Java anyway
     – Much of this is working around
       EJB                                           – Oops, I really meant “implement a
                                                       Java object,” not “implement a
     – If you want parameterization it                 Spring object”
       gets even more complex                        – If you want to manage simple
          • Need custom code, IoC container            properties or object
            or “environment variables” (ouch)          dependencies, it’s easy
            ―Old‖ J2EE vs Spring
• Use your SLSB                 • Use your Spring object
  – Write a Service Locator        – Just write the class that
    and/or Business Delegate:        uses it in plain old Java
    need JNDI code                 – Express a dependency of
  – Each class that uses the         the business interface type
    service needs to depend          using Java (setter or
    on EJB interface                 constructor)
    (home.create) or you need      – Simple, intuitive XML
    a Business Delegate with         configuration
    substantial code

  – Hard to test outside a         – No lookup code
    container                      – Easily test with mock object
        Productivity dividend
• Spring removes unnecessary code
• You end with no Java plumbing code and
  relatively simple XML
  – If your Spring XML is complex, you’re probably doing
    things you couldn’t do the old way without extensive
    custom coding
• The old way you have lots of Java plumbing
  code and lots of XML
  – A lot of the XML is not standard
• Combine with Hibernate or JDO for transparent
  persistence and the advantage is huge
   Quotes: Plenty of choice from
         Spring users…
• I use the Spring Framework daily and I've
  simply been blown away by how much
  easier it makes development of new
  software components
• Spring lets me port my business logic
  across those environments [application
  server, Swing client] with ease. That's why
  I love Spring.
    Quotes: Plenty of choice from
          Spring users…
• Lightweight containers make a lot of sense. Spring’s
  ability to decouple layers within an applications is very
• You will wonder how you ever developed anything in
  Hibernate without spring, it just makes it so much easier.
  You gotta love HibernateTemplate. You gotta love the
  session management.
• The proof of concept went up to 150 requests per
  second! Man, you guys did a hell of job with the whole
  thing. Spring MVC overhead is *minimal* and it took only
  15 hours to implement it, thanks for the dependency
• I'm a new user of spring and I have to say, it's great. It's
  really speeding up our development time
• One of the great things for me about the Spring
  Framework is that it makes using some of those "old"
  technologies easier to bear … the package is nice to use
  to reduce the amount of duplicate code around EJBs
• Spring now has the momentum to dominate the
  J2EE framework space – OO guru and consultant
  Craig Larman
         The Spring community
• 15 developers
   – Around 6 ―core‖ developers
   – Significant number of contributors
• Architects and key developers
   – Rod Johnson
   – Juergen Hoeller
• Test-first development on the framework
• Vibrant community
   – Very active mailing lists and forums
• JIRA Issue tracker at Atlassian
• Over 50,000 downloads total
     …The Spring community
• At least six books coming out in 2004
  – Spring Live (June): Matt Raible
  – J2EE Without EJB (May): Johnson/Hoeller
  – Professional Spring Development (Q4):
  – Better, Faster Lighter Java (Bruce Tate)
  – Bruce is also writing an introductory Spring book for
    O’Reilly (due out Q4)
  – Manning Spring in Action (Q4)
• Related projects
  – Acegi Security for Spring
    Spring services: Interface21
• Training
• Commercial support
• Consulting
• We offer more choices for companies who
  wish to form a strategic partnership with us
• We provide unique Spring and J2EE
Who’s using Spring (partial list)
• Banking
  – Global investment bank
       • 2 projects live with Spring MVC, IoC, AOP, JDBC; 10,000 users
         daily (whole Intranet)
       • Even bigger project rolling out this month (WebSphere)
  –   German domestic bank
  –   Leading US bank: online banking service (8m hits per day)
  –   At least three more global banks to my knowledge
  –   Several household names in US
       •   Defence
       •   Publishing
       •   Health care (WebSphere)
       •   Power generation (WebSphere)
Who’s using Spring (partial list)
• Government/NGO
   –   European Commission
   –   WHO
   –   CERN
   –   Several universities in the US and UK, including
        • Rutgers University (New Jersey)
        • Warwick University (UK)
        • uPortal project (US University portal)
• Many sophisticated websites
   –   Used by several consultancies on multiple client sites
   –   Major European delivery tracking service
   –   Nominet
   –   FA Premier League football
          Where it all began…
• Describes the
  motivation for Spring
  and basic concepts
• Practical approach to
  J2EE development
  that works
• One of the first
  expressions of
  ―lightweight J2EE‖
                     Episode 2…
• Describes the Lightweight
  Container Architecture in
• Practical guide to more
  efficient, more productive
   – Not just a polemic
• Not purely about Spring,
   – Uses Spring for all
   – Discusses all key parts of

Shared By: