Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Spring Framework TM Rod Johnson Interface21. Spring framework goals Make J2EE easier to use Address end-to-end requirements rather than one tier Eliminate.

Similar presentations


Presentation on theme: "The Spring Framework TM Rod Johnson Interface21. Spring framework goals Make J2EE easier to use Address end-to-end requirements rather than one tier Eliminate."— Presentation transcript:

1 The Spring Framework TM Rod Johnson Interface21

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 only a server –Works well in WebSphere

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 approaches

4 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 popular

5 Unique Spring capabilities Declarative transaction management for POJOs with or without EJB Consistent approach to data access, with common exception hierarchy –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

6 Spring focus Spring complements application servers like WebSphere –Spring comes out of the application space, rather than the server space 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

7 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

8 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 food

9 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

10 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 coding –No more Service Locators or ad hoc Singletons

11 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 (August) –JSF leaders (Ed Burns, David Geary) are working with us on Spring/JSF integration

12 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!

13 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

14 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 … 30

15 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 30

16 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)

17 Spring in the Middle Tier Advanced IoC features –Can manage lists, maps or sets, with arbitrary nesting –Leverages standard JavaBeans PropertyEditor machinery Register custom property editors –“Post processors”

18 Why AOP? 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 Spring provides important out-of-the box aspects –Declarative transaction management for any POJO –Pooling –Resource acquisition/release

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 solution

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

21 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 way 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

22 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

23 Spring DAO: Consistent exception hierarchy

24 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

25 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

26 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"); } mycompany/mappings.hbm.xml net.sf.hibernate.dialect.HSQLDialect <bean id=“myDao" class=“com.mycompany.MyHibernateDao" autowire="constructor" >

27 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

28 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 work Programmatic transaction management –Simpler API than JTA –Use the same API for JTA, JDBC, Hibernate etc. –Write once have transaction management everywhere TM

29 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 –Non-invasive: Minimizes dependence on the container No more passing around EJBContext

30 Make ServiceImpl POJO transactional 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 { } 30

31 Make ServiceImpl transactional PROPAGATION_REQUIRED,-ServiceWithdrawnException

32 Make ServiceImpl transactional Rollback rule means that we don’t need to call setRollbackOnly() –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

33 Make ServiceImpl transactional Alternative approaches, simpler in large applications: –Use “auto proxy creator” to apply similar transaction attributes to multiple beans –Use metadata or another pointcut approach to apply transactional behaviour to multiple classes

34 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

35 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

36 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

37 “Old” J2EE vs Spring Write a SLSB –Home interface –Component interface –“Business methods” interface –Bean implementation class –Complex XML configuration –POJO delegate behind it if you want to test outside the container –Much of this is working around EJB –If you want parameterization it gets even more complex Need custom code, IoC container or “environment variables” (ouch) Implement a Spring object –Business interface –Implementation class –Straightforward XML configuration –The first two steps are necessary in Java anyway –Oops, I really meant “implement a Java object,” not “implement a Spring object” –If you want to manage simple properties or object dependencies, it’s easy

38 “Old” J2EE vs Spring Use your SLSB –Write a Service Locator and/or Business Delegate: need JNDI code –Each class that uses the service needs to depend on EJB interface (home.create) or you need a Business Delegate with substantial code duplication –Hard to test outside a container Use your Spring object –Just write the class that uses it in plain old Java –Express a dependency of the business interface type using Java (setter or constructor) –Simple, intuitive XML configuration –No lookup code –Easily test with mock object

39 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

40 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.

41 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 addictive. 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 injection!

42 Quotes 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 org.springframework.ejb.support 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

43 The Spring community www.springframework.org 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

44 …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): Johnson/Risberg/Hoeller/Arendsen –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

45 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 expertise

46 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)

47 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

48 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”

49 Episode 2… Describes the Lightweight Container Architecture in detail Practical guide to more efficient, more productive J2EE –Not just a polemic Not purely about Spring, but –Uses Spring for all examples –Discusses all key parts of Spring

50 Questions


Download ppt "The Spring Framework TM Rod Johnson Interface21. Spring framework goals Make J2EE easier to use Address end-to-end requirements rather than one tier Eliminate."

Similar presentations


Ads by Google