[S lide] java_sig-spring-framework

1,599 views

Published on

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,599
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
78
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

[S lide] java_sig-spring-framework

  1. 1. The Spring Framework Colin Sampaleanu Interface21
  2. 2. 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 just an application server  Some applications don‘t need a full application server: just a web container  But where an app server adds value, take full advantage (no compromises) of all additional advanced functionalityCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  3. 3. …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 approachesCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  4. 4. Part of a new wave of frameworks Big change in how J2EE applications are written Less emphasis on EJB  EJB has been grossly overused  EJB has some unique capabilities for a minority of apps (distributed transaction management, RMI remoting) but for the most part is looking like legacy Not just Spring  PicoContainer, HiveMind and other Inversion of Control frameworks  EJB 3.0 (2006-2007) programming model looks a lot like (Spring IoC – important features) + Hibernate/JDO These lightweight frameworks are different from earlier frameworks Spring is the most mature, most powerful and by far the most popularCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  5. 5. Unique Spring capabilities  Declarative transaction management for POJOs with or without EJB. Optional Annotations support.  Consistent approach to data access, with common exception hierarchy  Simplifies working with JDBC, JDO, Hibernate, TopLink, etc  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, across all industriesCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  6. 6. A layered framework  Spring Web Flow  Web MVC  AOP framework  Integrates with IoC  IoC container  Dependency Injection  Transaction management  Data access  JMX  Transparent Remoting  One stop shop but can also use as modulesCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  7. 7. Layers of Spring Web AOP Enterprise Context Web Flow AOP core Web-based JDBC + ORM Web MVC AOP Alliance AspectJ Transactions Factories Incl. Views (JSP, Velocity, Remoting Access PDF, Excel) Source-level JMX Event metadata Web Messaging JNDI Integration Spring Core Beans UtilitiesCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  8. 8. 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 (most common choice) • But the IoC container is not tied to XML • Other formats coming Application code has few dependencies on the container—often no dependencies on the container  Spring Pet Store sample has no dependencies on Spring IoC  No imports, no magic annotations for IoC: nothing Spring- specific Easy unit testing. TDD works!Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  9. 9. …Spring in the Middle Tier Named ―beans‖—objects—provide a clear point for pluggability Objects that depend on a given bean depend on its interface(s) and/or class  Better practice to depend on interfaces Can change any object‘s implementation with zero impact on callers The ―Lego Hypothesis‖ made real in J2EE applicationsCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  10. 10. …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  Method Injection  Dependency Lookup • Avalon/EJB-style callbacksCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  11. 11. Middle Tier: Setter Injection public class PetStoreImpl implements PetStoreFacade { private OrderDao orderDao; private ItemDao itemDao; ... public void setOrderDao(OrderDao orderDao) { this.orderDao = orderDao; } public void setItemDao(ItemDao itemDao) { this.itemDao = itemDao; } ... public void insertOrder(Order order) { this.orderDao.insertOrder(order); this.itemDao.updateQuantity(order); } }Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  12. 12. Middle Tier: Setter Injection <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="... "/> <property name="url" value="..."/> <property name="username" value="...“> <property name="password" value="...“/> </bean> <bean id="itemDao" class="org.springframework.samples.jpetstore.dao.ibatis.SqlMapItemDao"> <property name="dataSource" ref="dataSource"/> <property name="sqlMap" ref="sqlMap"/> </bean> <bean id="petStore“ class="org.springframework.samples.jpetstore.domain.logic.PetStoreImpl"> <property name="orderDao" ref="orderDao"/> <property name="itemDao" ref="itemDao"/> </bean>Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  13. 13. Middle Tier: Constructor Injection public class PetStoreImpl implements PetStoreFacade { private OrderDao orderDao; private ItemDao itemDao; ... public PetStoreImpl(OrderDao orderDao, ItemDao itemDao) { this.orderDao = orderDao; this.itemDao = itemDao; } ... public void insertOrder(Order order) { this.orderDao.insertOrder(order); this.itemDao.updateQuantity(order); } }Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  14. 14. Middle Tier: Constructor Injection <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="... "/> <property name="url" value="..."/> <property name="username" value="...“> <property name="password" value="...“/> </bean> <bean id="itemDao" class="org.springframework.samples.jpetstore.dao.ibatis.SqlMapItemDao"> <property name="dataSource" ref="dataSource"/> <property name="sqlMap" ref="sqlMap"/> </bean> <bean id="petStore“ class="org.springframework.samples.jpetstore.domain.logic.PetStoreImpl"> <constructor-arg ref="orderDao"/> <constructor-arg ref="itemDao"/> </bean>Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  15. 15. Middle Tier: Dependency Injection 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…Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  16. 16. Middle Tier: Dependency Injection Properties & Constructor Arguments injected are:  Configuration values (i.e. something like a timeout integer value)  Dependencies on collaborators (i.e. the reference to accountDao in the example) 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)Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  17. 17. Spring in the Middle Tier Advanced IoC features  Manage lists, maps or sets, with arbitrary nesting  Create objects using new or from factory methods  Method Injection • Container can override abstract or concrete methods at runtime • Can use to avoid dependence on Spring (override isolates dependency on Spring API)  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 behaviourCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  18. 18. Why AOP?  Dependency Injection takes us a long way, but 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  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 components  Can‘t define new aspects  Constrained pointcut model (methods on the component interface)  Spring provides important out-of-the box aspects  Declarative transaction management for any POJO  Remoting  Pooling, and resource acquisition/releaseCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  19. 19. 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 container Spring is an integrated, consistent solutionCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  20. 20. Custom AOP Complements, rather then conflicts with, OOP  Email administrator if a particular exception is thrown  Apply custom declarative security checks  Performance monitoring  Auditing  Caching Objects have clear responsibilities  No need to abuse inheritance Integration with AspectJ/AspectWerz for when you need a full-blown AOP frameworkCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  21. 21. 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  JDO  Hibernate  TopLink  iBATIS  + others  Model allows support for other technologies  Java Persistence API support coming as soon as spec is stableCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  22. 22. …Spring DAO  Using clearly defined technology agnostic DAO interfaces is a best practice  Implement with JDO, JDBC, Hibernate, iBATIS…  Spring doesn‘t enforce this, but it makes it very easy  Consistent DataAccessException hierarchy allows truly technology-agnostic DAOs public interface ReminderDao { public Collection findRequestsEligibleForReminder() throws DataAccessException; void persist(Reminder reminder) throws DataAccessException; }Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  23. 23. Spring DAO:Consistent exception hierarchyCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  24. 24. Spring DAO: JDBC  Class library offers simpler programming model than raw JDBC  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)  Sophisticated, portable stored procedure and BLOB/CLOB support  Can refactor to clean up JDBC without adopting Spring overall  Incremental adoption: Step by stepCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  25. 25. Example Working With the JPetStoreDatabase Get a list of pet types (Strings)JdbcTemplate template = new JdbcTemplate(dataSource);final List names = new LinkedList();template.query("SELECT id,name FROM types ORDER BY name", new RowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { names.add(rs.getString(1)); } }); Note usage of ‗final‘ on the names variable so that the anonymous inner class can have access to it  Remember this when working with callbacksCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  26. 26. Mapping Result sets to Objects Example of a RowCallbackHandler mapping ResultSets to complex typesRowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { Pet pet=new Pet(); pet.setId(rs.getInt(“pet_id”)); pet.setName(rs.getString(“pet_name”)); … // more fields here pets.add(pet);}Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  27. 27. Spring DAO: ORM (Hibernate / JDO /TopLink / Other) Spring manages the unit of work (Hibernate Session, JDO PersistenceManager, TopLink UnitOfWork, etc.)  No more passing them around or custom ThreadLocals for this purpose  Sessions are managed within Spring transaction management  Works with JTA or local transactions, with no code changes  Works within EJB container with CMT if desired Templates (HibernateTemplate/JDOTemplate, etc.) makes common operations easy  Simpler, consistent exception handling  Many operations become one-liners  Less, simpler, code compared to using Hibernate alone Mixed use of ORM and JDBC within the same transactionCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  28. 28. HibernateTemplate DAO example public class HibernateReminderDao extends HibernateDaoSupport implements ReminderDao { public Collection findRequestsEligibleForReminder() throws DataAccessException { getHibernateTemplate().find("from Request r where r.something = 1"); } public void persist(Reminder reminder) throws DataAccessException { getHibernateTemplate().saveOrUpdate(reminder); } }Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  29. 29. HibernateTemplate DAO example (2) <bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean"> <property name="dataSource― ref="dataSource"/> <property name="mappingResources"> <value>mycompany/mappings.hbm.xml</value> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">net.sf.hibernate.dialect.HSQLDialect</prop> </props> </property> </bean> <bean id=―myDao" class=―com.mycompany.HibernateReminderDao" autowire=―autodetect―/>Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  30. 30. Spring DAO: JDO Comparable to Hibernate support PersistenceManager management just like Hibernate Session management Mixed use of JDO and JDBC within the same transaction Support JDO 2.0 features and vendor extensions in a portable manner  All major vendors support similar concepts We work closely with JDO vendors, including:  SolarMetric (Kodo)  Open source: JPOX JDO Spring + Kodo is a particularly strong enterprise combinationCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  31. 31. Spring DAO: TopLink Originally written by Oracle, donated to Spring Basic approach is very similar to Hibernate or JDO integration approach Mixed use of TopLink and JDBC within the same transaction Strong enterprise combinationCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  32. 32. 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, JDO, or Hibernate local transactions to JTA global transactions  Use the simplest transaction infrastructure that can possibly work  Global (JTA) transactions optionally take advantage of server-specific enhanced functionality  Local transactions offer more features than standard JTA (isolation levels, savepoints, etc.)Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  33. 33. Spring Transaction (WebLogic) Enhanced support for transactions in a WebLogic environment  Beyond the level of standard JTA APIs  WebLogicJtaTransactionManager  Allows Spring-driven transactions to be visible in WebLogic‘s transaction monitor  Supports per-transaction isolation level  Enhances resume support when using transaction suspension  Automatically detects WebLogic server version  Usage on a WebLogic client is supported  Fully XA capable access to WebLogic DataSources and JMSCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  34. 34. Programmatic TransactionManagement Simpler, cleaner API than JTA  Exception hierarchy as with DAO  No need to catch multiple exceptions without a common base class  Unchecked exceptions Use the same API for JTA, JDBC, Hibernate, etc. Write once have transaction management anywhereTMCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  35. 35. Declarative Transaction Management Most popular transaction management option Built on same abstraction as programmatic transaction management 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  Supports nested transactions and savepoints if the underlying resource manager does Non-invasive: Minimizes dependence on the container  No more passing around EJBContextCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  36. 36. Making a service transactional The original service implementation class is unmodified and knows nothing about transactions Pluggable metadata tells Spring to wrap the target service with a proxy object which looks like the target, but applies transaction semantics on method invocations Most people today use XML for defining both the services, and the transactional wrappers around them Once they can commit to a Java 5 dependency, most people will probably prefer to use source code AnnotationsCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  37. 37. Make ServiceImpl POJO transactionalpublic 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‖/> <property name="accountDao― ref="accountDao"/></bean>Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  38. 38. Make ServiceImpl transactional<bean id=―service" class=―org.springframework.transaction.interceptor.Transactio nProxyFactoryBean"/> <property name="transactionManager― ref=―txManager"/> <property name="target― ref="serviceTarget"/> <property name="transactionAttributes"> <props> <prop key="do*"> PROPAGATION_REQUIRED,-ServiceWithdrawnException </prop> </props> </property></bean> Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  39. 39. Make ServiceImpl transactional Rollback rule means that we don‘t need to call setRollbackOnly()  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…  Simply change definition of transaction managerCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  40. 40. Make ServiceImpl transactional Don‘t actually need this much XML per transactional object Alternative approaches, simpler in large applications:  Use ―auto proxy creator‖ to apply similar transaction attributes to multiple beans  Use metadata (annotations) or another pointcut approach to apply transactional behaviour to multiple classesCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  41. 41. Annotations for TransactionDemarcation@Transactional(readOnly=true)interface MyService { @Transactional(readOnly=false, rollbackFor=DuplicateOrderIdException.class) void createOrder(Order order) throws DuplicateOrderIdException ; List queryByCriteria(Order criteria);}Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  42. 42. Transactions: flexibility Rollback rule means that we don‘t need to call setRollbackOnly()  Spring also supports programmatic rollback Can run this from a JUnit test case in your IDE  Doesn‘t depend on deplying to an app server Can work with JTA, JDBC, JDO, Hibernate, iBATIS transactions…  Simply change definition of transaction manager Full ability to customize transaction semantics:  Propagation behavior (REQUIRED, SUPPORTS, REQUIRES_NEW, etc.). Isolation level. Read/write vs. read-only. Timeout value. Rollback rules.Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  43. 43. Spring J2EE No more JNDI lookups  JndiObjectFactoryBean  Generic proxy for DataSources etc. No more EJB API dependencies, even in code calling EJBs  ―Codeless EJB proxies‖  No more home.create(), Service Locators or Business Delegates  Callers depend on Business Methods interface, not EJB API  Enhanced testability Maximize code reuse by minimizing J2EE API dependencies Full power of your application server lies under the coversCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  44. 44. Goals of Spring Remoting Reduce the amount of glue code needed Clearly separate remoting infrastructure from application logic Increase ease-of-use Support both client and server Transparent support for different protocols  HttpInvoker  Hessian  Burlap  RMI  SOAP (using Axis or XFire)  Accessing EJBs  Special WebLogic specific cluster-aware web service invokerCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  45. 45. Spring Remoting Overview Server-side  Exporters provide Spring-style configuration for exposing services  Transparent exposure in most cases  Exporters used for both remoting and JMX  Translation of remote calls to local calls  Marshalling of return values and exceptions Client-side  Services are hidden behind (business) interfaces  Service proxies are generated dynamically  Translation of local calls to remote calls  Unmarshalling of return values and exceptions  Easy unit testing • Inject stub service implementationsCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  46. 46. Problems with Traditional JMX Requires too much effort from application developers Code is closely coupled to JMX Advanced features require a LOT of spaghetti code  ModelMBeans are a pain to code (see the Spring JMX code!) JMX 1.0 specification is inconsistentCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  47. 47. Spring JMX Features (1) Transparently expose ANY Spring bean to JMX Full control over ObjectNames Full control over methods in the management interface  Simple catch-all approach  Configure in Spring XML  Use interfaces  Use source-level metadata (Annotations) Removes the need for manual MBean creation  No need to create Standard MBean interfaces  No need to create Model MBean metadataCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  48. 48. Spring JMX Features (2) Declaratively registers MBeans with the MBeanServer  Supports Spring-created AND user-created MBeans  Autodetect MBeans in certain cases Declaratively setup JSR-160 connectors Access local and remote MBeans via simple Java proxies  MBean dependencies can be injected like any other dependency! Abstract many implementation inconsistenciesCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  49. 49. Spring Web MVC Most similar in design to Struts  Single shared Controller instance handles a particular request type Controllers, interceptors run in the IoC container  Important distinguishing feature  Spring eats its own dog foodCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  50. 50. Web MVC: Advantages over Struts Allows multiple DispatcherServlets  More elegant than Struts 1.1 approach  DispatcherServlets can share a base ―application context‖ Interceptors as well as controllers  No need to abuse inheritance to put interception behaviour in a common base Action No need for custom ActionForms  Reuse domain objects or DTOs as form objects. MUCH less binding code is needed  Avoid code duplication Interface not class based: Easy to customize Less tied to JSP  Clean separation of controller, model and viewCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  51. 51. Web tier integrationBut I love WebWork/Tapestry/Struts/JSF/whatever The customer is always right  …unless the customer has only ever used Struts 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 Seamless Struts, JSF, WebWork integration Portlet integration in Spring 1.3Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  52. 52. Spring Web Flow – What is it? A new spring-web module  A strong compliment to Spring MVC, Struts 1.x, JSF, and other frameworks, that addresses one problem really well: web application page flow  Builds on these lower-level frameworks, doesn‘t replace them  Proven in production Key benefits:  Captures page flow as a reusable module  Makes web application page flow explicit and clear  Scales elegantly as a web application grows in complexity  One consistent approach for your developers to learnCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  53. 53. Spring Web Flow - Design What makes a good Web Flow?  Accomplishes some business goal, e.g. • Book a flight • Pay your taxes • Apply for a Loan  Encapsulates that business goal as a reusable module • A ―black box‖  Often has multiple paths to support different scenarios • Paths may vary based on contextual information  Often spawns other Flows as sub flows • Has a clear, observable lifecycle: Flow executions start, events happens, they endCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  54. 54. Spring Web Flow - Design What doesn‘t make a good Flow?  Index pages  Welcome Pages  Menus  Simple Form Submissions  Sites with a lot of free navigation Web flows are best suited for enforcing controlled navigation to support business process workflows  Don‘t abuse themCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  55. 55. Web Flow Design – State Diagram Phonebook Search Flow State Diagram << StartState , ViewState >> << ActionState >> << ActionState >> Bind And Validate Search Criteria Execute Query submit success View Search Criteria success newSearch << ViewState >> View Results back << SubFlowState >> select Details << ActionState >> success Set Person ID Note how the Details sub flow is a "black box" - its internals are hidden from the Search parent flow!Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  56. 56. 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  Reduces the cost of programming to interfaces to near zero Dependency Injection keeps the container from messing up your object model  Base object granularity on OO considerations, not Spring considerations Combine with transparent persistence to achieve a true domain modelCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  57. 57. Spring Productivity Less code to develop in house Focus on your domain Reduced testing effort ―Old‖ J2EE has a poor productivity record  Need to simplify the programming model, not rely on tools to hide the complexityCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  58. 58. “Old” J2EE vs Spring Write a SLSB  Implement a Spring object  Home interface  Business interface  Component interface  Implementation class  ―Business methods‖ interface  Straightforward XML  Bean implementation class configuration  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 issues  Oops, I really meant ―implement a Java object,‖  If you want parameterization it not ―implement a Spring gets even more complex object‖ • Need custom code, IoC  If you want to manage container or ―environment simple properties or object variables‖ (ouch) dependencies, it‘s easy Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  59. 59. “Old” J2EE vs Spring Use your SLSB  Use your Spring object  Write a Service Locator  Just write the class that and/or Business uses it in plain old Java Delegate: need JNDI  Express a dependency of code the business interface  Each class that uses the type using Java (setter or service needs to depend constructor) on EJB interface (home  Simple, intuitive XML interface) or you need a configuration Business Delegate with substantial code duplication  No lookup code  Hard to test outside a  Easily test with mock container objectCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  60. 60. 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 JDO or Hibernate for transparent persistence and the advantage is huge compared to traditional J2EE. Still mix in JDBC as needed.  Real example: financial application with 15% of the code of a failed attempt to deliver a ―blueprints‖ solutionCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  61. 61. MedRec Experience A J2EE best practice example by BEA A three tier application with  Presentation tier  Service tier  Enterprise Information System tier Re-wrote MedRec with Spring  Demonstrating Spring best practices on WLS  Spring and WLS best practiceCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  62. 62. MedRec Architecture with J2EEMedRec (Patient/Admin) Application Shared Physician ApplicationPresentation/Interface Tier JSTL JSTL JSPs XMLBeans JSPs Log4j / WL Diagnostic Framework Web Struts Services StrutsServices Tier Security Local / Remote Driven Beans Local Stateless Session Message- JMX Stateless Session EJBs EJBsIntegration Tier Local CMP JDBC JMS JavaMai Web Services Entity RowSets l BeansEIS/External Services Tier PointBase MedRec WebLogic / J2EE component Open Source / 3rd Party componentCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  63. 63. MedRec Architecture with SpringMedRec (Patient/Admin) Application Shared Physician ApplicationPresentation/Interface Tier JSTL JSTL Java Server Pages XMLBeans Java Server Pages Web Struts Struts Services Log4j / WL Diagnostic Framework Spring Web Spring WebServices Tier Spring / WLS Java Transaction Management Extensions Security Spring Java Remoting Message- Driven Spring Beans Spring Beans Enterprise Java BeansIntegration Tier Spring Remoting Spring Spring Messaging Spring Java Database Java JavaMai Web Services Connectivity l MessagingEIS/External Services Tier PointBase MySQL MedRec WebLogic / J2EE component Open Source / 3rd Party component Spring Framework componentCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  64. 64. Quotes Spring now has the momentum to dominate the J2EE framework space – OO guru and consultant Craig Larman ―get off your butts and try it out ‖ – ‗Pragmatic‘ Dave ThomasCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  65. 65. A Shameless plug for a good book: Written by Rod Johnson and Juergen Hoeller Describes the Lightweight Container Architecture in detail Practical guide to more efficient, more agile, more productive J2EE  Not just a polemic Not purely about Spring, but  Uses Spring for all examples  Discusses all key parts of SpringCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  66. 66. The Spring community www.springframework.org 25 developers  Around 7-8 ―core‖ developers  Significant number of contributors Architects and key developers  Rod Johnson, Juergen Hoeller  Alef Arendsen, Keith Donald, Rob Harrop, Colin Sampaleanu, Mark Pollack, Thomas Risberg + others Framework is developed test-first Vibrant community  Very active mailing lists and forums (6k+ registered users) JIRA Issue tracker Around 400K direct downloads in late Summer 2005Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  67. 67. Momentum At least 9 books on Spring by late 2005  J2EE Without EJB: Johnson/Hoeller  Professional Java Development with Spring: Arendsen/Johnson/Hoeller/Risberg/Sampaleanu  Pro Spring: Rob Harrop  Spring Live: Matt Raible  Manning Spring in Action  Better, Faster Lighter Java (Bruce Tate)  Spring Developer‘s Handbook (Bruce Tate, O‘Reilly, Q4)  APress! : Spring MVC and Web Flow book coming  APress! : Introduction to Spring book coming Related projects  Acegi Security for Spring (Spring Security)  Spring Rich Client Project  Spring.NET  + many frameworks/apps using, integrating with, or architecturally based on SpringCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  68. 68. Roadmap Spring 1.2.6 is current production version (released Nov. 2005) Continuing vigorous development and innovation Spring 1.3 RC1 in early Dec. 2005 Upcoming features in 1.3 and beyond:  XML simplification (dialects)  Enhanced JMS and messaging integration/functionality  Enhanced JMX functionality  Portlet API support  Continuing AspectJ integration enhancements  Enhanced use of Annotations, where they make sense  Enhanced scripting support (scripts can be configured via dependency injection, regular objects can be injected with scripts)  Spring Web Flow final release  Innovative alternative to XML bean definitionsCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  69. 69. The Spring Experience 2005Copyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  70. 70. The Spring Experience 2005 International conference for agile Java developers http://www.thespringexperience.com December 7 – 10th, 2005, Sheraton Resort, Bal Harbour Beach Florida 40+ technical sessions across four tracks: Web, Enterprise, Process, Beyond J2EE Featuring  Rod Johnson (Spring Founder, i21 CEO)  Juergen Hoeller (Spring Co-Founder, i21 CTO)  Adrian Colyer (AspectJ Founder, i21 Chief Scientist)  Colin Sampaleanu (Author, Prof. Java Dev. With Spring)  Rob Harrop (Author, Pro Spring)  Keith Donald  Alef Arendsen  Ben Alex  … and many moreCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  71. 71. Interface21 – www.interface21.com Spring ―From the Source‖  Training • Both onsite and publicly scheduled (worldwide)  Consulting  Support Expert consulting on Agile and Lightweight J2EE, AspectJ We know Spring best, because we built it  Almost all core Spring developers work for Interface21 • Rod Johnson, Juergen Hoeller, Adrian Colyer, Colin Sampaleanu, Rob Harrop, Keith Donald, Alef Arendsen, Steven DevijverCopyright 2004-2005, Interface21 Ltd. - Copying, publishing, or distributing without expressed written permission is prohibited.
  72. 72. www.springframework.org Questions? Colin SampaleanuDirector, Interface21 North America www.interface21.com

×