1 / 26

Spring Framework Adam Waldal Senior Consultant

Spring Framework Adam Waldal Senior Consultant. About me. OPI is a leader in J2EE consulting with Relationships with BEA, IBM, Tibco, and many other vendors. Technical Project Lead for OPI Agile Software Practitioner Speaker for BEA User Group on Spring. Spring Framework Mission.

rudolpho
Download Presentation

Spring Framework Adam Waldal Senior Consultant

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Spring Framework Adam Waldal Senior Consultant

  2. About me.. • OPI is a leader in J2EE consulting with Relationships with BEA, IBM, Tibco, and many other vendors. • Technical Project Lead for OPI • Agile Software Practitioner • Speaker for BEA User Group on Spring

  3. Spring Framework Mission • We believe that: • J2EE should be easier to use • It's best to program to interfaces, rather than classes. Spring reduces the complexity cost of using interfaces to zero. • JavaBeans offer a great way of configuring applications. • OO design is more important than any implementation technology, such as J2EE. • Checked exceptions are overused in Java. A framework shouldn't force you to catch exceptions you're unlikely to be able to recover from. • Testability is essential, and a framework such as Spring should help make your code easier to test. • We aim that: • Spring should be a pleasure to use • Your application code should ''not'' depend on Spring APIs • Spring should not compete with good existing solutions, but should foster integration. (For example, JDO and Hibernate are great O/R mapping solutions. We don't need to develop another one.)

  4. Overview • IOC and Dependency Injection • Lightweight Containers explained • Description of Spring as a framework • Description of the BeanFactory • AOP explained • AOP in Spring overview • Why or Why not use Spring? • Example Application: jPetstore

  5. IOC Inversion of Control • IOC Definition “Giving control to an object over who it calls, but not who calls it.” – Me “IOC is this“ – Rod Johnson

  6. Two types of IOC common to J2EE • Dependency Lookup EJB and Apache Avalon - The coarse-grain beans are left looking up dependencies it needs. • “In J2EE, JNDI is the glue that holds J2EE applications together…” IBM • Dependency Injection Spring and Pico – Factories create beans with all the dependencies set on the bean. • In Spring that glue is externalized so business classes don’t have to worry about how or what they need to glue together.

  7. Setter and Constructor Injection // Example of Setter Injection package eg; public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; public void setBeanOne(AnotherBean b) { beanOne = b; } public void setBeanTwo(YetAnotherBean b) { beanTwo = b; } } // Example of Constructor Injection (This is the typical Spring usage) public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; public ExampleBean (AnotherBean a , YetAnotherBean b){ this.beanOne = a; this.beanTwo = b; } …Business Methods }

  8. My Description of Spring • Spring is a glue framework that is gives an easy way of configuring and resolving dependencies throughout the J2EE stack. It has MVC, AOP, declarative management of beans and services, JDBC, JMS, and other useful abstractions. • Spring ties many other technologies together in a consistent approach. • The light weight container only used for the service layer is enough to provide a business case for using Spring. • Spring also provides declarative access to enterprise services via AOP (Aspect Oriented Programming). J2EE services exposed through aspects ,usually hidden behind an EJB container, helps to facilitate testing and consequently ease of development. • The added ease of development and maintenance make the value proposition presented with Spring very attractive to most companies.

  9. Spring features Below is a list of some of the features in Spring. • MVC Framework implemented with interfaces and IOC(another presentation) • IOC (Inversion of Control) Container to facilitate Dependency Injection • Application Context which is an implementation of BeanFactory • AOP Framework for accessing J2EE service declaratively • JDBC and DAO layer Abstraction (another presentation) • Exception Handling Framework for Persisting proprietary exceptions ( another presentation ) • JMS producer, consumer abstractions, and conversion

  10. Spring API’s

  11. Bean Factory Configuration <bean id="exampleBean" class="eg.ExampleBean"> <property name="beanOne"> <ref bean="anotherExampleBean"/> </property> <property name="beanTwo"> <ref bean="yetAnotherBean"/> </property> </bean> <bean id="anotherExampleBean" class="eg.AnotherBean"/> <bean id="yetAnotherBean" class="eg.YetAnotherBean"/>

  12. Lightweight Containers Lightweight is maybe mistaken to mean less than an Enterprise container. Simplicity is actually often better than the complexity to handle the worst in every scenario. The ability to scale up and down is more desirable in most applications. Lightweight should be taken to mean flexible, pluggable, and configurable. The idea that the simplest solution that can work, should be supported by the container as well. Container Services • Lifecycle management • Lookup • Configuration • Dependency Resolution

  13. Criteria for a Lightweight Container Lightweight Criteria • Manage application code without imposing dependency on the container itself. • Quick startup • No special deployment • Flexibility to run in different environments • Easy management and low overhead to allow management of fine as well as coarse grained components.

  14. Struts Example using WebApplicationContext package org.springframework.samples.jpetstore.web.struts; import javax.servlet.ServletContext; import org.apache.struts.action.Action; import org.apache.struts.action.ActionServlet; import org.springframework.samples.jpetstore.domain.logic.PetStoreFacade; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; public abstract class BaseAction extends Action { private PetStoreFacade petStore; public void setServlet(ActionServlet actionServlet) { super.setServlet(actionServlet); ServletContext servletContext = actionServlet.getServletContext(); WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); this.petStore = (PetStoreFacade) wac.getBean("petStore"); } protected PetStoreFacade getPetStore() { return petStore; } }

  15. Child of BaseAction package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; … public class AddItemToCartAction extends BaseAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CartActionForm cartForm = (CartActionForm) form; Cart cart = cartForm.getCart(); String workingItemId = cartForm.getWorkingItemId(); if (cart.containsItemId(workingItemId)) { cart.incrementQuantityByItemId(workingItemId); } else { // isInStock is a "real-time" property that must be updated // every time an item is added to the cart, even if other // item details are cached. boolean isInStock = getPetStore().isItemInStock(workingItemId); Item item = getPetStore().getItem(workingItemId); cartForm.getCart().addItem(item, isInStock); } return mapping.findForward("success"); } }

  16. Spring Controller package org.springframework.samples.jpetstore.web.spring; … import org.springframework.samples.jpetstore.domain.logic.PetStoreFacade; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.util.WebUtils; public class AddItemToCartController implements Controller { private PetStoreFacade petStore; public void setPetStore(PetStoreFacade petStore) { this.petStore = petStore; } public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Cart cart = (Cart) WebUtils.getOrCreateSessionAttribute(request.getSession(), "sessionCart", Cart.class); String workingItemId = request.getParameter("workingItemId"); if (cart.containsItemId(workingItemId)) { cart.incrementQuantityByItemId(workingItemId); } else { boolean isInStock = this.petStore.isItemInStock(workingItemId); Item item = this.petStore.getItem(workingItemId); cart.addItem(item, isInStock); } return new ModelAndView("Cart", "cart", cart); } }

  17. AOP Description • AOP decomposes a system into aspects or concerns, rather than objects. An example of a concern in an application would be logging, security, or transaction management. • EJB declarative services are discrete example of aspects. • Often in OO systems there is code bloat and duplication from such concerns. • Code duplication is a sign there is something wrong with the solution. • There are some cases in some systems where OO does not provide a clean solution. • It is capable of using either dynamic proxies or dynamic bytecode generation with CGLIB. This is also used in Hibernate. • Spring, AspectJ, Nanning

  18. AOP in Spring • Spring implements AOP in the same consistent way it deals with bean definitions in a BeanFactory. • Transactions for JDBC <!-- Transaction manager for a single JDBC DataSource --> <!-- (see dataAccessContext-jta.xml for an alternative) --> <bean id="transactionManager" class="org.sf.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource"><ref local="dataSource"/></property> </bean> • Transactions for JTA <!-- Transaction manager that delegates to JTA (for a transactional JNDI DataSource) --> <!-- Necessary here due to the need for distributed transactions across two databases --> <!-- (see dataAccessContext-local.xml for an alternative) --> <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/> • Transaction Interceptor

  19. AOP in Spring • Definitions: • Aspect - An application wide concern that is often duplicated in many classes, that could be implemented before, after, or upon failure across a group of methods. • JointPoint - A join of methods across which an aspect can be implemented. • Spring allows method interception. This means when a method is called the framework can attach functionality. • Pointcut - Description of the collection of methods for which advice is to be applied • Introduction - Adding methods or properties to a class with advice. • AOP Proxies - Surrogate object that invokes advice and advises the invoked class

  20. Declarative Transactions with AOP • Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, • iBATIS Database Layer and JDO. • Provides a simpler, easier to use, API for programmatic transaction management than most of these transaction APIs • Integrates with the Spring data access abstraction • Supports Spring declarative transaction management <!-- Transactional proxy for the JPetStore primary business object --> <bean id="petStore" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"><ref bean="transactionManager"/></property> <property name="target"><ref local="petStoreTarget"/></property> <property name="transactionAttributes"> <props> <prop key="insert*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED,readOnly</prop> </props> </property> <!-- Uncomment the following in order to enable mail sending aspect --> <!-- <property name="postInterceptors"> <list> <ref local="emailAdvisor"/> </list> </property> -->

  21. TransactionManager Abstraction Spring Transaction Strategy Interface: public interface PlatformTransactionManager { TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException; void commit(TransactionStatus status) throws TransactionException; void rollback(TransactionStatus status) throws TransactionException; } JDBC - <bean id="transactionManager“ class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource"><ref local="dataSource"/></property> </bean> JTA - <bean id="transactionManager“ class="org.springframework.transaction.jta.JtaTransactionManager"/> Hibernate - <bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager"> <property name="sessionFactory"><ref local="sessionFactory"/></property> </bean>

  22. jPetstore Example Online at springframework.org • Petclinic is another version of the petstore app with Spring, and a number of different O/R and jdbc solutions

  23. Why use Spring? • Spring is a clear choice in a web application with a tiered architecture. • Spring gives good abstractions for integrating Hibernate. Use Spring and Hibernate together if O/R is necessary. • If using JDBC spring is a must. • If you are building a stateless service layer for any type of view Spring adds value. • If you want to simplify configuration and testing us Spring. • If you are using EJB still use the Spring Bean Factory for managing fine grained objects.

  24. Why not use Spring? • If you are already using EJB on a project and have a infrastructure built up around it that you think works. (Still look at Spring for managing a DAO layer or using the Template method pattern for JDBC or Hibernate Templates.) • Always evaluate any solution and only apply a new technology if it makes sense for the application not for the sake of the technology.

  25. OPI using Spring • We are currently using Spring in two clients • Evaluating replace of SLSB in favor of Spring with Hibernate • Our approach to technology selection aligns well with the principals held by the Spring development team

  26. Resources • www.springframework.org • http://www.warfrog.com/hibernatetutorial • http://www.java201.com/resources/browse/40-2004-10.html • Rod Johnson’s two books : • J2EE without EJB • J2EE Design and Development (co-author Juergen Hoeller) • Better, Faster, Lighter Java by Bruce Tate, Justin Gehtland • Spring Live by Matt Raible • Me, adam.waldal@objectpartners.com

More Related