Spring Framework Training

15,805 views

Published on

http://www.intertech.com/Courses/Course.aspx?CourseID=99468

This is a slide deck from a technology briefing delivered at Intertech on the Spring Framework.

Published in: Technology, Education
2 Comments
59 Likes
Statistics
Notes
  • Can anybody share the links for Spring core(version 3) certification mock exams or previous exams?
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Let every one Download manke it accessable
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
15,805
On SlideShare
0
From Embeds
0
Number of Embeds
255
Actions
Shares
0
Downloads
0
Comments
2
Likes
59
Embeds 0
No embeds

No notes for slide

Spring Framework Training

  1. 1. Complete Spring Spring 2.5 Oxygen Blast Fall 2008 Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 1
  2. 2. Complete Spring Before we begin… • Good afternoon and welcome! My name is Jim White. • Have you used WebEx before??? • A quick introduction to our meeting framework may be in order. • Especially important, if you have a question raise your “virtual hand.” • Technical difficulties – please use chat or email • Doug Laing at DLAING@intertech.com • Dan McCabe at DMCCABE@intertech.com - or call • 651-994-8558 Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 2
  3. 3. Complete Spring Who is this guy? • Jim White – jwhite@intertech.com • Author J2ME, Java in Small Things – 2002, Manning • International Speaker • Including JavaOne • Contributor to many journals including: • JDJ • DevX.com • JavaPro • Consultant, engineer and architect with several companies • Most recently - Senior Technical Architect at Target Corp. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 3
  4. 4. Complete Spring Objectives • The objectives for today’s talk are to learn about new Spring 2.5 and upcoming 3.0 features. • Understand the migration strategy from Spring 1.x and 2.0 to Spring 2.5. • Learn of possible upgrade issues when moving to Spring 2.5. • See the new autowire annotations. Explore the additional JSR-250 Annotations. • Learn about Spring 2.5 autodetection and stereotype components. • Examine annotated MVC controller configuration. • Learn of the powerful new TestContext Framework for simplified and agnostic unit/integration testing. • Examine the new AOP pointcut annotation. • Learn about Spring 2.5 and AspectJ load-time weaving for AOP. • Hear about the upcoming Spring 3.0 features such as support for REST and Unified EL*. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 4
  5. 5. Complete Spring Requirements • An understanding of Java is expected. • An understanding of Spring (API, config, etc.) is expected. • Preferably at the 2.0 level, but 1.x will probably get you by. • This material will be available to you on-line at: www.intertech.com • Any questions before we begin? Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 5
  6. 6. Complete Spring With a show of (virtual) hands… • How many people use Spring (any version) on their projects today? • How many people have already migrated to Spring 2.5? Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 6
  7. 7. Complete Spring Spring 2.X • Spring 2.0 was released in October 2006. Spring 2.5 was released in November 2007. • Spring 2.0 brought significant changes and additions to the Spring Framework. • While not quite as impactful as Spring 2.0, Spring 2.5 also introduced many new features and some changes. • Spring 2.0 and 2.5 changes are summarized at: http://static.springframework.org/spring/docs/2.5.x/reference/new-in-2.html • This talk focuses on those additions found in Spring 2.5. It is not an exhaustive look, but covers many of the more significant changes. • In order to provide appropriate background for Spring 2.5 features, some 2.0 features are discussed. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 7
  8. 8. Complete Spring Migrating to Spring 2.5 Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 8
  9. 9. Complete Spring From 2.0 to 2.5 • Upgrading to Spring 2.5 from Spring 2.0 should be seamless and backward compatible. • In order to upgrade to Spring 2.5, simply replace the Spring 2.0 JAR file with the Spring 2.5 JAR file(s). • However, in Spring 2.5, Spring MVC has been removed from the core spring.jar file. • Spring Web MVC is now in a separate spring-webmvc.jar. • The Spring Portlet framework is in a separate spring-webmvc-portlet.jar. • Also, the Struts 1.x support has been factored out into 'spring-webmvc- struts.jar'. • Therefore, while the upgrade should be seamless, additional JAR files may need to be added to a project’s classpath or server’s library. • All of the Spring JAR files can still be collectively downloaded in a single all inclusive ZIP file from springframework.org. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 9
  10. 10. Complete Spring From 1.x to 2.5 • Upgrading to Spring 2.5 from Spring 1.x may not be as seamless. • Spring 2.0 removed classes marked deprecated in Spring 1.2.x. • Therefore, code using deprecated 1.x classes will not be compatible with Spring 2.5. • Spring 2.0 also introduced schema guided XML configuration. • Use of Spring 1.2.x DTD for configuration does not allow applications to take advantage of many new Spring 2.0 and Spring 2.5 features. • Therefore moving from DTD to schema configuration, while not required, is a good idea. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 10
  11. 11. Complete Spring Java Requirements • Java platform requirements have been updated for Spring 2.5. • Spring 2.5 now requires JDK 1.4.2 or higher (inclusive of 5 and 6). • This is consistent with Sun’s End of Life process which deprecated JDK 1.3 December 11th, 2006. • Therefore, application servers such as WebSphere 4 and WebSphere 5 will not be able to leverage Spring 2.5. • Some functionality in Spring 2.5 supports Java 5 and Java 6 features. • Obviously, the appropriate JDK is required to leverage these features and cannot be utilized in a Java 1.4.x environment. • Spring 2.5 remains compatible with J2EE 1.3 and higher. Again, some dedicated support has been added for Java EE 5 environments. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 11
  12. 12. Complete Spring Other Framework/APIs • It should also be noted that for those using Spring with other frameworks, there have been some notable changes in support. • Support for Hibernate 2.1 and Hibernate 3.0 has been dropped with Spring 2.5. • Spring 2.5 now requires Hibernate 3.1 or better. • JDO 1.0 is also no longer supported and users of Spring 2.5 must move to JDO 2.0. • Support for iBatis 1.3 has also been dropped in favor of iBatis 2.3 or better. • Many other libraries that Spring works or integrates with may need to be upgraded when moving to Spring 2.5! • A Spring with dependencies downloaded is available from the Spring web site to ensure all appropriate updates are made. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 12
  13. 13. Complete Spring Autowire Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 13
  14. 14. Complete Spring Autowire Annotations • Spring 2.0 introduced configuration by annotation to the Spring Framework. • For example the @Required annotation can be applied to any bean property setter method in the source code. public class AccountServiceImpl implements AccountService { AccountDao dao; @Required public void setDao (AccountDao dao) { this.dao = dao; } public void processAccounts() { ... Account[] accts = dao.getAccounts(nm[]); ... } } • At runtime, as configuration is accomplished, the property (AccountDao in this case) must be set or a BeanInitializationException is thrown. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 14
  15. 15. Complete Spring Autowire Annotations Cont. • Of interesting note, annotations such as this one are accomplished with the help of a BeanPostProcessor in Spring. • Use of the BeanPostProcessor requires use of an application context (versus a bean factory) Spring container. • Source level annotations, like this one, are one of the Spring 2.X features that require Java 5 (or better). Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 15
  16. 16. Complete Spring Autowire Annotations Cont. • In Spring 2.5, a new autowire annotation can be used to autowire beans together by type without the “autowire” attribute in the configuration file. • The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. • The @Autowired annotation can be placed on the dependency injected class’s setter method as shown. public class OrderServiceImpl implements OrderService { private OrderDao orderDao; @Autowired public void setOrderDao(OrderDao orderDao) { this.orderDao = orderDao; } } Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 16
  17. 17. Complete Spring Autowire Annotations Cont. • It can also be placed on the field. public class OrderServiceImpl implements OrderService { @Autowired private OrderDao orderDao; public void setOrderDao(OrderDao orderDao) { this.orderDao = orderDao; } } • Or it can be placed on the constructor. public class OrderServiceImpl implements OrderService { private OrderDao orderDao; @Autowired public void OrderServiceImpl(OrderDao orderDao) { this.orderDao = orderDao; } } Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 17
  18. 18. Complete Spring Autowire Annotations Cont. • In fact, the @Autowired annotation can even be used with an arbitrary method. public class OrderServiceImpl implements OrderService { private OrderDao orderDao; @Autowired public void getReady(OrderDao orderDao) { this.orderDao = orderDao; } } Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 18
  19. 19. Complete Spring Autowire Annotations Cont. • The annotation can even be used to collect all beans of a given type and inject them in an array or collection. public class OrderServiceImpl implements OrderService { @Autowired private OrderDao[] orderDaos; } public class OrderServiceImpl implements OrderService { @Autowired private List<OrderDao> orderDaos; } • By default, the @Autowired annotation implies the dependency is required (like with the @Required annotation above). • However, the default “required” injection behavior can be turned off by using “required=false” as shown below. @Autowired(required=false) private OrderDao orderDao; Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 19
  20. 20. Complete Spring Autowire Annotations Cont. • Autowiring, while convenient, can lead to issues of confusion or exceptions. • This occurs when the Spring container is unable to resolve which bean to wire. • While there is a lot of flexibility in how autowiring is accomplished (by name, type, and constructor), there is little control on how it is invoked. • This lack of fine-grained control has led some experienced Spring users to avoid the autowire feature except in testing and prototyping situations. • However, the new @Autowire annotation also comes with additional annotations that allow more fine-grained control on how it is applied. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 20
  21. 21. Complete Spring Autowire Annotations Cont. • The @Qualifier annotation is used with @Autowired to help explicitly pick which bean to inject when autowiring by type leads to ambiguity. • Consider a bean configuration file where two OrderDao’s have been created. <bean id=quot;orderDao1quot; class=quot;com.intertech.dao.OrderDaoImplquot;> <property name=quot;templatequot;> <ref bean=quot;hibernateTemplatequot;/> </property> </bean> <bean id=quot;orderDao2quot; class=quot;com.intertech.dao.OrderDaoImplquot;> <property name=quot;templatequot;> <ref bean=quot;JPATemplatequot;/> </property> </bean> Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 21
  22. 22. Complete Spring Autowire Annotations Cont. • Use of the @Autowired annotation with the DAO here would lead to a runtime exception since no single bean can be matched by type. @Autowired public void setOrderDao(OrderDao orderDao) { this.orderDao = orderDao; } No unique bean of type [com.intertech.dao.OrderDao] is defined: expected single matching bean but found 2: [orderDao1, orderDao2] Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 22
  23. 23. Complete Spring Autowire Annotations Cont. • To solve the issue and to provide fine-grained control over which bean should be dependency injected, the @Qualifier can be used. @Autowired public void setOrderDao(@Qualifier(quot;orderDao1quot;) OrderDao orderDao) { this.orderDao = orderDao; } • The @Qualifier can be applied on a method or constructor parameter (as shown above) or on the field (as shown below). @Autowired @Qualifier(quot;orderDao1quot;) private OrderDao orderDao; • In these examples, the bean name is used as the @Qualifier value. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 23
  24. 24. Complete Spring Autowire Annotations Cont. • In the bean configuration file, alternatively, a qualifier name can be provided and used by the @Qualifier annotation. <bean id=quot;orderDao1quot; class=quot;com.intertech.dao.OrderDaoImplquot;> <qualifier value=quot;mainDaoquot;/> <property name=quot;templatequot;> <ref bean=quot;hibernateTemplatequot;/> </property> </bean> @Autowired @Qualifier(quot;mainDaoquot;) private OrderDao orderDao; • While there is not time to cover it here, you can create your own custom qualifier annotations to allow for even more discretion when autowiring. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 24
  25. 25. Complete Spring Autowire Annotations Cont. • When using Spring annotations, the source code will also need the appropriate imports. For those shown here, the imports are below. import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Required; Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 25
  26. 26. Complete Spring Autowire Annotations Cont. • The @Autowire and @Required annotations are accomplished in Spring with BeanPostProcessors. • Again, the BeanPostProcessor requires use of an application context. • In order to use the @Autowire annotation, a single Spring provided AutowiredAnnotationBeanPostProcessor bean must be registered. <bean class=quot;org.springframework.beans. factory.annotation.AutowiredAnnotationBeanPostProcessorquot;/> • A more concise means of doing this is by using the new Spring context namespace and the annotation-config element. <beans xmlns=quot;http://www.springframework.org/schema/beansquot; xmlns:xsi=quot;http://www.w3.org/2001/XMLSchema-instancequot; xmlns:context=quot;http://www.springframework.org/schema/contextquot; xsi:schemaLocation=quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsdquot;> <context:annotation-config/> </beans> Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 26
  27. 27. Complete Spring Java/Java EE Standard Annotations JSR-250 Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 27
  28. 28. Complete Spring JSR-250 Annotations • The @Resource annotation is used in • JavaServer Faces (to dependency inject the managed bean) • and in JAX-WS client applications (to dependency inject the Web service endpoint). Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 28
  29. 29. Complete Spring JSR-250 Annotations Cont. • Similarly, the @Resource can be used on a field or setter method in a Spring 2.5 application. • To dependency inject a Spring container managed bean. • The @Resource annotation takes a name attribute. The name specifies the name of a bean in the Spring configuration file. @Resource(name=quot;orderDao1quot;) private OrderDao orderDao; // or @Resource(name=quot;orderDao1quot;) public void setOrderDao(OrderDao orderDao) { this.orderDao = orderDao; } • In effect, the annotation functions like autowiring by name. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 29
  30. 30. Complete Spring JSR-250 Annotations Cont. • If no name is specified then the name of the bean will be derived from the name of the field. • If no name is provided and the name of the field does not match that in the configuration file, then Spring uses type to discern how to wire. • As with other annotations, when using type, there is the possibility for ambiguity (and exception) if more than one bean exists per type. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 30
  31. 31. Complete Spring JSR-250 Annotations Cont. • There are several ways to provide pre/post processing in beans after they are created or destroyed by the Spring container. • In the bean configuration file, initialization and destruction methods can be specified via the init-method and destroy-method attributes. • A bean could also implement the BeanPostProcessor interface (providing postProcessBeforeInitialization and postProcessAfterInitialization methods). Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 31
  32. 32. Complete Spring JSR-250 Annotations Cont. • New @PostConstruct and @PreDestroy annotations offer similar capability. • These annotations can be used on any no-argument method in a bean class. @PostConstruct public void construct(){ System.out.println(quot;I am alivequot;); } @PreDestroy public void destroy() { System.out.println(quot;I am going awayquot;); } Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 32
  33. 33. Complete Spring JSR-250 Annotations Cont. • The @Resource, @PostConstruct, and @PreDestroy annotations are defined in JSR-250 (common annotations for Java). • Therefore, Spring 2.5 is merely supporting well known and now standard Java and Java EE annotations. • In fact, when using @Resource, for example, the code must import javax.annotation.Resource rather than some Spring class/annotation. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 33
  34. 34. Complete Spring Stereotypes Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 34
  35. 35. Complete Spring Autodetecting and Spring Components • In Spring 2.0, the @Repository annotation was introduced to signify a data access object (bean). • This annotation allows the bean to be registered as a “component” without as much configuration. • Consider the typical service to DAO component relationship as setup in a standard Spring configuration file below. <bean id=quot;orderServicequot; class=quot;com.intertech.OrderServiceImplquot;> <property name=quot;orderDaoquot;> <ref bean=quot;orderDaoquot;/> </property> </bean> <bean id=quot;orderDaoquot; class=quot;com.intertech.OrderDaoImplquot;> </bean> Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 35
  36. 36. Complete Spring Autodetecting and Spring Components Cont. • Now, the OrderDao bean can be simply marked as a DAO component using the @Repository annotation. @Repository public class OrderDaoImpl implements OrderDao { ... } • And the configuration file does not even have to carry the DAO component configuration. • In order to use the annotation, the Spring container must be informed to scan for and automatically detect these types of components. • Therefore, the configuration file must include a “component-scan” element as shown below. <bean id=quot;orderServicequot; class=quot;com.intertech.OrderServiceImplquot;> </bean> <context:component-scan base-package=quot;com.intertechquot;> </context:component-scan> Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 36
  37. 37. Complete Spring Autodetecting and Spring Components Cont. • The @Repository is just one of several component annotations now available. • These annotations are known as “stereotype” annotations. • In Spring 2.5, several other stereotype annotations were added to mark components in each layer of the application. • The @Service and @Controller annotations allow service and controller beans to be denoted in a similar fashion. • There is also a @Component generic marker (it is actually the parent annotation to all the stereotype annotations). • This annotation allows any bean to be marked as a component. • These stereotype annotations help to clearly identify the components serving in each role of the application – especially as it relates to the MVC environment. • The Spring framework/container can then use these annotations to provide additional behavior to these components (now and in the future). • For example, these components now make themselves better known for processing by tools or associating them with aspects. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 37
  38. 38. Complete Spring Autodetecting and Spring Components Cont. • Autodected stereotype components are singletons by default. • However, their scope can be explicitly set with the @Scope annotation. @Scope(“prototype”) @Repository public class OrderDaoImpl implements OrderDao { ... } Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 38
  39. 39. Complete Spring Autodetecting and Spring Components Cont. • A name can explicitly be provided to each component. @Repository(“orderDao1”) public class OrderDaoImpl implements OrderDao { ... } • In fact, each component is given a name by default. • Lower camel casing of the class name is used as the default name of the component. • Without the name provided above, the repository’s name would have been “orderDaoImpl” in this example. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 39
  40. 40. Complete Spring Autodetecting and Spring Components Cont. • By default, all components marked with the @Repository, @Service, @Controller and @Component annotations are detected in the scan. • However, the component-scan element in the configuration file offers several filters to include or exclude classes in the scan. • In the example below, a regular expression include filter allows all classes that end in “Dao” to be included in the scan for components. • Likewise, any component marked with a “@Service” annotation are excluded from the scan. <context:component-scan base-package=quot;com.intertechquot;> <context:include-filter type=quot;regexquot; expression=quot;.*Daoquot;/> <context:exclude-filter type=quot;annotationquot; expression=quot;org.springframework.stereotype.Servicequot;/> </context:component-scan> • From the Spring 2.5 documentation, below is a list of the Include and exclude filter types (and associated expressions to use them). Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 40
  41. 41. Complete Spring Autodetecting and Spring Components Cont. Filter Type Example Expression Description annotation org.example.SomeAnnotation An annotation to be present at the type level in target components. assignable org.example.SomeClass A class (or interface) that the target components are assignable to (extend/implement). aspectj org.example..*Service+ An AspectJ type expression to be matched by the target components. regex org.example.Default.* A regex expression to be matched by the target components' class names. custom org.example.MyCustomTypeFilter A custom implementation of the org.springframework.core.type.TypeFi lter interface. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 41
  42. 42. Complete Spring Web MVC Controller Annotations • The Spring Web MVC controller has also been given a set of annotations to reduce its XML configuration in Spring 2.5. • The MVC annotations are available for either the Web (a.k.a. Servlet) or Portlet MVC environments. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 42
  43. 43. Complete Spring Web MVC Controller Annotations Cont. • As discussed in the previous section, the @Controller annotation indicates that a particular bean serves in the role of a controller component. • The @RequestMapping annotation is used in conjunction with the @Controller to map specific requests to the controller. • Used on the class, the @RequestMapping annotation directs specific URLs to the controller. @Controller @RequestMapping(quot;/browseOrders.requestquot;) public class BrowseOrdersController extends AbstractController { @Autowired private OrderService orderService; public void setOrderService(OrderService orderService) { this.orderService = orderService; } public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { List list = orderService.findAllOrders(); return new ModelAndView(quot;browseOrdersquot;, quot;orderListquot;, list); Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 43 } }
  44. 44. Complete Spring Web MVC Controller Annotations Cont. • Used on the methods, the @RequestMapping annotation specifies the handler for particular method (GET/POST/etc.) calls. • This allows any class to serve as controller and allow appropriate traffic to be guided to specific methods. @Controller @RequestMapping(quot;/browseOrders.requestquot;) public class BrowseOrdersController { @Autowired private OrderService orderService; public void setOrderService(OrderService orderService) { this.orderService = orderService; } @RequestMapping(method=RequestMethod.GET) public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { List list = orderService.findAllOrders(); return new ModelAndView(quot;browseOrdersquot;, quot;orderListquot;, list); } } Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 44
  45. 45. Complete Spring Web MVC Controller Annotations Cont. • Now the controller class does not have to be listed as a bean in the bean configuration file. • However, don’t forget to signal the container to scan the appropriate package for controller (or any other) stereotype components. <context:component-scan base-package=quot;com.intertech.webquot;/> • With these annotations, the controller also specifies its own URL mapping. • Therefore, URL mappings should not have to be configured in the bean configuration file with a handler mapping. • Instead, register one of Spring 2.5’s annotation handler mapping beans as shown below. <bean class=quot;org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMappingquot;/> <bean class=quot;org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapterquot;/> Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 45
  46. 46. Complete Spring Web MVC Controller Annotations Cont. • The URL/request mapping for multi-action controllers are typically done on methods since each method responds to multiple URLs. @RequestMapping(quot;/add.requestquot;) public void addHandler() { ... } @RequestMapping(quot;/edit.requestquot;) public void editHandler() { ... } Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 46
  47. 47. Complete Spring Web MVC Controller Annotations Cont. • Handler methods in the controllers are allowed to have varying signatures. • In other words, controller methods may have many arguments and various return types. • The table below specifies allowable argument types that can be used without further annotation in the controller. • That is, the Spring container will automatically locate and pass these types of parameter objects to @RequestMapping methods. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 47
  48. 48. Complete Spring Web MVC Controller Annotations Cont. Parameter Type Description Request Any request type like ServletRequest or HttpServletRequest Response Any response type like ServletResponse or HttpServletResponse Session HttpSession WebRequest org.springframework.web.context.request.WebRequest or NativeWebRequest Locale java.util.Locale InputStream java.io.InputStream Reader java.io.Reader OutputStream java.io.OutputStream Writer java.io.Writer Map java.util.Map Model org.springframework.ui.Model or org.springframework.ui.ModelMap Command Command/form objects Errors org.springframework.validation.Errors BindingResult org.springframework.validation.BindingResult SessionStatus org.springframework.web.bind.support.SessionStatus Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 48
  49. 49. Complete Spring Web MVC Controller Annotations Cont. • Additionally, the @RequestParam annotation can be used to bind HTTP request parameters to a method parameter. public void addCustomer(@RequestParam(quot;custIdquot;) int custId, @RequestParam(quot;custFirst) String firstName, @RequestParam(quot;custLastquot;) String lastName) { Customer c = new Customer(custId, firstName, lastName); ... } • @RequestParam parameters are required by default. • To make them optional, set the required attribute to false. @RequestParam(value=quot;custIdquot;, required=quot;falsequot;) Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 49
  50. 50. Complete Spring Web MVC Controller Annotations Cont. • The @ModelAttribute annotation can also be used on method parameters to bind model data to method parameters. public String processSubmit(@ModelAttribute(quot;custquot;) Customer customer) { ... } • This use of @ModelAttribute gives the controller a reference to the model object typically holding form data. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 50
  51. 51. Complete Spring Web MVC Controller Annotations Cont. • In fact, the @ModelAttribute annotation can also be used in front of a method. • When used in front of a method (method level), the @ModelAttribute annotation serves to mark a method used to pre-populate the model. • @ModelAttribute annotated methods will get executed before the chosen @RequestMapping annotated method in a controller. • In the example below, a date String is put into the model under the name of defaultOrderDate using the method marked with @ModelAttribute. @ModelAttribute(quot;defaultOrderDatequot;) public String setDefault(){ return quot;Jan 01, 2008quot;; } @RequestMapping(method=RequestMethod.GET) public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response, @ModelAttribute(quot;defaultOrderDatequot;) String defaultDate) throws Exception { System.out.println(quot;The default order date is: quot; + defaultDate); ... Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 51 }
  52. 52. Complete Spring Web MVC Controller Annotations Cont. • The pre-population of the data occurs before the @RequestMapping method is invoked (handleRequest in this case). • The call of the pre-populating method is done automatically by the Spring container. • The second @ModelAttribute use in this example shows again how the model data can then be accessed and bound to the method parameter. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 52
  53. 53. Complete Spring The new Testing Framework Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 53
  54. 54. Complete Spring Testing Support • An important tenant of the Spring Framework has always been the development of application code that is easy to test (unit and integration). • To this end, a new Spring TestContext Framework was added in Spring 2.5 to better facilitate unit testing. • Prior to Spring 2.5, Spring provided unit/integration testing support through JUnit. • The new Spring framework allows application testing to be agnostic; independent of any actual testing framework. • This allows JUnit 3.x, JUnit 4.x, TestNG or other unit testing framework to be used under the covers. • However, the new Spring testing framework does require Java 5. • The Spring project team recommends using the new Spring TestContext Framework for all new applications (over JUnit for older applications). Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 54
  55. 55. Complete Spring Testing Support Cont. • As with almost everything in Spring 2.5, unit testing in the new TestContext Framework is driven by annotation. • To demonstrate the TestContext Framework, examine the two simple Spring Beans. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 55
  56. 56. Complete Spring Testing Support Cont. package com.intertech; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Required; public class Stuff { private Thing thing; public Thing getThing() { return thing; } @Autowired public void setThing(Thing thing) { this.thing = thing; } } package com.intertech; public class Thing { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 56 } }
  57. 57. Complete Spring Testing Support Cont. • To create a “main” or driver unit testing class, simply create a Java class and annotate the class with the following TestContext annotations. package com.intertech; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={quot;/applicationContext.xmlquot;}) public class StuffTest { @Autowired private Stuff s; } Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 57
  58. 58. Complete Spring Testing Support Cont. • The first annotation is a JUnit 4 convenience annotation that allows any class to serve as the unit test “runner” without extending any other class. • Without this annotation, the test class would have to extend one of the unit testing framework abstract classes. • In JUnit 3.8 for example, StuffTest would extend org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests • The @ContextConfiguration annotation indicates the location of configuration information files for the test class. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 58
  59. 59. Complete Spring Testing Support Cont. • The locations attribute is an array containing the resource locations of XML bean configuration files. • Typically, the location attribute is set to the same set of bean config files as used in web.xml or other deployment configuration file. • The location attribute is optional. ... @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class StuffTest { ... • If left off, then in this example the configuration information would have to be in a file called “StuffTest-context.xml” in the com.intertech package. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 59
  60. 60. Complete Spring Testing Support Cont. • When using the JUnit 4 @RunWith annotation, any method in the test class becomes a test method by simply annotating it with @Test. • The code below provides two simple unit test methods for the Stuff class above. @Test public void useStuff() { assertNotNull(s.getThing().getName()); } @Test public void checkName(){ assertEquals(s.getThing().getName(), quot;Jimquot;); } • When not using JUnit 4 and @RunWith, the methods may have to adhere to certain naming conventions. • For example, when using JUnit 3.8 the method names would need to begin with “test” (when extending AbstractJUnit38SpringContextTests). Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 60
  61. 61. Complete Spring Testing Support Cont. • A common set of TestContext framework annotations can be used with any underlying test framework • For example, to time a method to ensure it executes in a set amount of time, use the @Timed annotation with a specified milliseconds attribute. @Test @Timed(millis=1000) public void useStuff() { assertNotNull(s.getThing().getName()); } • The list of testing annotations are provided in the table below. Common Testing Annotations @IfProfileValue @ ProfileValueSourceConfiguration @ExpectedException @Timed Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 61 @Repeat
  62. 62. Complete Spring Testing Support Cont. • When using JUnit 4, other methods such as before test and after test methods can be defined with JUnit 4 specific annotations as well. @Before public void start() { System.out.println(quot;starting my testquot;); } @After public void ending() { System.out.println(quot;ending testsquot;); } Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 62
  63. 63. Complete Spring Testing Support Cont. • A common issue when performing unit tests with a real database is that the testing often modifies the data and therefore affects future tests. • Furthermore, many data changing operations cannot be verified outside of a transaction. • For example, a transaction must exist to check the database for a newly inserted row. • In Spring 2.5, the testing framework transactions create and then roll back a transaction for each test. • Test code is written that just assumes the existence of a transaction for each test. But the data is preserved for future tests. • If a transaction should need to commit during a test, the framework can be instructed to have the transaction commit instead of rollback. • A set of transaction annotations are provided to configure and manage the transactions in the unit test. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 63
  64. 64. Complete Spring Testing Support Cont. @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @TransactionConfiguration(transactionManager=quot;txMgrquot;, defaultRollback=false) @Transactional public class FictitiousTransactionalTest { @BeforeTransaction public void verifyInitialDatabaseState() { // logic to verify the initial state before a transaction is started } @Before public void setUpTestDataWithinTransaction() { // set up test data within the transaction } @Test // overrides the class-level defaultRollback setting @Rollback(true) public void modifyDatabaseWithinTransaction() { // logic which uses the test data and modifies database state } @After public void tearDownWithinTransaction() { // execute quot;tear downquot; logic within the transaction } @AfterTransaction public void verifyFinalDatabaseState() { // logic to verify the final state after transaction has rolled back } @Test @NotTransactional public void performNonDatabaseRelatedAction() { // logic which does not modify database state Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 64 } }
  65. 65. Complete Spring New Pointcut Annotation Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 65
  66. 66. Complete Spring AOP Bean Pointcut • In Spring 2.0, annotations were introduced to greatly simplify the configuration of aspects. • In Spring 2.0, an aspect is made from any class using the @Aspect annotation. • Pointcuts designators are then used to indicate when/were the advice of an aspect was triggered. • In the example below, an execution designator is used to signal that the advice should trigger for any method of any class in the com.intertech.dao package. @Aspect public class MyAspect { @Before(quot;execution(* quot;com.intertech.dao.*.(..))quot;) public void doSomething() { ... Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 66
  67. 67. Complete Spring AOP Bean Pointcut Cont. • In Spring 2.0, there are nine (9) types of pointcut discriminators (see table below. execution within target this args @within @annotation @target @args • In Spring 2.5, an additional pointcut discriminator, bean, was added. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 67
  68. 68. Complete Spring AOP Bean Pointcut Cont. • The bean pointcut discriminator allows advice to be targeted based on the name or id of a bean. @Aspect public class MyAspect { @Before(quot;bean(orderDao)quot;) public void countAccess() { System.out.println(quot;Database accessed at:quot; + System.currentTimeMillis()); ... } ... • In this example, the countAccess advice is triggered before any OrderDao bean’s method is invoked. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 68
  69. 69. Complete Spring AOP Bean Pointcut Cont. • The wild card character (‘*’) can be used to specify a collection of beans in the pointcut. @Before(quot;bean(order*)quot;) public void countAccess() { System.out.println(quot;Database accessed at:quot; + System.currentTimeMillis()); ... } • In this example, beans with a name beginning with “order” will trigger the advice. • The bean pointcut is only supported by Spring AOP and not AspectJ implementations. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 69
  70. 70. Complete Spring AOP Bean Pointcut Cont. • Another AOP addition in Spring 2.5 is the support for load-time weaving of aspects into Spring classes. • In Load-time weaving, advice is added or “woven” into the actual class affected by aspects when the class file is loaded. • This is an alternate approach to the current proxy based mechanism in place for AOP within Spring 2.0 (and before). • In this approach, the JVM’s ClassLoader must be adapted to transform the classes as they are loaded into memory. • Load-time weaving is only available when using AspectJ AOP. • Load-time weaving should offer better performance than proxy-based weaving of aspects. • Complete coverage of load-time weaving is beyond the scope of this update. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 70
  71. 71. Complete Spring Other Stuff Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 71
  72. 72. Complete Spring Miscellaneous • Spring 2.5 supports many more features that cannot all be covered in sufficient detail here. • A few miscellaneous additions to Spring 2.5 are listed below. • Spring 2.5 provides support for IBM's WebSphere Application Server’s transaction manager. • Spring 2.0 started offering asynchronous JMS support. • Some additions to support the JCA style of setting up listeners (versus JMS listeners) was added in Spring 2.5. • Also, a new JMS XML namespace was added to simplify JMS configuration. • Spring 2.5 now supports the latest versions of the specified frameworks/APIs below. • Tiles 2 (a template framework) • JSF 1.2 (Java Server Faces – a Web MVC framework) • JAX-WS 2.0/2.1 (the latest Java Web services stack) Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 72
  73. 73. Complete Spring Miscellaneous Cont. • In addition to many of the other dynamic languages it supports, Spring 2.5 has added support for JRuby 1.0. • The sample applications (PetClinic and PetPortal) provided with the Spring 2.5 download have been updated to use the newest features • The Spring documentation has also been overhauled to reflect the many changes, updates and additions in Spring 2.x. • All of the 2.5 framework JARs are OSGi-compliant bundles to ease usage in OSGi environments. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 73
  74. 74. Complete Spring Spring 3.0 Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 74
  75. 75. Complete Spring Spring 3.0 – When? • Spring 3.0 first milestone/release candidate was expected late summer/early fall 2008. • It is still not available. • SpringOne is scheduled for Dec 1-4, 2008. • The release candidate is expected that week. • Juergen Hoeller (co-founder of the Spring Framework Project) is expected to speak on Spring 3.0 • Full release is now expected for Jan ’09. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 75
  76. 76. Complete Spring What is expected in Spring 3.0 • According to interviews/articles by Hoeller, Spring 3.0 will … • Further embrace Java 6. • No longer support Java 1.4 at any level. • Incorporate parts of the non-core modules into the core. • Be completely backward compatible with Spring 2.5 Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 76
  77. 77. Complete Spring Big Spring 3.0 Items • While specific details to certain enhancements/additions are limited, there some indications of big changes/additions. • Full scale REST support in the Spring MVC API • Support for Unified EL which is used in JSPs, JSF, etc. • Annotation support for factory methods • Support for Portlet 2.0 (JSR 286) • Prepatory support for the yet to be released for Servlet 3.0 specification. • We’ll have to wait a bit to get more details. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 77
  78. 78. Complete Spring Spring 2.5 Resources • What’s new in 2.0 and 2.5 from the Spring Framework: http://static.springframework.org/spring/docs/2.5.x/reference/new- in-2.html. • What’s new in Spring 2.5 (Part 1): http://www.infoq.com/articles/spring-2.5-part-1. • Spring 2.5 TestContext Framework example: http://www.springify.com/archives/8 • Pro Spring 2.5 by Machacek et al. (Apress) – expected to be available August 2008. • Info on Spring 3.0: http://www.springify.com/archives/15 Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 78
  79. 79. Complete Spring Summary • Spring 2.0 was released in October 2006. Spring 2.5 was released in November 2007. • In order to upgrade to Spring 2.5, simply replace the Spring 2.0 JAR file with the Spring 2.5 JAR file(s). • Spring Web MVC is now in a separate spring-webmvc.jar. • Spring 2.5 now requires JDK 1.4.2 or higher (inclusive of 5 and 6). • In Spring 2.5, a new autowire annotations can be used to autowire beans together by type without the “autowire” attribute in the configuration file. • The JSR-250 specified @Resource annotation can be used on a field or setter method to dependency inject a Spring container managed bean. • The @PostConstruct and @PreDestroy annotations offer pre and post processing of dependency injected beans. • Several stereotype annotations (@Service, @Controller, @Component) were added (to @Repository) to mark components in each layer of the application. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 79
  80. 80. Complete Spring Summary Cont. • The Spring Web MVC controller has also been given a set of annotations to reduce its XML configuration in Spring 2.5. • In Spring 2.5, an additional pointcut discriminator called bean has been added for Spring AOP. • Load-time weaving of aspects into Spring classes for AspectJ was also added in Spring 2.5 to improve AOP performance. • A new Spring TestContext Framework was added in Spring 2.5 to better facilitate framework agnostic unit testing. • Spring 3.0 is imminent, but details are sketchy. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 80
  81. 81. Complete Spring Thanks!!!!! • Thanks for coming. • We hope you learned something and • Enjoyed the talk. • Come back and see us again. • Plenty of classes on Spring, Struts and other Java/.Net technologies this winter/spring. • Feel free to chat with one of our account reps for more info. • The material can be downloaded from Intertech at: http://www.intertech.com/downloads/Spring2-5v2.pdf. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 81
  82. 82. Complete Spring Intertech Resources • Intertech offers free: • Content packed newsletters • Podcasts through iTunes • YouTube videos • Free Oxygen Blast seminars • Whitepapers and .pdf downloads • For the above and special offers, register for the newsletter at the bottom of our homepage Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 82
  83. 83. Complete Spring Intertech Training • Founded in 1991, Intertech offers a full training line-up: • JEE, open source technologies • .NET, SQL Server, SharePoint • XML, Ajax • Delivery formats include: • Instructor-led public and onsite • Instructor-led night and virtual • Self-paced study • For advanced purchase customers, Intertech offers Elite Rewards™—call 651-994-8558 +23 Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 83
  84. 84. Complete Spring Intertech Consulting • In addition to training, Intertech delivers consulting • Consulting is part of our brand: Instructors Who Consult | Consultants Who Teach • Give your project success with our consulting services • To learn more, contact us at 651-994-8558 +11 Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 84

×