EVALUATION on Tomcat/Eclipse - ITCourseware Tomcat/Eclipse Student Guide ... Integration with Java...
Transcript of EVALUATION on Tomcat/Eclipse - ITCourseware Tomcat/Eclipse Student Guide ... Integration with Java...
Fast Track to Spring 3.x, Spring MVC, and Spring Web Flow
on Tomcat/Eclipse
Student Guide
LearningPatterns™™, Inc. Courseware
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
This material is copyrighted by LearningPatterns Inc. This content and shall not be reproduced, edited, or distributed, in hard copy or soft copy format, without express written consent of LearningPatterns Inc. Copyright © 2004-13 LearningPatterns Inc. For more information about Java Enterprise Java, or related courseware, please contact us. Our courses are available globally for license, customization and/or purchase. LearningPatterns. Inc. [email protected] | www.learningpatterns.com Global Courseware Services 262 Main St. #12| Beacon NY, 12508 USA 212.487.9064 voice and fax Java, and all Java-based trademarks and logo trademarks are registered trademarks of Oracle, Inc., in the United States and other countries. LearningPatterns and its logos are trademarks of LearningPatterns Inc. All other products referenced herein are trademarks of their respective holders.
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
20130401 Copyright © 2004-13, LearningPatterns Inc. All rights reserved i
™
Table of Contents – Fast Track to Spring 3.x, Spring MVC, and Spring Web Flow
Fast Track to Spring 3.x, Spring MVC, and Spring Web Flow ___________________ 1 Workshop Overview _______________________________________________________________ 2 Workshop Objectives ______________________________________________________________ 3 Workshop Agenda_________________________________________________________________ 4 Typographic Conventions ___________________________________________________________ 5 Labs ____________________________________________________________________________ 6 Release Level_____________________________________________________________________ 7
Session 1: Introduction to Spring __________________________________________ 8 Lesson Objectives _________________________________________________________________ 9
Overview _________________________________________________________________ 10 The Challenge of Enterprise Applications______________________________________________ 11 Shortcomings of Java/Java EE ______________________________________________________ 12 What is Spring? __________________________________________________________________ 13 The Spring Modules ______________________________________________________________ 14 The Spring Distribution____________________________________________________________ 15
Lab 1.1 – Setting Up the Environment ____________________________________________ 17 Spring Introduction ________________________________________________________ 33
Managing Beans _________________________________________________________________ 34 A Basic Spring Application_________________________________________________________ 35 Some Bean Classes _______________________________________________________________ 36 Configuration Metadata____________________________________________________________ 37 Declaring Beans__________________________________________________________________ 38 The Spring Container _____________________________________________________________ 39 Working With Spring _____________________________________________________________ 40 A Simple Spring Example __________________________________________________________ 41 Why Bother? ____________________________________________________________________ 42 Some BeanFactory/ApplicationContext API____________________________________________ 43
Lab 1.2 – Hello Spring World____________________________________________________ 44 Dependencies and Dependency Injection _______________________________________ 49
Dependencies Between Objects______________________________________________________ 50 Example of a Direct Dependency ____________________________________________________ 51 Dependency Inversion Principal _____________________________________________________ 52 Example of Dependency Inversion ___________________________________________________ 53 Dependency Injection (DI) in Spring _________________________________________________ 55 Dependency Injection Configuration__________________________________________________ 56 Dependency Injection Example______________________________________________________ 57 Advantages of Dependency Injection _________________________________________________ 58 Dependency Injection Reduces Coupling ______________________________________________ 59
Lab 1.3 – Dependency Injection __________________________________________________ 60 Review Questions ________________________________________________________________ 65 Lesson Summary _________________________________________________________________ 66
Session 2: More About Bean Properties ____________________________________ 68 Lesson Objectives ________________________________________________________________ 69
Working with Properties ____________________________________________________ 70 Configuring Value Based Properties __________________________________________________ 71 Using Value Based Properties _______________________________________________________ 72 Property Conversions _____________________________________________________________ 73
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
20130401 Copyright © 2004-13, LearningPatterns Inc. All rights reserved ii
™
Constructor Injection ______________________________________________________________ 74 Constructor Argument Resolution____________________________________________________ 75 XML Shortcuts - p: and c: Namespaces _______________________________________________ 78 Setter Injection vs. Constructor Injection ______________________________________________ 79 Setter Injection vs. Constructor Injection ______________________________________________ 80
Lab 2.1 – Spring Configuration __________________________________________________ 81 Collection Valued Properties _________________________________________________ 91
Working with Collections __________________________________________________________ 92 Collection Property Example________________________________________________________ 93 Configuring <list> and <set> Properties _______________________________________________ 94 Configuring Collection of Bean References ____________________________________________ 95 Map Valued Properties ____________________________________________________________ 96 java.util.Properties Valued Properties _________________________________________________ 97
Lab 2.2 – Collection Valued Properties ____________________________________________ 98 Additional Capabilities_____________________________________________________ 103
- Factory Methods - ______________________________________________________________ 104 Instance Factory Methods _________________________________________________________ 105 - Bean Aliases - _________________________________________________________________ 106 - Bean Definition Inheritance - _____________________________________________________ 107 Inheritance Example _____________________________________________________________ 108 - SpEL: Spring Expression Language - _______________________________________________ 109 Other SpEL Capabilities __________________________________________________________ 110 - Autowiring - __________________________________________________________________ 111 Autowiring byName Example ______________________________________________________ 112 Autowiring byType ______________________________________________________________ 113 Pros and Cons of Autowiring ______________________________________________________ 114 To Autowire or Not to Autowire ____________________________________________________ 115 Review Questions _______________________________________________________________ 116 Lesson Summary ________________________________________________________________ 117
Session 3: The Spring Container and API _________________________________ 119 Lesson Objectives _______________________________________________________________ 120
ApplicationContext________________________________________________________ 121 ApplicationContext Interface ______________________________________________________ 122 ApplicationContext Implementations ________________________________________________ 123 Constructors____________________________________________________________________ 124 Using an ApplicationContext ______________________________________________________ 125 Spring Resource Access __________________________________________________________ 126 Built-in Resource Implementations __________________________________________________ 127
Lab 3.1 – More about ApplicationContexts _______________________________________ 128 Bean Scope and Lifecycle _________________________________________________________ 132 Bean Scope ____________________________________________________________________ 133 Specifying Bean Scope ___________________________________________________________ 134 Inner Beans ____________________________________________________________________ 135 Compound Names _______________________________________________________________ 136 Depends On ____________________________________________________________________ 137 Bean Creation Lifecycle __________________________________________________________ 138 Bean Creation Lifecycle Details ____________________________________________________ 139 Using the Lifecycle Interfaces for Beans______________________________________________ 140 Bean Destruction Lifecycle ________________________________________________________ 141 BeanPostProcessor ______________________________________________________________ 142 @PostConstruct and @PreDestroy __________________________________________________ 143 Event Handling _________________________________________________________________ 144
Lab 3.2 – Bean Lifecycle _______________________________________________________ 145
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
20130401 Copyright © 2004-13, LearningPatterns Inc. All rights reserved iii
™
Annotation Driven Configuration ____________________________________________ 151 Annotations in Spring ____________________________________________________________ 152 Enabling Spring Annotations_______________________________________________________ 153 @Component and Auto-Detecting Beans _____________________________________________ 154 Annotation-based Bean Definition and DI ____________________________________________ 155 Complete Declarations Using Annotations ____________________________________________ 156 XML Config for Annotations and Scanning ___________________________________________ 157 Other Stereotype Annotations ______________________________________________________ 158 @Resource - Additional Uses ______________________________________________________ 159 @Autowired ___________________________________________________________________ 160 @Autowired Examples ___________________________________________________________ 161 Qualifiers______________________________________________________________________ 162 Lifecycle Annotations ____________________________________________________________ 163 Annotation Configuration - Pro / Con ________________________________________________ 164 A Note on the XML Configuration __________________________________________________ 165 A Brief Note on Annotations_______________________________________________________ 166 Annotation Definition Example_____________________________________________________ 167
Lab 3.3 – Spring Annotations___________________________________________________ 168 Java-based Configuration __________________________________________________ 173
Java Configuration Overview ______________________________________________________ 174 Using Java-based Configuration ____________________________________________________ 175 Dependency Injection ____________________________________________________________ 176 More on How it Works ___________________________________________________________ 177 Dependencies Between Configuration Classes _________________________________________ 178 Other Usage Scenarios____________________________________________________________ 179 Classpath Scanning ______________________________________________________________ 180 Other @Bean Capabiliites _________________________________________________________ 181 Java-based Configuration - Pro / Con ________________________________________________ 182
[Optional] Lab 3.4 – Java-based Config __________________________________________ 183 Maven and Spring_________________________________________________________ 188
About Maven___________________________________________________________________ 189 How We'll Work With Maven______________________________________________________ 190 The POM (Project Object Model) ___________________________________________________ 191 POM - Required Elements_________________________________________________________ 192 POM - External Dependencies _____________________________________________________ 193 Maven Artifacts for Spring ________________________________________________________ 194 Repositories ____________________________________________________________________ 195 Maven Project Structure __________________________________________________________ 196 Eclipse / Maven Integration________________________________________________________ 197 The Lab _______________________________________________________________________ 198 [Optional] Lab 3.5 – Using Maven __________________________________________________ 199
Lab 3.5 – Using Maven ________________________________________________________ 200 Review Questions _______________________________________________________________ 210 Lesson Summary ________________________________________________________________ 211
Session 4: Database Access With Spring __________________________________ 214 Lesson Objectives _______________________________________________________________ 215
Overview ________________________________________________________________ 216 DAO Support___________________________________________________________________ 217 Datasources ____________________________________________________________________ 218 Configuring the DataSource _______________________________________________________ 219 Looking up a DataSource in JNDI___________________________________________________ 220
[Optional] Using Spring with Hibernate_______________________________________ 221 Hibernate Overview______________________________________________________________ 222
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
20130401 Copyright © 2004-13, LearningPatterns Inc. All rights reserved iv
™
Typical Hibernate Configuration File ________________________________________________ 223 Using Hibernate Directly__________________________________________________________ 224 Spring Support for Hibernate ______________________________________________________ 225 LocalSessionFactoryBean _________________________________________________________ 226 Configuring a Hibernate Session Factory _____________________________________________ 227 Contextual Sessions______________________________________________________________ 228 Spring Free DAO________________________________________________________________ 229 What Approach to Use ___________________________________________________________ 230
[Optional] Using Spring with JPA ___________________________________________ 231 Template Support for JPA _________________________________________________________ 232 Managing the EntityManager ______________________________________________________ 233 LocalContainerEntityManagerFactoryBean ___________________________________________ 234 Container-Managed EntityManager _________________________________________________ 235 JEE: Obtaining an EntityManager From JNDI _________________________________________ 236 LocalEntityManagerFactoryBean ___________________________________________________ 237 Additional Spring Configuration ____________________________________________________ 238 Spring Configuration Example _____________________________________________________ 239 JPA Data Access Object __________________________________________________________ 240 Extended Persistence Context ______________________________________________________ 241
[Optional] Lab 4.1 – Integrating Spring and JPA __________________________________ 242 Review Questions _______________________________________________________________ 253 Lesson Summary ________________________________________________________________ 254
Session 5: Transactions ________________________________________________ 256 Lesson Objectives _______________________________________________________________ 257
Spring Transaction Management ____________________________________________ 258 Transaction (Tx) Overview ________________________________________________________ 259 Transaction Lifecycle ____________________________________________________________ 260 Transaction Managers ____________________________________________________________ 261 Configuring Transaction Managers __________________________________________________ 262 JTA Transaction Manager _________________________________________________________ 263 Spring Declarative Transaction Management __________________________________________ 264 Spring Transactional Scope________________________________________________________ 265 Transaction Propagation __________________________________________________________ 266 Transaction Attributes for Propagation _______________________________________________ 267 MANDATORY _________________________________________________________________ 268 NESTED ______________________________________________________________________ 269 NEVER _______________________________________________________________________ 270 NOT_SUPPORTED _____________________________________________________________ 271 REQUIRED____________________________________________________________________ 272 REQUIRES_NEW ______________________________________________________________ 273 SUPPORTS ____________________________________________________________________ 274 Transaction Example _____________________________________________________________ 275 Transaction Attributes – Some Choices ______________________________________________ 276 Specifying Transaction Attributes ___________________________________________________ 278 Additional Transactional Attributes _________________________________________________ 280 Transactional Attributes Guidelines _________________________________________________ 281 Rolling Back and Exceptions ______________________________________________________ 282
Lab 5.1 – Spring Transactions __________________________________________________ 283 Spring Proxies and Direct Invocation ________________________________________________ 292 Example – Invoking Directly ______________________________________________________ 293 Load-Time Weaving _____________________________________________________________ 295 Spring's Load-Time Weaving ______________________________________________________ 296
[Optional] Lab 5.2: Load-Time Weaving _________________________________________ 297
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
20130401 Copyright © 2004-13, LearningPatterns Inc. All rights reserved v
™
[Optional] XML Configuration ______________________________________________ 302 Specifying Transactions Using XML ________________________________________________ 303 Spring Transactions and AOP ______________________________________________________ 304 Defining a Pointcut ______________________________________________________________ 305 Linking Advice With Pointcuts _____________________________________________________ 306 <tx:method> Attributes ___________________________________________________________ 307 Why Use XML Configuration______________________________________________________ 308 Review Questions _______________________________________________________________ 309 Lesson Summary ________________________________________________________________ 310
Session 6: Web Applications with Spring MVC ____________________________ 311 Lesson Objectives _______________________________________________________________ 312
Integration with Java EE ___________________________________________________ 313 Spring and Java EE ______________________________________________________________ 314 Overview of Java EE Web Applications ______________________________________________ 315 Web Application Structure ________________________________________________________ 316 Web Application Components______________________________________________________ 317 ApplicationContext and Web Apps__________________________________________________ 318 Configuring ContextLoaderListener _________________________________________________ 319 Using the Application Context _____________________________________________________ 320
Lab 6.1 – Spring and the Web __________________________________________________ 321 Spring MVC Basics________________________________________________________ 337
What is Spring MVC? ____________________________________________________________ 338 General MVC Architecture ________________________________________________________ 339 MVC Pattern flow _______________________________________________________________ 340 Spring MVC Architecture _________________________________________________________ 341 Simple Search App Model - Servlets/JSP _____________________________________________ 342 Simple Search App Model - Spring MVC_____________________________________________ 343 DispatcherServlet _______________________________________________________________ 344 DispatcherServlet Initialization _____________________________________________________ 345 Controllers_____________________________________________________________________ 346 A Very Simple Controller _________________________________________________________ 347 Control Flow ___________________________________________________________________ 348
Lab 6.2 – Spring MVC Basics___________________________________________________ 349 @RequestParam – Parameter Binding _______________________________________________ 355 Returning Model Data ____________________________________________________________ 356 The JSP Pages __________________________________________________________________ 358 Other Handler Method Capabilities__________________________________________________ 359 Example – Other Handler Capabilities _______________________________________________ 360
Lab 6.3 – Parameters and Models _______________________________________________ 361 View Resolvers _________________________________________________________________ 365 Controller Using Logical Names____________________________________________________ 366 Other View Resolvers ____________________________________________________________ 367
Lab 6.4 – View Resolvers ______________________________________________________ 368 Forms and Command Objects_______________________________________________ 371
Spring MVC Form Tags __________________________________________________________ 372 A JavaBean Command Class_______________________________________________________ 373 Working with Model Classes ______________________________________________________ 374 Request Handling Flow ___________________________________________________________ 375 Exposing Reference Data in the Model _______________________________________________ 376
Lab 6.5 – Forms and Command Objects__________________________________________ 377 Review Questions _______________________________________________________________ 384 Lesson Summary ________________________________________________________________ 385
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
20130401 Copyright © 2004-13, LearningPatterns Inc. All rights reserved vi
™
Session 7: Spring Security Overview______________________________________ 387 Spring Security _________________________________________________________________ 388 Spring Web Security - web.xml_____________________________________________________ 389 Spring Web Security - Spring Configuration __________________________________________ 390 More <security:http> Capabilities ___________________________________________________ 392 Other User Details Services________________________________________________________ 393
Lab 7.1 – Spring Web Security__________________________________________________ 394 Method Security ________________________________________________________________ 399 Method Security - Annotations _____________________________________________________ 400 Method Security - Pointcut Expressions ______________________________________________ 401 Method Security - XML Configuration_______________________________________________ 402
Lab 7.2 – Method Security _____________________________________________________ 403 Session 8: Introducing Spring Web Flow __________________________________ 407
Lesson Objectives _______________________________________________________________ 408 Spring Web Flow Overview _________________________________________________ 409
The Need for Spring Web Flow_____________________________________________________ 410 What is Spring Web Flow? ________________________________________________________ 411 Benefits of Spring Web Flow ______________________________________________________ 412 The Spring Web Flow Project ______________________________________________________ 413 Overview of a Flow in SWF _______________________________________________________ 414 Elements of a Flow ______________________________________________________________ 415 Defining a Flow_________________________________________________________________ 416
Defining Flows____________________________________________________________ 417 Elements of a Flow Definition______________________________________________________ 418 How a Flow Works – Start State ____________________________________________________ 419 How a Flow Works - Transition ____________________________________________________ 420 How a Flow Works – End State ____________________________________________________ 421 How a Flow Works – Web Pages ___________________________________________________ 422 Leaving a Flow _________________________________________________________________ 425
Lab 8.1 – Spring Web Flow Basics_______________________________________________ 426 Basic System Configuration_________________________________________________ 433
Configuring Spring Web Flow _____________________________________________________ 434 Configuring a Flow Registry _______________________________________________________ 435 Integrating with Spring MVC ______________________________________________________ 436 Customizing the Flow Registry _____________________________________________________ 437 Complete Context Configuration (1/3) _______________________________________________ 438 Overall Request Flow ____________________________________________________________ 441
[Optional] Lab 8.2 – Spring Web Flow Configuration_______________________________ 442 Working with Data and Actions _____________________________________________ 447
Data Available to a Flow__________________________________________________________ 448 Flow Instance Variables __________________________________________________________ 449 Binding Model Objects to Views ___________________________________________________ 450 View Pages and Model Binding ____________________________________________________ 451 Flow Inputs in Flow Definitions ____________________________________________________ 452 Actions and Programming in Flow Definitions_________________________________________ 453 Example of Action: <set> _________________________________________________________ 454 Examining an Action: <set> _______________________________________________________ 455
Lab 8.3 – Using Actions in a Flow _______________________________________________ 456 Review Questions _______________________________________________________________ 464 Lesson Summary ________________________________________________________________ 465
Session 9 : More on Spring Web Flow ____________________________________ 467 Lesson Objectives _______________________________________________________________ 468
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
20130401 Copyright © 2004-13, LearningPatterns Inc. All rights reserved vii
™
The Spring Expression Language ____________________________________________ 469 EL Syntax _____________________________________________________________________ 470 More On SpEL Expressions _______________________________________________________ 471 EL Literals and Implicit Objects ____________________________________________________ 472 EL Implicit Objects ______________________________________________________________ 473 Examples of EL Expressions_______________________________________________________ 474 Flow Control Using EL Expressions _________________________________________________ 475
Lab 9.1 – Adding a Shopping Cart_______________________________________________ 476 Data Scopes ______________________________________________________________ 486
Variable Scopes_________________________________________________________________ 487 POST – REDIRECT – GET Idiom __________________________________________________ 488 Request vs. Flash Scope __________________________________________________________ 489 Flow Scope ____________________________________________________________________ 490 Conversation Scope, and Subflows __________________________________________________ 491 Session Scope __________________________________________________________________ 492 Accessing the Scopes Within a Flow_________________________________________________ 493
Lab 9.2 – Using Session Scoped Data_____________________________________________ 494 Flow Language Elements ___________________________________________________ 499
Overview of Language Elements____________________________________________________ 500 Overview of Action Related Elements _______________________________________________ 501 Overview of Other Elements _______________________________________________________ 502 <action-state> Routing ___________________________________________________________ 503 decision-state ___________________________________________________________________ 504 on-* Actions ___________________________________________________________________ 505 Configuring Security _____________________________________________________________ 506
Lab 9.3 – Adding More Behavior________________________________________________ 507 Review Questions _______________________________________________________________ 514 Lesson Summary ________________________________________________________________ 515
Session 10: Programming with Spring Web Flow ___________________________ 517 Lesson Objectives _______________________________________________________________ 518
Creating Custom Actions ___________________________________________________ 519 Programming Your Own Actions ___________________________________________________ 520 Example: Defining a Custom Action_________________________________________________ 521 The RequestContext _____________________________________________________________ 522 The ExternalContext _____________________________________________________________ 523 Using a Custom Action ___________________________________________________________ 524
Lab 10.1 – Custom Actions _____________________________________________________ 525 Validation and Error Reporting _____________________________________________ 532
Validating A Model______________________________________________________________ 533 Defining a Validator Method in the Model ____________________________________________ 534 Validation and ValidationContext ___________________________________________________ 535 The MessageContext _____________________________________________________________ 536 Using Validation ________________________________________________________________ 537 Validation at Work ______________________________________________________________ 538 Defining a Validator Class ________________________________________________________ 539 Resource Bundles _______________________________________________________________ 540 Parameterizing Error Messages _____________________________________________________ 541
Lab 10.2 – Validation _________________________________________________________ 542 Using Subflows ___________________________________________________________ 546
Using Subflows _________________________________________________________________ 547 Branching on Subflow end-state ____________________________________________________ 548 Using Input/Output Variables ______________________________________________________ 549
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
20130401 Copyright © 2004-13, LearningPatterns Inc. All rights reserved viii
™
Using Conversation Scope_________________________________________________________ 551 When to Use Subflows ___________________________________________________________ 553
Lab 10.3 – Subflows___________________________________________________________ 554 Review Questions _______________________________________________________________ 561 Lesson Summary ________________________________________________________________ 562
[Optional] Session 11: Aspect Oriented Programming ___________________________ 564 Lesson Objectives _______________________________________________________________ 565 Overview ______________________________________________________________________ 566 The Issue with Crosscutting Concerns _______________________________________________ 567 Crosscutting Illustrated ___________________________________________________________ 568 Aspect Oriented Programming (AOP) Defined_________________________________________ 569
Spring AOP Introduction___________________________________________________ 570 Spring AOP With AspectJ Annotations ______________________________________________ 571 Defining an Aspect with @AspectJ__________________________________________________ 572 Defining a Pointcut ______________________________________________________________ 573 Defining Advice ________________________________________________________________ 575 Configuring Spring ______________________________________________________________ 576 Triggering Advice _______________________________________________________________ 577 More on How Spring AOP Works___________________________________________________ 578
Lab 11.1 – Hello AOP World ___________________________________________________ 579 Pointcut Expressions and Advice ____________________________________________ 586
Pointcut Expressions _____________________________________________________________ 587 Sample execution Designator Patterns _______________________________________________ 588 Other Designators Available in Spring AOP___________________________________________ 590 Sample Designator Patterns________________________________________________________ 591 Combining Pointcut Expressions____________________________________________________ 592 Kinds of Advice_________________________________________________________________ 593 Advice Examples________________________________________________________________ 594 Around Example ________________________________________________________________ 595
Lab 11.2 – More Spring AOP ___________________________________________________ 597 XML Based AOP Support __________________________________________________ 602
Defining Aspects Using XML______________________________________________________ 603 AOP XML Configuration Example__________________________________________________ 604 Specifying Advice With XML _____________________________________________________ 605
Lab 11.3 – Using AOP XML Configuration [Optional] ______________________________ 606 Other Considerations ______________________________________________________ 610
Spring Proxies and Direct Invocation ________________________________________________ 611 More on Spring Proxies___________________________________________________________ 612 Issues with AOP ________________________________________________________________ 613 Is AOP Worth It ? _______________________________________________________________ 615 Other AOP Capabilities and Functionality ____________________________________________ 616 Review Questions _______________________________________________________________ 617 Lesson Summary ________________________________________________________________ 618
Recap ______________________________________________________________ 620 Recap of what we've done _________________________________________________________ 621 What Else is There_______________________________________________________________ 622 Resources______________________________________________________________________ 623
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 120130401
Fast Track to Spring 3.x and Spring Web
Fast Track to Spring 3.x,Spring MVC, and Spring Web Flow
The Java Developer Education Series
Introduction
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 220130401
Fast Track to Spring 3.x and Spring Web
Workshop Overview
This is an in-depth course covering the use of the Spring 3 framework to build enterprise applications using Java
The course, at a high level, covers the following areas of Spring technology
– Core features of Spring– Data Access Features– Transaction Support– Web Application Support including Spring MVC– Spring Security Overview– Spring Web Flow– Aspect Oriented Programming (AOP)
Introduction
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 320130401
Fast Track to Spring 3.x and Spring Web
Workshop Objectives
To understand the Spring framework and use its capabilities, including:Spring Core: Dependency Injection (DI) and lifecycle management of application objects– Using the Spring API and Spring configuration to write Spring programs– Configuration covers both XML and annotations
Data Access: Data access via Spring's data support– DataSource support– Hibernate and JPA-based DAOs
Transactions: Control transactions declaratively with Spring– Use the Spring annotations and XML configuration elements
Web: Integrate Spring with Web applications and understand the basic structure and use of Spring MVC and Spring Web FlowSecurity: Understand the architecture and basic use of Spring SecurityAOP: Use Spring's AOP (Aspect Oriented Programming) capabilities toinject crosscutting concerns
Introduction
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 420130401
Fast Track to Spring 3.x and Spring Web
Workshop Agenda
Session 1: Introduction to SpringSession 2: More About Bean PropertiesSession 3: The Spring Container and APISession 4: Database Access With SpringSession 5: TransactionsSession 6: Web Applications with Spring MVCSession 7: Spring Security OverviewSession 8: Introducing Spring Web FlowSession 9: More on Spring Web FlowSession 10: Programming with Spring Web FlowSession 11: [Optional] Aspect Oriented Programming
Introduction
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 520130401
Fast Track to Spring 3.x and Spring Web
Typographic Conventions
Code in the text uses a fixed-width code font, e.g.:
JavaInstructor teacher = new JavaInstructor()
–Code fragments use the same font, e.g. teacher.teach()
–We bold/color text for emphasis
–Filenames are in italics, e.g. JavaInstructor.java
–We sometimes denote more info in the notes with a star *
–Longer code examples appear in a separate code box - e.g.
package com.javatunes.teach;public class JavaInstructor implements Teacher {
public void teach() {System.out.println("BeanFactories are way cool");
}}
* If we had additional information about a starred item in the slide, it would appear here in the notes
We might also put other related information that generally pertains to the material in the slide
Introduction
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 620130401
Fast Track to Spring 3.x and Spring Web
Labs
The workshop has numerous hands-on lab exercises, structured as a series of brief labs – Many follow a common fictional case study called JavaTunes
• An online music store– The labs are in the course book, and include detailed instructions
Setup zip files are provided with skeleton code for the labs– Students add code focused on the topic they're working with– There is a solution zip with completed lab code
Lab slides have an icon like in the upper right corner of this slide– The end of a lab is marked with a stop like this one:
Lab
STOP
Introduction
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 720130401
Fast Track to Spring 3.x and Spring Web
Release Level
This manual has been tested with, and contains instructions for, running the labs using the following platforms:
– Spring 3.2.1+ (tested with 3.2.2)• The material is compatible with Spring 3.1 (see notes)
– Spring Web Flow 2.3 (tested with 2.3.2)– Spring Security 3.1 (tested with 3.1.3)– Java 6 or 7– Eclipse Java EE Edition (any fairly recent edition)– Tomcat 7.0.x for the Spring/Web material
Recent similar versions of the software will likely work except for potentially small configuration changes
Lab
Note that there are interdependencies between the different Spring projects– Spring Web Flow 2.3.2 depends on Spring 3.2.1+– We supply all the needed jars in the lab setup, and they are compatible with each other
• If you use them, all the labs should workThe course material is also compatible with Spring 3.1
– However, in order to make the labs easy to run in a lab environment, we supply all the external dependency jars required for the labs
– We supply the dependency jars for 3.2, and some of these may be different than the ones needed for 3.1
– This is the main reason that you should stick with the versions we have tested with– If you want to use a different Spring version, you'll need to make sure all the projects are
compatible, and the dependency jars are the correct version
All labs have been tested on Microsoft Windows using the software listed above– The labs should work on Unix with little modification, except for the database setup scripts,
which need to be use Unix shell scripts
Introduction
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 820130401
Fast Track to Spring 3.x and Spring Web
Session 1: Introduction to Spring
OverviewSpring Introduction
Dependency Injection
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 920130401
Fast Track to Spring 3.x and Spring Web
Lesson Objectives
Understand why we need the Spring Framework
Understand what Spring is, and how it simplifies enterprise application development with Java
Learn how Spring uses configuration information and Dependency Injection (DI)– To manage the beans (objects) in an application– To manage bean dependencies
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1020130401
Fast Track to Spring 3.x and Spring Web
Overview
OverviewSpring Introduction
Dependency Injection
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1120130401
Fast Track to Spring 3.x and Spring Web
The Challenge of Enterprise Applications
Enterprise applications have many complex requirements– Many types, with complex dependencies– Persistent data retrieved from / stored to a data store– Transactional requirements– Remote (distributed) access requirements– Web access requirements
Java / Java EE (Enterprise Edition) provides many capabilities to build enterprise applications– Java SE: Basic building blocks like Java primitives and core
libraries like Collections– Java EE: Enterprise technologies like EJB, Servlets/JSP, JDBC– However, there are shortcomings to the standard Java solution
There really is no formal definition of an enterprise applicationTypically though, some of the characteristics they have are:
– Used in a business environment, often in business-critical domains– Have some form of persistent storage– Have some form of remote access (Web/HTTP, Web service, Distributed Objects, etc)– Require some measure of scalability and fault tolerance
The definition of enterprise application is not important– Many Java applications share some of the requirements that we are outlining here
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1220130401
Fast Track to Spring 3.x and Spring Web
Shortcomings of Java/Java EE
Java/Java EE can have significant shortcomings, including:
Little support for managing the lifecycle of your objects and the dependencies between them– Managing large numbers of objects requires significant effort
Java EE is large and requires a fairly heavyweight app server– Even if using only a subset of capabilities (e.g. Web apps and
transactions), the application server generally supports all of them
Java EE has been difficult to use, and intrusive in its design– Not as big an issue now– Newer releases, such as EJB 3, are less intrusive
Though rich in functionality, due to its complexity, and the complexity of the systems being written, Java / Java EE can have a number of shortcomings for writing these systems
– These programs are composed of many collaborating objects and technologies, which require significant effort to manage
There are many design guidelines to help you with managing the collaboration of objects– Best practices, design patterns, etc.– These help you create a good design to make it easier to write and maintain your program– However, these still require that you write the code that manages the collaboration of objects
The newer Java and Java EE technologies have started to address the ease of use issue– The use of Java annotations (introduced in Java 5), new versions of existing technologies (such
as EJB 3), and completely new technologies such as JavaServer Faces (JSF) have made it significantly easier to use Java
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1320130401
Fast Track to Spring 3.x and Spring Web
What is Spring?
Lightweight framework to build enterprise applications– "Lightweight" meaning non-intrusive in your programming, and
allowing you to use only what you need
It includes the following capabilities– A Dependency Injection (Inversion of Control) container to
manage objects and their dependencies– A DAO package that abstracts JDBC and simplifies its use– An ORM package providing integration with technologies such as
Hibernate and JPA (Java Persistence API)– An AOP package for doing aspect-oriented programming– A Web package to integrate with Web technologies– An MVC package that provides a full Model-View-Controller
based Web framework for Web applications– A security framework for authentication and authorization
DAO stands for Data Access ObjectORM stands for Object-Relational Mapping
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1420130401
Fast Track to Spring 3.x and Spring Web
The Spring Modules
Module diagram from the Spring Reference Documentation
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1520130401
Fast Track to Spring 3.x and Spring Web
The Spring Distribution
Spring home page: http://spring.io/ (see notes)– Can download Spring fromhttp://repo.spring.io/simple/libs-release-local/org/springframework/spring/
Framework distributed as a set of jar files– Each module packaged in its own archive
• e.g. spring-beans-3.2.2.RELEASE.jar– The core Spring download has the all the spring module jars, a
reference manual, and API docsSpring has many dependencies on external technologies– e.g. - Apache commons logging, jars for AOP, and more– Not included in the core Spring download
Maven is commonly used to manage Spring's dependencies– Project and dependency management tool - covered more later
There has been a major reorganization of the Spring websites since the creation of the "Pivotal Initiative" that merged a number of new technology initiatives
– See the following for more info: – http://blogs.vmware.com/vmware/2012/12/the-pivotal-initiative.html– Previously, the Spring website was at http://www.springsource.org
Downloads of the distributions are not very well documented– In general, it is expected that most people will use a tool like maven for dependency
management, rather than downloading a distribution
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1620130401
Fast Track to Spring 3.x and Spring Web
The Spring Distribution
Below left, is the folder structure of the core distribution– Below right, are some of the jars in the libs folder
• Note that there are source and javadoc jars also– At bottom is the docs folder
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1720130401
Fast Track to Spring 3.x and Spring Web
Lab 1.1 – Setting Up the Environment
Lab 1.1: Setting Up the Environment
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1820130401
Fast Track to Spring 3.x and Spring Web
Lab 1.1 – Set up the Environment
Overview: In this lab, we will become familiar with the lab structure, set up our working environment, and test it to make sure it is running well– The end goal is to compile and run an application that requires
the Spring libraries
Objectives: – Become familiar with the lab structure– Set up our environment– Write and run a simple application that requires Spring
Builds on previous labs: None
Approximate Time: 45-60 minutes
Lab
Lab 1.1: Setting Up the Environment
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1920130401
Fast Track to Spring 3.x and Spring Web
Information Content and Task Content
Within a lab, information only content is presented in the normal way – the same as in the student manual pages– Like these bullets at the top of the page
Tasks that the student needs to perform are in a box with a slightly different look – to help you identify themAn example appears below
Tasks to PerformLook at these instructions, and notice the different look of thebox as compared to that above– Make a note of how it looks, as future labs will use this format
OK – Now get out your setup files; we're ready to start working
Lab
Lab 1.1: Setting Up the Environment
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2020130401
Fast Track to Spring 3.x and Spring Web
Setup Environment
Tasks to PerformMake sure Java is installed– Usually in a folder (for Java 7) like
C:\Program Files\Java\jdk1.7.0_nn– If not, then install it - it can be downloaded from:http://www.oracle.com/technetwork/java/javase/downloads/index.html
Check that Spring 3.2 is installed – likely in a folder like:C:\spring-framework-3.2.2.RELEASE– It is not required - you can use it for reviewing the documentation– We supply the needed jars in the setup– It can be downloaded from
http://repo.spring.io/simple/libs-release-local/org/springframework/spring/3.2.2.RELEASE/
Lab
Lab 1.1: Setting Up the Environment
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2120130401
Fast Track to Spring 3.x and Spring Web
Extract the Lab Setup Zip File
To set up the labs, you'll need the course setup zip file. e.g.LabSetup_Spring3x-Web_Tomcat-Eclipse_20130401.zip
Our base working directory for this course will be C:\StudentWork\Spring
–This directory will be created when we extract the Setup zip–It includes a directory structure and files (e.g., Java files, XML files, other files) that will be needed in the labs–All instructions assume that this zip file is extracted to C:\. If you choose a different directory, please adjust accordingly
Lab
Tasks to PerformUnzip the lab setup file to C:\– This will create the directory structure, described in the next slide,
containing files that you will need for doing the labs
Depending on how your training environment, the setup files may be given to you in different ways, including:
– Present on the training machines as a zip file– Already unzipped on the training machine– Given to you by the instructor– Available as a network share or web download
Your instructor will let you know how to access them
Lab 1.1: Setting Up the Environment
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2220130401
Fast Track to Spring 3.x and Spring Web
Lab Directory Structure
StudentWork\Spring contains– Derby: Database files– SpringDependencies: jars for
Spring dependencies– SpringLibraries: Spring jars– Springxxx: Other Spring jars– workspace: Eclipse workspace
StudentWork\Spring\workspacewill contain the following folders:– common: shared files (if any)– LabNN : Folder for Lab NN– LabNN/src : Java source– LabNN/bin/ : compiled code
(Eclipse's standard location)
Lab
To make it easier to open command windows in the lab dirs, we've included a utility in the setup that allows you to right click on a folder to open a command prompt
– Not needed for Windows 7, where you can press and hold the shift key, then right click on a folder and select "Open Command Window Here"
– For earlier Windows versions, install this as follows: • Go to the Resources/CommandPromptHere folder• Right click on the .reg file there, and select Merge• Once you've done that, right clicking on a folder will show a Command Prompt Here
selection in the context menu - Select that to open a command prompt in the directory
Lab 1.1: Setting Up the Environment
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2320130401
Fast Track to Spring 3.x and Spring Web
General Instructions
Root lab folder for this lab is: C:\StudentWork\Spring\workspace\Lab01.1–Already exists in your workspace–You'll create a new Eclipse project in this folder, which contains starter files that we provide–In general, all the lab files are under this project/folder and instructions are given relative to this project/folder
Detailed instructions are included in this lab–Including complete Eclipse instructions, as well as details about the lab requirements
Subsequent labs are similar to this lab, so include fewer detailed instructions
Lab
Lab 1.1: Setting Up the Environment
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2420130401
Fast Track to Spring 3.x and Spring Web
The Eclipse Development Environment
Eclipse: Open source platform for building integrated development environments (IDEs)– Used mainly for Java development– Can be flexibly extended via plugins to add capabilities– http://www.eclipse.org is the main website
This lab includes detailed instructions on using Eclipse– Starting it, creating and configuring projects, etc.
Other labs include fewer Eclipse details - they may just say build/run as previously– Just use the same procedures to build/run as in this lab– Refer back to these lab instructions as needed
Lab
The Eclipse source base was originally developed by IBM– It was released by IBM into open source– IBM's RAD (and previously its WSAD) environment is built on top of Eclipse
Lab 1.1: Setting Up the Environment
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2520130401
Fast Track to Spring 3.x and Spring Web
Launch Eclipse
Tasks to PerformLaunch eclipse: Go to c:\eclipse and run eclipse.exe– A dialog box appears prompting for workbench location (below left)– Set the workbench location to C:\StudentWork\Spring\workspace– If a different default Workbench location is set, change it– Click OK– Close the Welcome screen: Click the X on its tab (below right)
Lab
If Eclipse was installed elsewhere, adjust the paths to the Eclipse executable accordingly– You can put a shortcut to this executable on your desktop
You can also have your lab workspace in a different location– Again, just adjust the lab instructions as required
Lab 1.1: Setting Up the Environment
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2620130401
Fast Track to Spring 3.x and Spring Web
Workbench and Java Perspective
Tasks to PerformYou should be in a Java EE perspective *Open a Java Perspective: Click the Perspective icon at the top right of the Workbench, and select Java (see below left)– Close the Java EE perspective by right clicking its icon, and
selecting close (see below right)Unclutter the Java Perspective by closing some views– Close the Task List, Outline and Hierarchy views (click on the X)– Open the Navigator View (Window | Show View | Navigator)
Lab
The Eclipse Java EE version opens in the Java EE perspective by default– Other versions may open in a different perspective– If you're already in a Java perspective, you don't need to switch perspectives, and there is nothing
for you to do– Note that you'll need the Eclipse Java EE version for the Web and Security labs
To save a our "uncluttered" perspective as the default Java perspective go to– Window | Save Perspective As | Java
You can reset the perspective to its defaults via– Window | Reset Perspective
Lab 1.1: Setting Up the Environment
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2720130401
Fast Track to Spring 3.x and Spring Web
The Java Perspective Lab
Lab 1.1: Setting Up the Environment
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2820130401
Fast Track to Spring 3.x and Spring Web
Create User Libraries
We'll need to include a number of Spring jars in our classpath– We include the Spring jars from the Spring distribution in the setup– We also supply other external dependencies in a separate folder– We'll set these up as a user library for ease of use
Tasks to PerformGo to Window | Preferences | Java | Build Path | User Libraries– Click New… , in the next dialog, call the library Spring, and press OK– Click the Add External JARs… button, browse to StudentWork\Spring\SpringLibraries, select all the jars in that folder, and
click OK (see notes)– Select the Spring library again, click Add External JARs…, browse to
StudentWork\Spring\SpringDependencies, add in all jars in that folderCreates a library with the Spring distribution and dependency jars– We'll use it to configure the project build path
Lab
financial info
We include all the Spring jars from the Spring distribution in our setup– This is for ease of use - the Spring distribution includes a lot of extraneous jars (src and
javadoc) mixed in with the standard jars– This can be confusing when starting out, so we just supply them separately
We supply all needed dependencies in the SpringDependencies folder– These were figured out by using Maven and seeing what dependencies were added to the
project– In this folder, we supply all the external dependencies for all the labs– This is quite a bit more than is needed for this lab
Lab 1.1: Setting Up the Environment
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2920130401
Fast Track to Spring 3.x and Spring Web
Create a Project for our Application
Tasks to PerformCreate a Java Project *– Call the project Lab01.1– Eclipse will then automatically set
the project folder to Lab01.1• This folder already exists in the
workspace• It contains a Java project laid out
for Eclipse– Click Next
– This will bring you to a dialog where you can set the Java Settings for the project
Lab
To create a new Java Project, use the menuitem– File| New | Java Project
There are many other ways to create a project– You can use the new icon on the left hand side of the toolbar, as shown above
You will need to create a new Java project in Eclipse each time the lab instructions tell you to use a new Lab directory
– This happens several times in the course, and you'll need to create a new project each time
Lab 1.1: Setting Up the Environment
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 3020130401
Fast Track to Spring 3.x and Spring Web
Add the Spring Library to the ClassPath
Tasks to PerformIn the Java Settings dialog, click the Libraries tab *– Click the Add Library button, and in the dialog that comes up,
select User Library then click Next– Check off Spring, then click Finish in all open dialogs *
Lab
If you forget to add the library in this step, you can always add it later as follows– Right click on the project, select Properties, then select Java Build Path– Go to the Libraries tab, and add in the Spring library as described above
When the project is created, Eclipse will attempt to compile all the Java source– This will lead to warnings about unused imports, variables, etc.– You can just ignore these – most of them are because the files we give you are just skeletons, and
not complete.– If you want, you can shut these warnings off as follows:
Window | Preferences | Java | Compiler | Errors/Warnings– Go to the "Unnecessary Code" section, and change the settings for "Unused import", "Unused
local or private member", and "Local variable is never read" to "Ignore"
Lab 1.1: Setting Up the Environment
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3120130401
Fast Track to Spring 3.x and Spring Web
Running the Lab
Tasks to PerformWe will use Eclipse to run a skeleton program we supply in TeachMeSpring.javaAfter a clean build (one that is error-free, but not necessarily warning-free), do the following– In the Package Explorer pane,
right click on TeachMeSpring.java(in package com.javatunes.teach under the src folder)
– Select:Run As -> Java Application
– This will automatically find the main method in TeachMeSpringand run it for you
Lab
Lab 1.1: Setting Up the Environment
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3220130401
Fast Track to Spring 3.x and Spring Web
Program Output
You should see output in the Eclipse Console view showing the results of running the program– Similar to that shown below– If you see any exceptions, then you have a problem somewhere
Note: You will follow similar procedures whenever you have a Java program to run in the labs– The only thing that may change is the program class that you'll
need to right click on to run
Lab
STOP
Lab 1.1: Setting Up the Environment
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3320130401
Fast Track to Spring 3.x and Spring Web
Spring Introduction
OverviewSpring Introduction
Dependency Injection
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3420130401
Fast Track to Spring 3.x and Spring Web
Managing Beans
Managing application objects is a core Spring capability
These managed objects are called beans– Just a POJO (Plain Old Java Object) – Bean is a common name (e.g. JavaBeans and EJB)
The Spring container manages objects– Often called the Dependency Injection (DI) or Inversion of
Control (IoC) container– Configuration metadata is used by the container to instantiate,
configure, and assemble your beans– Generally supplied in simple XML format
You write a configuration with bean definitions and dependencies– The container does the work of managing the beans
Spring will create and initialize bean instances based on your configuration data– You can then request those instances from the Spring container by name– We'll see how this works soon
We'll cover the Spring container, and the principles behind it, in more detail later– For now, we will just describe some of its basic capabilities
Spring 2.x added a number of Java 5 annotations that can be used, and Spring 3 added the ability to write the configuration using Java
– We'll cover these laterConfiguration metadata can also be provided in the Java properties format, or even provided programmatically (using Spring's public API)
– These are generally more cumbersome to use, and we won't cover them in this course– The vast majority of Spring users use the XML format– In fact, the Spring IoC container is totally decoupled from the external form of the metadata– It has its own internal format which it uses to store this information
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3520130401
Fast Track to Spring 3.x and Spring Web
A Basic Spring Application
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3620130401
Fast Track to Spring 3.x and Spring Web
Some Bean Classes
Assume the following types (your business objects)– Teacher interface defining our functionality– JavaInstructor: Concrete class, implementing Teacher– Note: Spring strongly advocates programming to interfaces
(see notes)
Let's look at how to manage instances of our types with Springpackage com.javatunes.teach;public interface Teacher {
public void teach();}
package com.javatunes.teach;public class JavaInstructor implements Teacher {
public void teach() {System.out.println("BeanFactories are way cool");
}}
Programming to interfaces provides many advantages by decoupling your code from concrete implementation classes
– This is not a concept unique to Spring– Many design patterns are based on the decoupling gained by programming to an interface– We'll soon see how the Spring framework makes these advantages even more usable and
powerful by helping manage the dependencies that have been abstracted using interfaces
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3720130401
Fast Track to Spring 3.x and Spring Web
Configuration Metadata
A Spring configuration contains bean definitions– And information about your beans (the metadata)– Bean definitions correspond to actual objects in your app that the
Spring container will manage– Typically - many bean definitions and dependencies
Beans are configured with a top level <beans> element– It contains namespace declarations and <bean> elements as
shown in the applicationContext.xml file below
<?xml version="1.0" encoding="UTF-8"?>
<!-- The beans namespace is the default one for the document --><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"/>
</beans>
applicationContext.xml is a fairly standard name for the Spring config file, but you can name it anything that you wantSpring 2.0 and later provided an XML Schema for the XML configuration file
– The examples and lab setup files have the necessary XML namespace information in them to refer to the Spring XML Schema properly
– This is standard XML usage, and we don't go into the details here of how to use an XML Schema– Refer to an XML reference if you need more detail on this– The XML Schema is the recommended way to use Spring, and we'll use it in this course
Typically you'll configure beans such as– Service layer objects, DAO objects, Hibernate session factories, JMS queue references
Some BeanFactory implementations also permit the registration of existing objects that have been created outside the factory (by user code)The schemaLocation property shown in the slide can use a version number if you want to specify a specific spring version, e.g. spring-beans-3.2.xsd
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3820130401
Fast Track to Spring 3.x and Spring Web
Declaring Beans
Each bean definition must specify a package-qualified class name– Usually the bean implementation class (i.e. the class that the
container will instantiate)– In our example, the class attribute, specifies the implementation
as com.javatunes.teach.JavaInstructor
In general, a bean identifier (or name) is also specified– In our example, the id attribute, specifies the identifier as springGuru• It is a label for the bean – both in code and the config file
– A bean can have multiple names (or aliases)– Generally, bean names use camelCase for bean names (e.g.
springGuru)
There are more sophisticated ways to create beans, for example with a factory class, in which case the class name may not be the actual implementation classIf you don't specify a bean name, the container will generate a unique name for the bean
– This can be useful in some more sophisticated scenariosThe springGuru name follows the same convention as Java instance field names
– Bean names start with a lowercase letter, and are camel cased from then onBean names must be unique within the container the bean is hosted inUsually a bean will have a single name
– If it has multiple names, these are considered aliasesThe id attribute must follow the standard XML rules for ids
– There is a limited set of characters that are allowed for XML idsThe name attribute can also be used to specify (multiple) names
– You can have a value that specifies multiple bean ids separated by a comma, semicolon, or whitespace
– If there is no id attribute, the first name becomes the identifier, the rest are aliases– You may use the id and name attributes at the same time
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3920130401
Fast Track to Spring 3.x and Spring Web
The Spring Container
Spring container instantiates/configures application objects– Provides a configuration mechanism for managing objects– And resolves object dependencies based on configuration
org.springframework.context.ApplicationContext– Core API to access the Spring container in your code– Multiple implementations provided for flexibility, e.g.– ClassPathXmlApplicationContext: Commonly used
implementation that loads resources from the class path
ApplicationContext extends interface org.springframework.beans.factory.BeanFactory– Defines many core methods, but usually not used directly– ApplicationContext is the recommended API choice
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4020130401
Fast Track to Spring 3.x and Spring Web
Working With Spring
High level scenario for using Spring includes the following:
Create Spring configuration data for your beans– e.g. In an XML file like applicationContext.xml– Or via annotations in code (covered later)– The "cookbook" telling Spring how to create objects
Initialize Spring container, create access point, e.g.– Create an application context instance that reads config data
• It will initialize the beans in the config file– Use the context instance to access beans
Retrieve beans via the context and use them– e.g. use getBean() to look up a bean by name– getBean() is part of BeanFactory/ApplicationContext API
There are many, many usage scenarios for Spring– And many, many different alternatives for each scenario– Spring is very large, and has a lot of flexibility and capability
In this initial introduction we show you one straightforward way of using Spring– We will gradually introduce more capabilities throughout the course
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4120130401
Fast Track to Spring 3.x and Spring Web
A Simple Spring Example
The code below provides a simple Spring example– Based on applicationContext.xml seen earlier– Instantiates a ClassPathXmlApplicationContext to read
applicationContext.xml from the classpath to create the spring container– Looks up the springGuru bean from the container and uses it– Closes the context (destroying all beans) *
package com.javatunes.teach;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TeachMeSpring {public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
// Note that getBean uses Java generics (no casting needed)Teacher teacher = ctx.getBean("springGuru", Teacher.class);teacher.teach(); // Use our beanctx.close(); // Close the context
}}
ClassPathXmlApplicationContext(String) loads the named file from the classpath– Uses Spring-based resource classes (org.springframework.core.io.Resource
implementations) to access the file– The resource classes abstract access to resources - often used by other classes to access data– ClassPathResource is a concrete implementation that allows you to easily access resources
on the classpath, e.g. Resource resource = new ClassPathResource("applicationContext.xml");
– This is how ClassPathXmlApplicationContext accesses its resourcesThe context implementations uses Spring resources to locate the configuration files
– The Resource interface allows you to flexibly specify paths to resources as resource strings– These are then mapped by a particular implementation to the actual resource, for example a file
on a file system or from the Java classpathA bean definition can be seen as a recipe for creating one or more actual objects
– The container looks at the recipe for a named bean when asked, and uses the configuration metadata encapsulated by that bean definition to create (or acquire) an actual object
Closing the context reclaims all the resources and does any needed cleanup– Good practice in standalone applications, even in a small program like this which is terminating
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4220130401
Fast Track to Spring 3.x and Spring Web
Why Bother?
The example looks like a lot of work to create a single object !
Main benefit: We've decoupled our code from a dependency on the implementation class JavaInstructor– Our code does not need to know about JavaInstructor– We just know about the functionality we need
• i.e. The Teacher interface (which JavaInstructor implements)– We can use any conforming implementation in our configuration
• Our client code will not change– This can be very useful for complex systems
We'll soon see additional capabilities that make Spring useful
In this simple example, it looks like we've done quite a bit of work to instantiate a single instance of a single class
– What is the benefit?
The decoupling we've achieved seems like a simple thing, but it has a lot of benefits, especially when maintaining large systems
– We'll see how useful it can be when we explore more of the capabilities
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Some BeanFactory/ApplicationContext API
boolean containsBean(String): returns true if BeanFactorycontains a bean definition or instance with the given name<T> T getBean(String, Class<T> requiredType): Returns a bean instance, registered under the given name– Spring 3 style using Java generics (see notes) and is preferredObject getBean(String): Old style – non generics version– Requires cast
Class<?> getType(String name): Returns the Class of the bean with the given nameboolean isSingleton(String): Determines whether or not the named bean is a singletonString[] getAliases(String): Return the aliases for the given bean name, if anyMany more methods - view the javadoc for more details
The methods shown are a part of the BeanFactory API - inherited by ApplicationContextgetBean(String, Class) returns either a singleton (shared) instance, or newly created bean– NoSuchBeanDefinitionException thrown if the bean can't be found– BeansException thrown if an exception occurred while instantiating/preparing the bean– BeanNotOfRequiredTypeException thrown if the bean is not of the required type
Object getBean(String) returns an object – which is then cast to the required type– The newer getBean(String,Class) method is generally preferred.
getType(String) throws NoSuchBeanDefinitionException if the bean can't be foundisSingleton(String) throws NoSuchBeanDefinitionException if bean can't be foundThe method <T> T getBean(String, Class<T> requiredType) may look strange
– The first <T> in the return type simply indicates that this is a generic method, parameterized by the type parameter <T>
– The T return value indicates that the return type is generic (that is, it will take on different types based on the <T> parameter)
– The Class<T> argument indicates that when you call the method, you pass in the class which specifies what type <T> actually is in that call
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4320130401
Fast Track to Spring 3.x and Spring Web Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4420130401
Fast Track to Spring 3.x and Spring Web
Lab 1.2 – Hello Spring World
Lab 1.2: Hello Spring World
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4520130401
Fast Track to Spring 3.x and Spring Web
Lab 1.2 – Hello Spring World
Overview: In this lab, we will create and use a Spring context to access a bean instance– The end goal is to build a complete (and simple) Spring
application and run it– This lab uses the JavaInstructor, Teacher, and TeachMeSpring types shown previously in the student manual
Objectives: – Become familiar with the different parts of a basic Spring
program– Write and run a simple Spring application
Builds on previous labs: 1.1
Approximate Time: 20-30 minutes
Lab
The purpose of this lab is to become familiar with the different parts of a Spring application– Accordingly, the program is as simple as we can make it– It mirrors the code already shown in the previous section
In later labs, we'll work with more complex applications
Lab 1.2: Hello Spring World
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4620130401
Fast Track to Spring 3.x and Spring Web
Writing and Configuring a Bean in Spring
Tasks to PerformContinue to work in the Lab01.1 projectOpen up the JavaInstructor.java fileThe class is in the com.javatunes.teach package, under srcMake sure JavaInstructor implements the Teacher interface– Remember that we code to interfaces to decouple us from a
specific implementationOpen up the src/applicationContext.xml file– Click the Source tab to edit it– Finish up the declaration of the <bean> element by declaring:
• An id of springGuru• A class of com.javatunes.teach.JavaInstructor
Lab
There are two other files in the src tree that we will use in the next lab– InfoSource.java and SpringCourseBook.java– Ignore these for now
Lab 1.2: Hello Spring World
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4720130401
Fast Track to Spring 3.x and Spring Web
Using a Bean in a Program
Tasks to PerformOpen up TeachMeSpring.java, look for the TODO comments, and add in the following code– First, create a ClassPathXmlApplicationContext to read
applicationContext.xml– Next, look up the springGuru bean from the context– Call teach() on the springGuru bean– Finally, call close() on the context
Make sure you have no compilation errors in your code
Run the TeachMeSpring program again– Run the same way as in previous labs– You should see the output from the teach() method
You've successfully configured and used a bean with Spring– Congratulations !
Lab
Lab 1.2: Hello Spring World
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4820130401
Fast Track to Spring 3.x and Spring Web
Logging and Additional Things (Optional)
We've provided a log4j.properties file in src– This configures some of the logging that Spring will do– You can reduce the logging output by opening this file, and
changing the INFO to WARN at the top line of the file:log4j.rootLogger=WARN, stdout
– You can increase the logging by using DEBUG instead
Other things to try– Try looking up the bean by a different name – what happens?– Try casting the bean you look up to a JavaInstructor
instead of a Teacher• Does this work? • Is it a good idea? (see notes)
– Change your code back to your original solution before going on STOP
Spring has logging built into it– It uses commons-logging by default, which will detect the log4j jar file and use that if it is on the
classpath– You can see the logging by properly configuring it, as we do in the log4j.properties file– The details of log4j are beyond the scope of this course
Casting the bean you look up to a JavaInstructor will work– These are POJOs, and the actual type is JavaInstructor– It's not a good idea though, because you are defeating the purpose of decoupling your code from
the actual implementation type
Lab 1.2: Hello Spring World
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4920130401
Fast Track to Spring 3.x and Spring Web
Dependencies and Dependency Injection
OverviewSpring Introduction
Dependency Injection
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5020130401
Fast Track to Spring 3.x and Spring Web
Dependencies Between Objects
Different objects work together in an OO application– e.g., Object A directly uses Object B to accomplish a goal– Object A depends on Object B
Direct dependencies can lead to unwanted traits– Rigidity: Hard to make changes - they affect many other parts of
the system– Fragility: Changes cause unexpected failures in other system
areas– Immobility: Hard to reuse functionality elsewhere - modules
can't be disentangled
We'll show a direct dependency example, then show an alternative approach using Dependency Inversion
In straightforward applications, Object A will often just create an instance of Object B and use it– Object A is highly coupled to, and directly dependent on, Object B
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5120130401
Fast Track to Spring 3.x and Spring Web
Example of a Direct Dependency
Assume JavaInstructor uses SpringCourseBook– Below, JavaInstructor creates a SpringCourseBook
instance directly– JavaInstructor depends on the lower level module details– If the data source changes - e.g. to a SpringWiki, then JavaInstructor code must change (see notes)
public class JavaInstructor implements Teacher {SpringCourseBook springBook = new SpringCourseBook();public void teach() {
System.out.println(springBook.getData());}
}
public class SpringCourseBook { // package statements not shown *public String getData() {
return "Dependencies are not so cool";}
}
Assume that all the classes in the examples in this session are in the com.javatunes.teachpackage
– We'll be leaving out all the package statements in the Java code examples for brevityAssume we want to get our information from a class called SpringWiki
– Not shown, but assume it has a getData() methodIn that case, JavaInstructor might need to be changed to something like that below
public class JavaInstructor implements Teacher {
SpringWiki springWiki = new SpringWiki();
public void teach() {
System.out.println(springWiki.getData());
}
}
– This is not such a big deal if you have to change it in one place– But imagine if you had to change it in 100 places, or 10,000 places
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5220130401
Fast Track to Spring 3.x and Spring Web
Dependency Inversion Principal
High level or low level modules should should depend upon abstractions and not upon each other– Use abstractions, e.g. interfaces, that all modules depend on– High level modules are written in terms of abstractions (the
interfaces), and not directly in terms of low level modules– Dependencies exist, but not exposed in implementation classes
Using this design strategy has a number of advantages:
– Facilitates less coupled components• With a high degree of separation of responsibilities
– Produces greater flexibility• Implementations can be swapped without affecting other modules
– Facilitates reuse of components• They're less coupled to other parts of an application
Dependency Inversion is not a new idea– The idea of "Programming to Interfaces" has been around since long before Java– It has been used in non-OO languages also, for example the stdio module in the C programming
language abstracted away the details of the actual devices doing the output
Many people don't use this design in building applications– Even though we know of good design principals, there is no way to make sure people use them
We'll soon look at Spring's Dependency Injection which makes this design strategy even easier to use
We talk of modules here, which in Java are basically reflected as dependencies between different classes
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5320130401
Fast Track to Spring 3.x and Spring Web
Example of Dependency Inversion
Both JavaInstructor and SpringCourseBook depend on InfoSource (an interface) – neither depend on the other
public class JavaInstructor implements Teacher {private InfoSource info;public void setInfo (InfoSource infoIn) {
info=infoIn;}public void teach() {
System.out.println(info.getData());}
}
public class SpringCourseBook implements InfoSource {public String getData() {
return "Dependencies are not so cool";}
}
public interface InfoSource {public String getData();
}
In the code example, we can see that JavaInstructor knows nothing about SpringCourseBook– Instead, it depends on the InfoSource interface (the abstraction)– When JavaInstructor is created, it is initialized with an instance of some InfoSource
implementation– However, it doesn't know any details of this implementation, and doesn't even know its exact
type
SpringCourseBook likewise depends on the abstraction (it implements the InfoSource interface)– The abstraction (the interface) is the common language that lets the different part of the system
work together with depending directly on each other
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5420130401
Fast Track to Spring 3.x and Spring Web
Example of Dependency Inversion
Below, JavaInstructor is initialized with a SpringCourseBook instance (that implements InfoSource)
– JavaInstructor only sees this as the InfoSource type– We could initialize JavaInstructor with any type that
implemented InfoSource – e.g. a SpringWiki– We've decoupled the modules, and made them more flexible and
easier to use, reuse, and maintain
public class TeachMeSpring {
public static void main(String[] args) {SpringCourseBook springBook = new SpringCourseBook();JavaInstructor myInstructor = new JavaInstructor();myInstructor.setInfo(springBook);myInstructor.teach();
}}
In the example above, we are still creating SpringCourseBook in a fairly straightforward way– This exposes the actual implementation class of the lower level module (SpringCourseBook)
in our TeachMeSpring code– There are other, more sophisticated, ways to create these lower level modules– For example, we could use factories of some sort to more completely abstract which
InfoSource is being used– We will soon show how Spring can do this for you
Whenever you have modules depending on one another, something has to know about the implementation details
– Even if it's abstracted through multiple layers, there is still a layer somewhere which creates the instance of the actual implementation
– The goal is to do this in a way that makes your code easier to write, reuse, and maintain
We'll see how Spring deals with this soon
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5520130401
Fast Track to Spring 3.x and Spring Web
Dependency Injection (DI) in Spring
With Dependency Injection, Spring lets you abstract dependencies even more– The Spring container can initialize and inject dependencies into
a bean• Via constructors, properties in the bean, or arguments to a factory
method
Dependencies are defined in the Spring configuration– The Spring container uses these dependency definitions to
initialize the bean– No need to explicitly initialize dependencies in your code
Your bean classes are normal POJO classes– You only need appropriate setter methods or constructors
needed to initialize the dependencies– There is nothing else special about the bean classes
Dependency injection is a fancy way of saying that the container will initialize all the dependencies in the bean when the bean is created
– The bean has to be a bean whose lifecycle is managed by the container
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5620130401
Fast Track to Spring 3.x and Spring Web
Dependency Injection Configuration
The Spring configuration below uses DI
– Declares two beans: springBook and springGuru– <property name="info" ref="springBook"/> tells the
container to initialize the info property of springGuru• Using the instance of SpringCourseBook defined above it
– Uses setter injection - calling setInfo() on springGuru– You don't need to write any code for the injection to happen
<?xml version="1.0" encoding="UTF-8"?>
<beans … > <!-- Namespace declarations omitted -->
<bean id="springBook" class="com.javatunes.teach.SpringCourseBook"/>
<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"><property name="info" ref="springBook"/>
</bean>
</beans>
The container first creates an instance of SpringCourseBook, with the id springBookThe container next creates an instance of JavaInstructor using the no-arg constructor
– To accomplish the DI, the container calls the setInfo method, passing in the instance of SpringCourseBook that it had created
– The result is a fully initialized JavaInstructor instanceThe <property> element tells the container to use setter injection to initialize the dependency
– Setter injection uses the standard setter methods on your bean– It follows the standard property naming conventions, so if the property is named info, it will
call the setInfo method to initialize the dependency– There are other ways of initializing the dependency, such as constructor injection, that we'll see
laterThe bean reference can also be declared using a nested <ref> element as shown below<property name="info"><ref bean="springBook"/></property>
– Generally, the ref attribute shown in the slide is easier to use and understand– You can use the nested element if for some reason it is clearer to express it this way than as an
attribute (this is also provided for backwards compatibility with earlier Spring releases)
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5720130401
Fast Track to Spring 3.x and Spring Web
Dependency Injection Example
The example below shows how to use our beans with Spring– Our main code is decoupled from JavaInstructor - it is
written in terms of the Teacher interface– JavaInstructor, is totally decoupled from the concrete class SpringCourseBook, it's written in terms of InfoSource
– The JavaInstructor instance's info property is injected with a SpringCourseBook instance by the Spring container• This is transparent to all your code
// imports not shownpublic class TeachMeSpring {
public static void main(String[] args) {ClassPathXmlApplicationContext ctx = new
ClassPathXmlApplicationContext("applicationContext.xml");Teacher teacher = ctx.getBean("springGuru", Teacher.class);teacher.teach();
}}
Note that your SpringCourseBook and JavaInstructor class definitions didn't need to change to use DI
– Of course, they had to support the design principle of Dependency Inversion, which we had already done
– Once this was done, we didn't need any changes or additional code to support DINote also that there is nothing in your TeachMeSpring code which shows that JavaInstructordepends on SpringCourseBook
– This is defined in your configuration, and handled for you by the containerNote that the no-arg constructor is present by default in JavaInstructor since we haven't defined any constructors at all
– If we defined constructors, and still wanted to use only setter injection, as for the configuration file in this example, we would have to include a no-arg constructor
– We'll take a look at constructor injection, which allows us to use constructor arguments, a little later
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5820130401
Fast Track to Spring 3.x and Spring Web
Advantages of Dependency Injection
DI reduces coupling between modules in your code– Coupling is basically a measure of the dependencies
We've seen this reduction in two ways in our example:– JavaInstructor is not coupled to SpringCourseBook– TeachMeSpring is not coupled to JavaInstructor or SpringCourseBook
The dependencies are still there but not in the code– Dependencies are moved to the spring configuration– They're injected into beans without your needing to write code– Commonly referred to as wiring beans together
This leads to more flexible code that is easier to maintain– At a cost – using Spring, and maintaining the spring configuration
Coupling is the measure of how much a module of code relies on other modules– Loosely coupled code is generally considered better code
Consider some of the following scenarios, and how DI makes them easier– Testing your code with testing framework such as JUnit can be much easier with DI – you can
configure the application to use mock objects wherever you want – without changing your code at all
– Testing different versions of classes can be done just by changing the configuration metadata– In fact, any implementation class that implements the particular interfaces being used can be
swapped into your program simply by changing the configuration informationThere is debate about how worthwhile DI and frameworks like Spring are
– However, the principles that it is based on that lead to loose coupling are widely accepted– Spring simply makes it easier to apply these principles– The effort required to adopt and use Spring is not trivial, but for larger projects the initial cost
of adopting Spring can be well worth it
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5920130401
Fast Track to Spring 3.x and Spring Web
Dependency Injection Reduces Coupling
The simplest case, JavaInstructor coupled to SpringCourseBook
JavaInstructor coupled to InfoSource only– TeachMeSpring coupled to JavaInstructor and SpringCourseBook
Using DI - TeachMeSpringonly coupled to Teacher– JavaInstructor only
coupled to InfoSource
JavaInstructor SpringCourseBook
InfoSource<<interface>>
creates
JavaInstructor
SpringCourseBookTeachMeSpringimplements
creates
InfoSource<<interface>>
TeachMeSpring
Teacher<<interface>> JavaInstructor
implements
looks up
ApplicationContext
injects
In the slide, we show diagrams of the three different ways we structured our code in the earlier slides
In the DI version, the couplings are ONLY to interfaces– This is much better than being coupled to actual implementation classes– It increases flexibility, testability, and ease of maintenance
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6020130401
Fast Track to Spring 3.x and Spring Web
Lab 1.3 – Dependency Injection
Lab 1.3: Dependency Injection
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6120130401
Fast Track to Spring 3.x and Spring Web
Lab 1.3 – Dependency Injection
Overview: In this lab, we'll work with Spring's DI capabilities– We will add a property (a dependency on another bean) to the JavaInstructor class, and initialize it using Spring DI
– The main program will not change at all– Again, the program is kept very simple so the concepts will be
clear
Objectives: – Become familiar with Spring DI, and use it in a program
Builds on previous labs: 1.2
Approximate Time: 20-30 minutes
Lab
Lab 1.3: Dependency Injection
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6220130401
Fast Track to Spring 3.x and Spring Web
Writing and Configuring a Bean in Spring
Tasks to PerformContinue to work in the Lab01.1 project
Open up SpringCourseBook for editing– Make sure that SpringCourseBook implements the InfoSource interface
Open up JavaInstructor for editing– Add in a property called info, of type InfoSource– You'll need an instance field of type InfoSource, as well as a
getter/setter method for this field– Modify the teach() method to print out the data from the info
properties getData() method
We won't initialize the info property – that will be done with DI
Lab
All the classes we're working with are in the com.javatunes.teach package
Lab 1.3: Dependency Injection
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6320130401
Fast Track to Spring 3.x and Spring Web
Using a Bean in a Program
Tasks to PerformOpen up the src/applicationContext.xml file– Add in a new bean element for SpringCourseBook
• Give it an id of springBook– Modify the <bean> element for springGuru by initializing its info property with a <property> element• Use the springBook bean to initialize the info property
Run the program as before– The output should now be whatever data the SpringCourseBook returns
– The main program doesn't change at all – the JavaInstructordependency on SpringCourseBook is completely hidden
– JavaInstructor is also decoupled from SpringCourseBook
Lab
Lab 1.3: Dependency Injection
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6420130401
Fast Track to Spring 3.x and Spring Web
Additional Things to Try (Optional)
In applicationContext.xml, try leaving out the initialization of the springGuru bean's info property– Run your program– What happens? Why?
Change your code back to your original solution before going on
STOP
Lab
Lab 1.3: Dependency Injection
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6520130401
Fast Track to Spring 3.x and Spring Web
Review Questions
What is Spring?
How does Spring help you to build enterprise applications?
What is Dependency Injection, and how does it work in Spring
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6620130401
Fast Track to Spring 3.x and Spring Web
Lesson Summary
Spring is a lightweight framework for building enterprise applications whose capabilities include:– Dependency Injection– Persistence support (DAO and ORM)– AOP capabilities– Integration with standard Web technologies– An MVC based Web package
Spring helps build complex enterprise applications– Provides a non-intrusive, lightweight solution for managing
complex dependencies between Java objects– Supplies many of the important capabilities of Java EE in a less
complex and lighter weight manner
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6720130401
Fast Track to Spring 3.x and Spring Web
Lesson Summary
Spring supports loose coupling between components– Promotes technique of coding to interfaces, rather than
concrete implementation classes– This by itself is an important design technique,
Provides support for initialization of beans and their dependencies through configuration– Can be done using XML configuration files
Dependency Injection is used by the Spring container to inject bean dependencies based on configuration data– Allows complete decoupling of your code from concrete
implementation types
Session 1: Introduction to Spring
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6820130401
Fast Track to Spring 3.x and Spring Web
Session 2: More About Bean Properties
Working with PropertiesCollection Valued Properties
Additional Capabilities
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6920130401
Fast Track to Spring 3.x and Spring Web
Lesson Objectives
Gain a deeper understanding of Spring's core capabilities related to bean properties and dependencies
Initialize simple and complex bean properties using Spring configuration
Understand and use constructor injection, and understand its strengths and weaknesses
Work with collection valued bean properties
Understand how Spring supports factory methods
Understand how autowiring works
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 7020130401
Fast Track to Spring 3.x and Spring Web
Working with Properties
Working with PropertiesCollection Valued Properties
Additional Capabilities
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 7120130401
Fast Track to Spring 3.x and Spring Web
Configuring Value Based Properties
Spring also allows configuration of value based properties– Containing simple values such as an int or String
Similar to configuring dependencies– Configure the property value using a string representation of
the bean property– At bottom, we configure a string property of JavaInstructor
called favoriteTopicpublic class JavaInstructor implements Teacher {
// Much detail omitted …private String favoriteTopic;public void setFavoriteTopic (String topic) {
favoriteTopic = topic;}public String getFavoriteTopic() { return favoriteTopic; }
}
<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"><property name="favoriteTopic" value="Dependency Injection"/><!-- Other detail omitted … -->
</bean>
Value based bean properties hold simple values rather than references to other beans (dependencies)Once the JavaInstructor instance (with an id of springGuru) has been created, the Spring container will set the favoriteTopic property value by calling setFavoriteTopic on the instance with an argument of "Dependency Injection"
– In this case there is no conversion required, because the property is a string– If the property was of a different type, then Spring will use a JavaBean's PropertyEditor to
convert the string representation into the expected typeThe property value can also be declared using a nested <value> element as shown below<property name="favoriteTopic">
<value>Dependency Injection</value>
</property>
– Generally, the value attribute shown in the slide is terser, and easier to use and understand– You can use the nested element if for some reason it is clearer to express it this way than as an
attribute, or hard to express as an attribute– The nested form is also provided for backwards compatibility with earlier Spring releases
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 7220130401
Fast Track to Spring 3.x and Spring Web
Using Value Based Properties
The favoriteTopic property is set by the Spring container when the bean is instantiated– No dependency on any Spring API in JavaInstructor
These properties are normal Java properties– For example, if the Teacher interface exposed the favoriteTopic property, we could use it as shown below
– It's transparent to bean users that Spring is involved in initializing a property
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Teacher teacher = ctx.getBean("springGuru", Teacher.class);System.out.println("My favorite topic is " +
teacher.getFavoriteTopic());
One of the nice things about using Spring is that a great deal of it does not directly require the use of any Spring-specific API
– You write your beans as POJOs– Once you retrieve a bean, code that uses it is the same as for any other POJO
Our Teacher interface would now look like the following:public interface Teacher {
public String getFavoriteTopic();
public void teach();
}
In this example, we've decided that how you set a teacher's favorite topic is not exposed in the Teacher interface
– This is to let implementations do it in different ways– In our simple JavaInstructor, it is set via a setter method and the Spring configuration– More complex classes might, for example, go to a database to determine what is the teacher's
current favorite topic
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 7320130401
Fast Track to Spring 3.x and Spring Web
Property Conversions
Spring automatically converts strings in the configuration to the type of its property in the Java class– It uses Java PropertyEditors– Supports all the standard primitive and wrapper types– Below, a java.lang.Double property (called age) is configured– The string "35" is automatically converted to a Double value
public class JavaInstructor implements Teacher {// Much detail omitted …private Double age;public void setAge (Double d) {
age = d;}public Double getAge() { return age; }
}
<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"><property name="age" value="35"/><!-- Other detail omitted … -->
</bean>
PropertyEditors are part of the JavaBeans specification– Designed to facilitate conversion of user entered text values into Java values of some type– Spring uses them to convert the text strings in the configuration file into the proper type of a
bean property– There is built in support for converting to the Java primitive types and wrappers– You can also register your custom PropertyEditors – either one of Spring's, or one that you
write yourself
In the example in the slide, the Spring container figures out the type of the age property (using reflection)
– It then uses one of the standard PropertyEditors to convert the string "35" into an instance of the Double wrapper class
– This Double instance is then used to initialize the age property of the JavaInstructorinstance
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 7420130401
Fast Track to Spring 3.x and Spring Web
Constructor Injection
Properties can be injected using constructors– Via <constructor-arg> elements in the config file– Requires a matching constructor in the implementation class– Can initialize both simple properties and bean references
public class JavaInstructor implements Teacher {private InfoSource info;private String favoriteTopic;
public JavaInstructor(InfoSource infoIn, String topicIn) {info = infoIn;favoriteTopic = topicIn;
}// Much detail omitted …
}
<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"><constructor-arg ref="springBook"/><constructor-arg value="Dependency Injection"/><property name="age" value="35"/>
</bean>
By using a <constructor-arg> element in the Spring configuration file, we tell the Spring container to pass these arguments to the JavaInstructor constructor when it instantiates the instance
– The container figures out which constructor to call by looking at the number and type of the constructor arguments in the <bean> element
In the example in the slide, it will look for a constructor that receives a SpringBook (or a type that a SpringBook is assignable to, such as InfoSource) and a value argument
– It will find the JavaInstructor (InfoSource, String) constructor– It will try to invoke this constructor, passing in the springBook bean as the first argument, and
the string "Dependency Injection" as the second argument
The example code assumes that JavaInstructor also has an age property that we haven't shown in its class definition
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 7520130401
Fast Track to Spring 3.x and Spring Web
Constructor Argument Resolution
The container tries to resolve constructor elements in the configuration to constructor arguments in the bean definition– Can do this in multiple ways
For example, the configuration shown below will work– Uses the JavaInstructor constructor seen previously– Note how the springBook reference is last in the configuration,
but first in the constructor definition– Spring uses the constructor argument types first to determine
what each <constructor-arg> element is for– The order is not needed in this case
<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"><constructor-arg value="Dependency Injection"/><property name="age" value="35"/><constructor-arg ref="springBook"/>
</bean>
In the example, there is also a <property> element for the age property– This has no affect on the constructor argument resolution– <property> explicitly declares which property it is for, and doesn't interact with constructor
initialization– The properties are set after the bean is created, and its constructor is called
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 7620130401
Fast Track to Spring 3.x and Spring Web
Constructor Argument Resolution
Consider the example at bottom though– The 2nd and 3rd constructor arguments can't be resolved by type– They are just strings in the config file– Here, the container will use the order in the config file to initialize the
last two constructor argumentspublic class JavaInstructor implements Teacher {
private InfoSource info;private String favoriteTopic;private Double age;
public JavaInstructor(InfoSource infoIn, String topic, Double ageIn) {info = infoIn;favoriteTopic = topic;age = ageIn;
}// Much detail omitted …
}
<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"><constructor-arg ref="springBook"/><constructor-arg value="Dependency Injection"/><constructor-arg value="35"/>
</bean>
In the slide example, the default ordering works fine– We've supplied the arguments in the order that they appear in the constructor– The container will initialize them properly
In the example in the slide, it will look for a constructor that receives a SpringBook (or a type that a SpringBook is assignable to, such as InfoSource) and two value arguments
– It will find the JavaInstructor (InfoSource, String, Double) constructor– It will try to invoke this constructor, passing in the springBook bean as the first argument, the
string "Dependency Injection" as the second argument, and will try to convert the string "35" to a Double for the third argument
The example works, but what if you change the order of the arguments in the constructor, or want to guarantee that the arguments in the configuration file are passed to the correct constructor arguments
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 7720130401
Fast Track to Spring 3.x and Spring Web
Constructor Argument Resolution
Consider a new constructor definition: public JavaInstructor(InfoSource infoIn, Double ageIn, String topic)
– The age argument is now before the topic string– The previous configuration entries will throw an exception (the
container tries to convert "Dependency Injection" to a Double)
Specifying the type of the argument can help argument resolution, as shown below– The container must be able to unambiguously resolve the
arguments– You can also use indices *
<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"><constructor-arg ref="springBook"/><constructor-arg type="java.lang.String" value="Dependency Injection"/><constructor-arg type="java.lang.Double" value="35"/>
</bean>
Spring allows you to declare the argument index to help argument resolution– Indexing of arguments begins at 0<bean id="springGuru" class="com.javatunes.teach.JavaInstructor">
<constructor-arg ref="springBook"/>
<constructor-arg index="2" value="Dependency Injection"/>
<constructor-arg index="1" value="35"/>
</bean>
You can mix and match all these ways of resolving the arguments
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 7820130401
Fast Track to Spring 3.x and Spring Web
XML Shortcuts - p: and c: Namespaces
p: (p-namespace) allows using attributes to set property values– If our Teacher type had a "bestSubject" property, we could initialize it
using the p:bestSubject syntax shown below– -ref after the property name would indicate the value is a reference
c: (c-namespace) allows using attributes to set constructor args– If JavaInstructor had a constructor taking an InfoSource, we could
initialize it with the c:infoIn-ref syntax shown at bottom– Here we use the -ref suffix to show that the value is a reference
<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"p:bestSubject="Spring"/>
<bean id="springBook" class="com.javatunes.teach.SpringCourseBook"/>
<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"c:infoIn-ref="springBook"/>
You would need to include the namespaces in your <beans> element, e.g.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 7920130401
Fast Track to Spring 3.x and Spring Web
Setter Injection vs. Constructor Injection
Generally, setter injection is easier to use than constructor injection - however, they both have pros and cons
Setter Injection Pros– Much easier to use - Multiple property definitions easier than a
constructor with many arguments or multiple constructors– Can flexibly choose which properties to configure– Fairly easy to use with inheritance
Setter Injection Cons– Doesn't guarantee property initialization (if you leave out a
property configuration, it will simply remain unitialized)– Requires setter methods for any property you want to configure– Doesn't support immutable beans well, since you have to have
setters for the properties
It is possible to use both constructor and setter injection in the same bean– For example, you may use constructor injection on properties that you want to ensure are always
set on a bean– You would then define a constructor that took only those properties as arguments– You can use setter injection on the rest of the properties for flexibility and ease of use
Spring doesn't mandate what kind of injection you use– It gives you the capabilities, and lets you choose the appropriate solution for your particular
situation
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 8020130401
Fast Track to Spring 3.x and Spring Web
Setter Injection vs. Constructor Injection
Constructor Injection Pros– Guarantees properties are initialized – if constructor argument
is left out, you'll get an error when the bean is instantiated– Setter methods not needed for properties– Immutable beans easily supported (since setters not required)
Constructor Injection Cons– Constructors can be unwieldy – Complex and hard to use with
large numbers of properties– Constructors offer less flexibility – Separate constructors
needed for different initialization scenarios– More complex XML for constructor injection than setter injection
• Especially if type or index arguments are needed
Constructor Injection is less flexible than Setter Injection– However, it has the advantage of enforcing a stronger dependency contract– A bean MUST be instantiated using one of the available constructors– If a mistake is made, and you leave out a constructor argument an exception will be thrown
You can make an immutable bean by setting all the bean's properties via constructor injection, and not defining setter methods
– Once the bean is created, there will be no way for a programmer to change the value of the properties
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 9120130401
Fast Track to Spring 3.x and Spring Web
Collection Valued Properties
Working with PropertiesCollection Valued Properties
Additional Capabilities
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 9220130401
Fast Track to Spring 3.x and Spring Web
Working with Collections
Spring can configure properties containing a collection– Four types of collection configuration elements:– <list>: A list of values, allowing duplicates– <set>: A set of values, allowing NO duplicates– <map>: A set of name-value pairs, where name and value can
be of any type– <props>: A set of name-value pairs, where the name and value
are both Strings
<list> and <set> can be used for array valued properties or for implementations of java.util.Collection– The actual bean property does not have to be List or Set– The container enforces the list or set contract
The <list> or <set> configuration elements can be used with many different kind of collection valued properties of a bean
– For example, you can use a <set> configuration element to initialize an array valued property ofa bean
The Spring container will enforce the list or set semantics– For example, if you have duplicates in a <set> element, then the container will only include one
of the valuesIf you use a specific type of Collection for the property (for example a List or Set) then the Spring container will create the proper collection for you
– For example, an ArrayList for a List property, or a LinkedHashSet for a Set property
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 9320130401
Fast Track to Spring 3.x and Spring Web
Collection Property Example
Consider a collection valued property, as shown below– The favoriteTopics property is now defined as a collection– A teacher can now have multiple favorite topics that are
contained in this collection property– We'll see how to configure this next
public class JavaInstructor implements Teacher {// Much detail omitted …private Collection<String> favoriteTopics;public void setFavoriteTopics (Collection<String> topics) {
favoriteTopics = topics;}public Collection<String> getFavoriteTopics() { return favoriteTopics; }
}
public interface Teacher {// Much detail omitted …public Collection<String> getFavoriteTopics();
}
This example uses Java generic collections– This is the preferred and standard way to use collections– When using generic collections, Spring will do any required conversions from the configuration
value to the elements of the collection, just as with regular properties– It uses the type of the Collection to determine what to convert the configuration value to– Our example contains strings, so no conversion is necessary, but if it was another type, such as
Collection<java.lang.Double> then conversion would be usedSpring also supports the older style of Object based collections
– If using the older style collections, your types would be defined in terms of Collection rather than Collection<String>
– For example, the Teacher interface would be:public interface Teacher {
// Much detail omitted …
public Collection getFavoriteTopics();
}
– Similarly, the JavaInstructor class would be written in terms of Collection
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 9420130401
Fast Track to Spring 3.x and Spring Web
Configuring <list> and <set> Properties
We can initialize the favoriteTopics property using either of the examples shown below– The <list> element will result in a collection with 3 values– The <set> element will filter out the duplicate "Spring" value, and will
result in a collection with 2 values
<property name="favoriteTopics"> <!-- Most details omitted --><set><value>Spring</value><value>Java</value><value>Spring</value>
</set></property>
<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"><property name="favoriteTopics"><list><value>Spring</value><value>Java</value><value>Spring</value>
</list></property>
</bean>
If you were using old style collections, and you want conversion of values to occur, you can use the type attribute of the value element to indicate how to do the conversion
– For example, lets say you had a property that you wanted to contain java.lang.Double values, such as the one below
private Collection evaluationScores;
– You could initialize it as below<property name="evaluationScores">
<list>
<value type="java.lang.Double">4.5</value>
<value type="java.lang.Double">4.25</value>
</list>
</property>
– The Spring container will now convert the values to a java.lang.Double before inserting them in the collection
Note that the Spring container will also create a Collection that is compatible with the configuration element (e.g. a List implementation for <list> and a Set implementation for <set>)
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 9520130401
Fast Track to Spring 3.x and Spring Web
Configuring Collection of Bean References
Collection properties may also contain references to other beans (dependencies)– They are configured similarly to value based collections– For example, if JavaInstructor had the following Constructor:JavaInstructor(Set<InfoSource> infoSources)
– You could configure it using the configuration elements below
<bean id="springBook" class="com.javatunes.teach.SpringCourseBook"/><bean id="javaBook" class="com.javatunes.teach.JavaCourseBook"/>
<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"><constructor-arg>
<set><ref bean="springBook"/><ref bean="javaBook"/>
</set></constructor-arg>
</bean>
Collections may also be used with properties containing bean references– For example, if the JavaInstructor class had a set method for the infoSources property
(which is of type Set<InfoSource>) you could configure using a <property> element and a collection as follows:
<bean id="springGuru" class="com.javatunes.teach.JavaInstructor">
<property name="infoSources">
<set>
<ref bean="springBook"/>
<ref bean="javaBook"/>
</set>
</property>
</bean>
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 9620130401
Fast Track to Spring 3.x and Spring Web
Map Valued Properties
Map valued properties can also be configured with Spring– For example, if JavaInstructor had the following property:Map<String,InfoSource> infoSources;
– You could configure it using the configuration elements below<bean id="springBook" class="com.javatunes.teach.SpringCourseBook"/><bean id="javaBook" class="com.javatunes.teach.JavaCourseBook"/><bean id="totalGuru" class="com.javatunes.teach.JavaInstructor"><property name="infoSources"><map><entry><key><value>Spring Book</value></key><ref bean="springBook"/>
</entry><entry><key><value>Java Book</value></key><ref bean="javaBook"/>
</entry></map>
</property></bean>
Map valued properties allow you to create maps containing any type– In this example we use a string as the key, but it's possible to use any type as the key– The value is a reference to bean that implements the InfoSource interface – e.g. one of our
book implementations
Similarly to the other collection elements, <map> can also be used with constructor arguments
We don't show the setter/getter methods here, but assume that they exist for the infoSourcesproperty
– Using this property is easy; you just access it using getInfoSources(), then work with the Map object just like you would with any other property
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 9720130401
Fast Track to Spring 3.x and Spring Web
java.util.Properties Valued Properties
java.util.Properties valued properties can also used– A Properties object holds String names and values– For example, if JavaInstructor had the following property:Properties topicExpertise;
– Assume this property holds a topic as the key, and a descriptionof the Instructor's expertise as a value
– You could configure it using the configuration elements below
<bean id="totalGuru" class="com.javatunes.teach.JavaInstructor"><property name="topicExpertise"><props><prop key="Spring">Expert</prop><prop key="Java">Expert</prop><prop key="EJB3">Good</prop>
</props></property>
</bean>
Similarly to the other collection elements, <props> can also be used with constructor arguments
We don't show the setter/getter methods here, but assume that they exist for the topicExpertiseproperty
– Using this property is easy; you just access it using getTopicExpertise(), then work with the java.util.Properties object just like you would with any other property
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 9820130401
Fast Track to Spring 3.x and Spring Web
Lab 2.2 – Collection Valued Properties
Lab 2.2: Collection Valued Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 9920130401
Fast Track to Spring 3.x and Spring Web
Lab 2.2 – Configuring Collections
Overview: In this lab, we will initialize a collection valued property by injection– The lab is also based on JavaTunes code– It modifies the InMemoryItemDAO class so its in-memory storage
is initialized by injection, rather than hard coded
Objectives: – Use the Spring configuration file to inject a collection valued
property
Builds on previous labs: none
Approximate Time: 20-30 minutes
Lab
Lab 2.2: Collection Valued Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 10020130401
Fast Track to Spring 3.x and Spring Web
Lab Preparation
The new lab folder where you will do all your work is: C:\StudentWork\Spring\workspace\Lab02.2
Lab
Tasks to PerformClose all open files
Create a new Java project called Lab02.2 in the workspace *– See Lab 1.1 instructions on how to do this– Remember to add the Spring user library
To add the Spring library after creating the project you can do the followingRight Click on the project in Package Explorer, select Build Path | Configure Build Path
– Click the Libraries tab, click the Add Library button, and in the dialog , select User Librarythen click Next
– Check off Spring, then click Finish in all open dialogs (screenshot in notes)
Lab 2.2: Collection Valued Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 10120130401
Fast Track to Spring 3.x and Spring Web
Lab Preparation Lab
Tasks to PerformOpen InMemoryItemDAO.java for review– Note that it now has a constructor that receives a collection
representing its in-memory store– You'll need to supply this collection via constructor injection in the
Spring configuration file– There is nothing you need to code in this class
Open src/applicationContext.xml– Note the configuration of numerous MusicItem beans, with ids of mi1, mi2, and etc.
– Go to the inMemoryItemDAO bean definition, and add in a constructor argument containing a list of MusicItem references
– Use some of the MusicItem beans configured later in the file as the contents of the list (make sure to include the bean with id = mi2, since we search on it in the test program)
Lab 2.2: Collection Valued Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 10220130401
Fast Track to Spring 3.x and Spring Web
Configure the Beans
Tasks to PerformRun the program in JavaTunes.java as before *
If you've configured the constructor argument correctly, your program will run without any exceptions– You should see output from the calls to the search methods we've
included in the JavaTunes program
Congratulations – you've configured a complete app– You've used both constructor and setter injection
Lab
STOP
To run the program in Eclipse, right click on JavaTunes.java, and select Run As | Java ApplicationLook at the <list> elements in the slides, or from previous labs to help you remember what they look likeIt's a bit unwieldy to configure so many beans in one file
– However, it's useful to be able to configure the contents of the "datastore" without recompiling code - This is especially helpful with testing
– For example, you can configure it without any elements, and see if your code works properlyLater, we'll see how to use multiple configuration files
– This helps keep the configuration manageable
Note that we are setting date properties for music items in the config file in a rather cumbersome way – we have an additional setReleaseDateString method in MusicItem
– This is required because there is no built in conversion from a string to a date when setting a property with the standard Spring config file
– You can also configure a custom property editor for this, which we'll look at later
Lab 2.2: Collection Valued Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 10320130401
Fast Track to Spring 3.x and Spring Web
Additional Capabilities
Working with PropertiesCollection Valued Properties
Additional Capabilities
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 10420130401
Fast Track to Spring 3.x and Spring Web
- Factory Methods -
Spring supports the creation of beans via factory methods– First, we consider static factory methods
The getInstance() method, shown below, is used to create JavaInstructor instances– Rather than using new JavaInstructor()
The <factorymethod> attribute of <bean> tells Spring to use a factory method, as shown at bottom
public class JavaInstructor implements Teacher { // Details omittedpublic static JavaInstructor getInstance() { /* ... */ }
}
<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"factory-method="getInstance">
<!-- Most detail omitted --></bean>
There are many reasons why factory methods may be used - e.g. creating a singleton bean– Frameworks often use them, and Spring can integrate with these frameworks via the factory
method capabilities we show hereNote: The getInstance() details aren't shown because they are not relevant to our topicThere is much less need for factory methods if you design your classes with Spring in mind
– Spring has support for many of the capabilities that you would get from using factory methods – such as singletons and ease of configuration
When using factory methods, the class attribute specifies the name of the class that contains the factory method, and not the name of the class that is being produced by the factory methodYou can also pass arguments to the factory method using <constructor-arg> elements
– With getInstance defined as below, the configuration at bottom supplies the argumentpublic static JavaInstructor getInstance(InfoSource infoIn)
<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"
factory-method="getInstance">
<constructor-arg ref="springBook"/>
</bean>
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 10520130401
Fast Track to Spring 3.x and Spring Web
Instance Factory Methods
Spring also supports instance factory methods– Often encountered when using factory classes
JavaInstructorFactory, shown below, has an instance method to produce JavaInstructors
<bean> uses a factory-bean attribute rather than class– The factory method is invoked on the specified factory bean
instance
public class JavaInstructorFactory { // Details omittedpublic JavaInstructor getInstance() { /* ... */ }
}
<bean id="myFactory" class=com.javatunes.teach.JavaInstructorFactory"/>
<bean id="springGuru"factory-bean="myFactory" factory-method="getInstance">
</bean>
Typically a factory class will also have some configurable properties that control details of the instances that are produced
– We don't show any of those details here, as they are not relevant to the topic– However, if there were such properties on JavaInstructorFactory, you could use the Spring
configuration to set themTo use instance factory methods, the class attribute must be left empty
– The factory-bean attribute must specify the name of a bean in the current container that contains the factory method
– The factory method on this bean must still be set via the factory-method attribute
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 10620130401
Fast Track to Spring 3.x and Spring Web
- Bean Aliases -
A bean must have at lease one id, but may have more– Ids can be specified with the id or name attributes
id attribute: Lets you specify exactly one id, must follow rules for XML ids - e.g. it can't start with a number
name attribute: Can hold multiple values, doesn't have to follow rules for XML ids– Multiple values can be separated by a comma (,) semicolon (;) or
white space– Below, we give a bean 2 names that are not valid XML ids
<bean name="1-springBook, 2-javaBook"class="com.javatunes.teach.SpringCourseBook"/>
<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"><property name="info" ref="1-springBook"/>
</bean>
All values declared with the id or name attributes become aliases for the bean
Using the name attribute:– Allows you to define names that don't conform to XML id names - for example you might use a
naming convention that starts bean names with a number– Allows you to have multiple aliases for a bean
If you don't supply any ids, then the container will generate a unique id for the bean based on the class name
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 10720130401
Fast Track to Spring 3.x and Spring Web
- Bean Definition Inheritance -
A bean definition (the child) can inherit configuration data from another bean (the parent)– Useful when configuration data is common to multiple beans– Possible to override some values, or add values
The parent attribute is used to specify that a bean inherits configuration data from another bean– Inherits the bean class, constructor-args, and all the properties – Can override all of these – Certain settings always taken from the child *
An abstract="true" attribute is available for parent beans– The container won't instantiate abstract beans– Useful if you're defining the bean ONLY to share configuration
Inheritance is useful when you're sharing large amounts of configuration data among multiple beans
The settings that are always taken from the child are:– depends on, autowire mode, dependency check, singleton, scope, lazy init– We haven't covered many of these yet, and will cover some of them later
Defining a bean as abstract ensures that somebody doesn't accidentally instantiate it– This may be undesirable in the case of bean definitions that are only partly configured, where the
remaining configuration is done in the child– In this case, the abstract bean isn't intended to be used directly
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 10820130401
Fast Track to Spring 3.x and Spring Web
Inheritance Example
The example below shows both inheritance and overriding<bean id="seniorJavaInstructor" class="com.javatunes.teach.JavaInstructor"><property name="infoSources">
<set><ref bean="springBook"/><ref bean="javaBook"/>
</set></property><property name="favoriteTopics"><list><value>Spring</value><value>Java</value><value>Hibernate</value>
</list></property>
</bean><!– Inherit definitions from parent -->
<bean id="springGuru" parent="seniorJavaInstructor"><property name="favoriteTopics"> <!-- Override this property --><set><value>Spring</value>
</set></property><property name="age" value="35"/>
</bean>
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 10920130401
Fast Track to Spring 3.x and Spring Web
- SpEL: Spring Expression Language -
Spring Expression Language (SpEL) introduced in Spring 3– Allows wiring values into beans, including:
• Values from other bean properties• Method return values, including static methods of a non-bean class• System properties
A SpEL expression has the form #{expression string}– For example, if our springGuru (Teacher) bean had a "bestSubject"
property, we could access it as follows:#{springGuru.bestSubject}
• springGuru is a bean id and bestSubject is a property of the bean– When used in a config file, it would look like the example below– When used with annotations, it would like the example at bottom
<property name="subject" value="#{springGuru.bestSubject}" />
@Value( "#{springGuru.bestSubject}" )private String bestSubject;
The expression language supports the following capabilities [Spring 3.0 Ref Sec. 3.2] – Literal expressions, Regular expressions, Class expressions– Boolean and relational operators– Accessing properties, arrays, lists, maps– Method invocation– Assignment– Calling constructors– Ternary operator– Variables– User defined functions– Collection projection and Collection selection– Templated expressions
The @Value annotation can be placed on fields, methods and method/constructor parameters to specify a default value
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 11020130401
Fast Track to Spring 3.x and Spring Web
Other SpEL Capabilities
Invoke methods on a bean– For example, to invoke pickASubject() on springGuru
#{springGuru.pickASubject()}
Access system properties through the predefined systemProperties variable– For example, to get the todaysSubject system property
#{systemProperties.todaysSubject}
Access static members of a class using the T (type) operator– For example, you can call java.lang.Math.random() as follows
#{ T(java.lang.Math).random() }
Can also be used to evaluate expressions in Java programs through the use of ExpressionParser and other classesSee the reference manual for the wide range of SpEL's capabilities
In the slide, we're assuming that the springGuru bean has a pickASubject() method that returns a subject
– The details of the method are unimportant for this exampleThe systemProperties variable is a java.util.Properties reference that contains any system properties available to the application
– It's effectively the same as calling System.getProperties()
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 11120130401
Fast Track to Spring 3.x and Spring Web
- Autowiring -
Spring can automatically resolve bean dependencies– Called autowiring, and can be done four different ways
byName : Attempts to find a bean named exactly the same as the property which needs to be autowired
byType : Attempts to find a single bean whose type matches the type of the property being wired– If there is more than one match, a fatal exception is thrown. – If there are no matching beans the property is not set.
constructor : Analogous to byType, but applies to constructor args
autodetect : Attempts to wire constructor and then byTypethrough introspection of the bean class– If a default constructor is found, byType mode will be applied
byName: For example, if you have a bean definition which is set to autowire by name, and it contains a favoriteTopic property, Spring will look for a bean definition named favoriteTopic, and use it to set the propertybyType: If you want byType to fail if there are no matching beans of the needed type, you can set the dependency-check="objects" attribute value
– This specifies that an error should be thrown in this situation
Explicit dependencies in property and constructor-arg settings always override autowiringIt is not possible to autowire simple properties
– This is by design, as it is only meant to wire beans
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 11220130401
Fast Track to Spring 3.x and Spring Web
Autowiring byName Example
Autowiring specified via autowire attribute of <bean>– The default is autowire="no" which specifies no autowiring– You specify one of the other four possibilities to trigger autowiring
Below, the JavaInstructor info property is autowired to the bean named info (a SpringCourseBook)– This uses byName autowiring
public class JavaInstructor implements Teacher { // Detail omittedprivate InfoSource info;public void setInfo (InfoSource infoIn) {
info=infoIn;}
}
public class SpringCourseBook implements InfoSource { /* … */ }
<bean id="info" class="com.javatunes.teach.SpringCourseBook"/>
<bean autowire="byName" id="springGuru" class="com.javatunes.teach.JavaInstructor"/>
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 11320130401
Fast Track to Spring 3.x and Spring Web
Autowiring byType
The first example below shows a successful use of byType– There is one bean of type InfoSource, and so it is wired to the JavaInstructor info property
The second example below will fail – There are two beans of type InfoSource– Assumes that JavaCourseBook also implements InfoSource
<bean id="springBook" class="com.javatunes.teach.SpringCourseBook"/>
<bean autowire="byType" id="springGuru" class="com.javatunes.teach.JavaInstructor"/>
<bean id="springBook" class="com.javatunes.teach.SpringCourseBook"/><bean id="javaBook" class="com.javatunes.teach.JavaCourseBook"/>
<bean autowire="byType" id="springGuru" class="com.javatunes.teach.JavaInstructor"/>
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 11420130401
Fast Track to Spring 3.x and Spring Web
Pros and Cons of Autowiring
Autowiring: Saves you the trouble of wiring beans with XML– Can make your configuration files simpler– Can help your configuration files evolve "automatically"– Very useful in the common case where there is only one instance
of a particular bean type
Some disadvantages to autowiring– Less clear than explicit wiring – You don't see the exact configuration, since it's done by the
container - creating a place for errors to enter– byName and byType place requirements and restrictions on
the names or types of beans you can have in a configuration– Can lead to unforeseen results when you make modifications
• e.g. if you change the name of a property wired byName, behind the scenes it may get wired to something you didn't expect
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 11520130401
Fast Track to Spring 3.x and Spring Web
To Autowire or Not to Autowire
Autowiring lacks clarity, and may change in unexpected ways as you maintain and evolve your program– Tools also do not support autowiring very well
Because of this, autowiring should be used carefully– Very useful in situations where it's not likely to give an error
• e.g. - where there is only one bean instance of a given type– Perhaps avoid it with complex systems where the autowiring may
inadvertently change, or where the complexity is confusing
It is available in the Spring framework, and should be evaluated carefully– To make sure it is not likely to introduce subtle bugs
Session 2: More About Bean Properties
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 40920130315
Fast Track to Spring 3.x and Spring Web
Spring Web Flow Overview
Spring Web Flow OverviewDefining Flows
Basic System ConfigurationWorking with Data and Actions
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 41020130315
Fast Track to Spring 3.x and Spring Web
The Need for Spring Web Flow
Spring Web Flow (SWF) addresses the need for defining user interface (UI) flow in a Web application– A flow can involve multiple user interactions and system actions– It may involve multiple views (Web pages) and multiple
components to handle actions
Typical frameworks only provide part of this functionality– Typically provide for navigation and controller components in a
single step• e.g. JSF navigation rules and managed beans
– Don't provide a way to define larger flows• Usually scattered over multiple rules and controllers• A major shortcoming of these frameworks
A UI flow is somewhat equivalent to a Use Case in terms of modeling
– It represents a series of actions by the user and system, to achieve a particular result
Different frameworks implement their navigation/controller functionality differently
– For example, struts used Action components and a configuration file to configure navigation
– In general, they did not have a general purpose mechanism for defining overall UI flow
Spring MVC does include a form controller, which controls UI flow for a form submission
– This is still not a general purpose mechanism
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 41120130315
Fast Track to Spring 3.x and Spring Web
What is Spring Web Flow?
Spring Web Flow lets you define a complete Web UI flow – Typically done using XML configuration to explicitly and clearly
define flows– Plugs into Spring MVC and other frameworks such as JSF
Flow: A sequences of steps usable in different situations– A blueprint for carrying out a conversation with a single user– For example, a login flow or a checkout flow
Flows support user and application-directed control– e.g. in a checkout flow for e-commerce, you might have:
• Decisions (e.g. confirm/cancel order)• Loops (remove/modify item in cart)• Subflows (e.g. login to your account)
Flows go well beyond the simple progression through a multipart form– Spring MVC has support for that in it's Form Controller– Spring Web Flow has much more capability than this
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 41220130315
Fast Track to Spring 3.x and Spring Web
Benefits of Spring Web Flow
UI flows are clearly defined and clearly visible– Typically defined in a single location (an XML file)
• Relatively easy to understand and maintain• As opposed to being scattered over multiple files and controllers
Easier to implement and get correct– A single consistent and clear mechanism– As opposed to multiple, hard to maintain, ad-hoc mechanisms
Promotes reuse– The flow logic is self-contained, making it easier to reuse
There also costs when using Spring Web Flow– Considerable complexity to learn and use– Dependent on a non-standard (though popular) framework
Generally, creating and maintaining the UI flow in a Web application is one of the more complicated pieces of creating it
– Often, ad hoc methods are used which present numerous challenges in creating, understanding, and maintaining the flow
– This is true even when applications leverage technologies like Spring MVC or JSF
– Spring Web Flow is designed to address these issues
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 41320130315
Fast Track to Spring 3.x and Spring Web
The Spring Web Flow Project
Home Page: http://projects.spring.io/spring-webflow/
Downloading: http://mvnrepository.com/artifact/org.springframework.webflow
Documentation:http://docs.spring.io/spring-webflow/docs
There is an additional jar file available for download– spring-webflow-2.n.n.RELEASE-with-dependencies.zip– This contains additional material in the project folder
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 41420130315
Fast Track to Spring 3.x and Spring Web
Overview of a Flow in SWF
A flow encapsulates a sequence of steps within a Web app
– For example, a search flow for searching in our JavaTunes app– This has two parts from a UI point of view
• Submitting search criteria, and viewing search results– The Web app below lets you submit search criteria, view the
results, and search on new criteria from the results page
enterSearchCriteria viewSearchResults
submitSearch
submitSearch(new search)
Flows fulfill much of the same requirements as generalized workflows in Business Process Management
– However, they are specialized for defining UI flows in a Web application
– You could theoretically use more general purpose mechanisms to achieve the same results as SWF flows
– Using these specialized flows makes your UI definition much clearer and simpler to create
We have chosen to diagram our flow in an informal way in the slide– There is no standard way to diagram flows– UML state diagrams and Garrett diagrams are some ways that
people use to diagram their flows
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 41520130315
Fast Track to Spring 3.x and Spring Web
Elements of a Flow
State: A point in the flow representing a condition or situation– Typically where some activity takes place (e.g. showing a view or taking
an action)
View: A single page that visualizes (displays) information
Event: An occurrence of some sort that's handled by a state– Causes an action to occur, and/or a change to another state
Transition: A change in state – Usually results in a view navigation
Action: Execution of some business functionality– May be executed at numerous points in a flow (we'll look at this later)
In the previous diagram, in the enterSearchCriteria state, the submitSearch action triggered a transition to the state viewSearchResults (and executed an action to do the search)– In each state, an associated view was displayed to the user
In the diagram in the previous slide, we did not show any actions– It's possible to include actions in your diagram, but it is also
common to leave them out, and just show the flow navigation– In our simple diagram, we chose to leave it out
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 41620130315
Fast Track to Spring 3.x and Spring Web
Defining a Flow
Flows are defined using an XML flow definition language– An example definition for our search flow is below– It defines states (e.g. enterSearchCriteria), views, and event-based
transitions (on event submitSearch go to state viewSearchResults)– We'll go into much more detail on this shortly
<?xml version="1.0" encoding="UTF-8"?><flow xmlns="http://www.springframework.org/schema/webflow"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/webflowhttp://www.springframework.org/schema/webflow/spring-webflow.xsd">
<view-state id="enterSearchCriteria" view="search"><transition on="submitSearch" to="viewSearchResults"/>
</view-state> <!-- By default, the first state is the start state. -->
<view-state id="viewSearchResults" view="searchResults"><transition on="submitSearch" to="viewSearchResults"/><transition on="endSearch" to="goHome"/>
</view-state>
<end-state id="goHome" view="externalRedirect:contextRelative:/"/></flow>
You can also define a flow using a Spring Web Flow API for Java– This allows programmatic definition of a flow– This is not the typical method used when doing application
development with Spring Web Flow, and we do not cover it in this course
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 41720130315
Fast Track to Spring 3.x and Spring Web
Defining Flows
Spring Web Flow OverviewDefining Flows
Basic System ConfigurationWorking with Data and Actions
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 41820130315
Fast Track to Spring 3.x and Spring Web
Elements of a Flow Definition
Our earlier flow definition file (excerpted below) contains a number of core elements for defining flows<flow>: Root element defining exactly one flow definition– start-state attribute: Start point of flow (default is first state defined)<view-state>: A state that displays a view when entered– States define the steps of a flow– id: The id (name) of the state, view: The view to display<end-state>: Terminates a flow, and defines its outcome<transition>: Handles events occurring within a state– on: The event triggering the transition, to: The state transitioned to
<?xml version="1.0" encoding="UTF-8"?><flow xmlns="http://www.springframework.org/schema/webflow" … detail omitted …
start-state="enterSearchCriteria">
<view-state id="enterSearchCriteria" view="search"><transition on="submitSearch" to="viewSearchResults"/>
</view-state> <!-- Remaining Detail omitted </flow>
The XML namespace elements for the flow definition need to be included at the beginning of every XML flow definition file
– We've left out some of the detail in the document above– Typically, you'll have an example or template that you can copy from that already includes all
the namespace informationFrom the XML schema document for flows:
The root "flow" element in this document defines exactly one flow definition. A flow definition is a blueprint for a carrying out a conversation with a single user.
A flow is composed of one or more states that form the steps of the flow. Each state executes a behavior when entered. What behavior is executed is a function of the state's type. Core state types include view states, action states, subflow states, decision states, and end states.
A flow definition has exactly one start state. Events that occur within states drive state transitions.In the flow definition in the slide, we explicitly declared enterSearchCriteria the start state
– In the earlier example we used the fact that the first state is the default start state– Either is acceptable
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 41920130315
Fast Track to Spring 3.x and Spring Web
How a Flow Works – Start State
Enter a flow by browsing to a URL that includes the flow name– e.g. http://localhost:8080/javatunes/search.do– The flow name and associated URL, are derived from the flow
configuration (covered more later)Upon entering a flow, you go to its start state– enterSearchCriteria in our example
• Configured to display the view named search (via view="search")– The search view is mapped to a JSP page
• e.g. via a Spring MVC view resolver mapping to search.jsp
<?xml version="1.0" encoding="UTF-8"?><flow xmlns="http://www.springframework.org/schema/webflow" … detail omitted …
start-state="enterSearchCriteria">
<view-state id="enterSearchCriteria" view="search"><transition on="submitSearch" to="viewSearchResults"/>
</view-state> <!-- Remaining Detail omitted -->
</flow>
The URL http://localhost:8080/javatunes/search.do is derived from a flow name of search, and from configuration settings that map *.doto the Webflow engine
– We'll see how that is done later
The enterSearchCriteria state is a view-state– A view-state has an associated view that is displayed when
the view is entered– The view that is shown can be configured by using the view
attribute to specify the view– The value of this attribute is mapped to a display page– How that mapping is done is based on configuration elements
we'll look at later
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 42020130315
Fast Track to Spring 3.x and Spring Web
How a Flow Works - Transition
Upon receiving the submitSearch event, the flow transitions to the viewSearchResults state– The event is triggered by a user action
• e.g. clicking the submit button on a search form– The viewSearchResults state displays the searchResults
view (e.g. searchResults.jsp)
<?xml version="1.0" encoding="UTF-8"?><flow xmlns="http://www.springframework.org/schema/webflow" … detail omitted …
start-state="enterSearchCriteria">
<view-state id="enterSearchCriteria" view="search"><transition on="submitSearch" to="viewSearchResults"/>
</view-state>
<view-state id="viewSearchResults" view="searchResults"><transition on="submitSearch" to="viewSearchResults"/><transition on="endSearch" to="goHome"/>
</view-state> <!-- Remaining Detail omitted -->
</flow>
Spring Web Flow uses a flow handler to control the flow of the Web application
– We'll look more at flow handlers later
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 42120130315
Fast Track to Spring 3.x and Spring Web
How a Flow Works – End State
The viewSearchResults state has two transitions– submitSearch: Goes back to the viewSearchResults state– endSearch: Goes to the goHome state
The goHome state displays the root of the web app, and ends the flow (because it is an end-state)– goHome's view is a special value
• It instructs the flow handler to redirect to the given URL
<?xml version="1.0" encoding="UTF-8"?><flow xmlns="http://www.springframework.org/schema/webflow" … detail omitted …
start-state="enterSearchCriteria"> <!-- Some detail omitted -->
<view-state id="viewSearchResults" view="searchResults"><transition on="submitSearch" to="viewSearchResults"/><transition on="endSearch" to="goHome"/>
</view-state>
<end-state id="goHome" view="externalRedirect:contextRelative:/"/>
</flow>
The view for the goHome state uses two special prefixes as part of the view value– externalRedirect: This prefix instructors the flow handler to
redirect to an external location (that is, one that is not part of the web flow)
– contextRelative: This prefix instructs the flow handler to redirect to a resource relative to the current web application context path
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 42220130315
Fast Track to Spring 3.x and Spring Web
How a Flow Works – Web Pages
Below, are key parts of our flow's web pagesindex.jsp: Home page containing a link to enter the flow– The search.do link is mapped to a flow
• So the request is handled by the flow engine• The start state is entered, and the view page (search.jsp) is rendered
search.jsp: View page for the enterSearchCriteria state– Has a single link, which triggers the submitSearch event– ${flowExecutionUrl} is an implicit variable that is put in scope by
the flow engine, and maps to the current flow (the search flow)– The value of the eventId parameter identifies the event
<!-- index.jsp: Link to search.do, which enters the search flow --><BODY> <a href="search.do">Search</a>
</BODY>
<!-- search.jsp: Link which generates submitSearch event in the flow --><BODY> <a href="${flowExecutionUrl}&_eventId=submitSearch">Submit Search</a>
</BODY>
flowExecutionURL is an implicit variable that may be referenced from within a flow
– It holds the context-relative URI for the current flow execution view-state
– Basically it is a URI which tells the flow engine what flow and what state in a flow the current request is coming from
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 42320130315
Fast Track to Spring 3.x and Spring Web
How a Flow Works – Web Pages
searchResults.sjp: View page for the viewSearchResult state– Has two links - one triggers the submitSearch event, which ends up
redisplaying this same view– The other link triggers the endSearch event, which results in the home
page being displayed again• Remember - The goHome end-state redirects the view to the home page
We've left out a lot of functionality in this example– Display markup in the HTML, or behavior that might execute upon an
event– We demonstrated enough to see how states, events and transitions
work to produce navigation through a flow
<!-- searchResults.jsp: Links which generate submitSearch, endSearch events --><BODY> <a href="${flowExecutionUrl}&_eventId=submitSearch">Submit Search</a><br/><a href="${flowExecutionUrl}&_eventId=endSearch">End Search</a>
</BODY>
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 42420130315
Fast Track to Spring 3.x and Spring Web
How a Flow Works – Web Pages
index.jsp
Link goes to search.do
search.jspLink submits eventsubmitSearch
searchResults.jspLinks submit eventssubmitSearchendSearch
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 42520130315
Fast Track to Spring 3.x and Spring Web
Leaving a Flow
You can leave a flow from the flow definition– Typically done via an end state - which terminates the flow
You can also redirect to another flow or to a URLflowRedirect redirects to another flow, as shown at bottom– The goToFlow2 end state redirects to the flow named flow2– You can include parameters, for example passing on a request paramflow2?_p1=${requestParameters._p1}
externalRedirect redirects to a URL, as shown at bottom– It supports a number of qualifiers, including
• servletRelative: redirect relative to current servlet• contextRelative: redirect relative to current Web app context • serverRelative: redirect relative to server root• http//: or https//: Redirect to fully qualified URL
<end-state id="gotoFlow2" view="flowRedirect:flow2"/><end-state id="goHome" view="externalRedirect:contextRelative:/"/>
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 43320130315
Fast Track to Spring 3.x and Spring Web
Basic System Configuration
Spring Web Flow OverviewDefining Flows
Basic System ConfigurationWorking with Data and Actions
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 43420130315
Fast Track to Spring 3.x and Spring Web
Configuring Spring Web Flow
We will look first at generic Web Flow configuration– Then look at the elements needed to work with Spring MVC
Two important components for handling flow are:– Flow executor: Handles all flow execution requirements (e.g.
executing a transition upon receiving an event in a flow)– Flow registry: Loads flow definitions from XML files, and makes
them available for execution by an associated flow executor– These components are configured in the spring configuration file
using a web flow configuration schema– A segment of this configuration is shown below
<!-- Much detail omitted --><flow:flow-executor id="flowExecutor" flow-registry="flowRegistry"/>
<!-- This creates an XmlFlowRegistryFactory bean --><flow:flow-registry id="flowRegistry" base-path="/WEB-INF/flows">
<flow:flow-location path="/search/search.xml"/></flow:flow-registry>
The elements in the configuration segment above are from the web flow schema– The root element of the configuration file that the segment appeared in would contain namespace
declarations that declared the web flow namespace correctly:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:flow="http://www.springframework.org/schema/webflow-config"
xsi:schemaLocation="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.xsd
http://www.springframework.org/schema/webflow-config
http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd">
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 43520130315
Fast Track to Spring 3.x and Spring Web
Configuring a Flow Registry
A flow registry is defined via <flow-registry>
Flow definitions are defined via <flow-location>– In the config below, we declare a base-path of /WEB-INF/flows– So all the flow definitions are under this path
A flow registry assigns a flow id identifying each flow definition– The location & base-path help determine flow id– Flow id: The path segment between the base path and file name– The flow definitions at bottom result in:
• A flow definition with an id of search (derived from /search)• A flow definition with an id of cart (derived from /cart)
– Best practice: Put each flow in its own directory– See notes for an alternative organization
<flow:flow-registry id="flowRegistry" base-path="/WEB-INF/flows"><flow:flow-location path="/search/search.xml"/><flow:flow-location path="/cart/shoppingCart.xml"/>
</flow:flow-registry>
In the examples on this page, the flow definition files are assumed to be under the directory /WEB-INF/flowsIt is also possible to define a flow registry without a base-path, as shown below
– In that case, the id that is generated is equal to the flow def filenames minus the file extension– In the example below, this gives ids of search, and shoppingCart respectively<flow:flow-registry id="flowRegistry">
<flow:flow-location path="/WEB-INF/flows/search.xml"/>
<flow:flow-location path="/WEB-INF/flows/shoppingCart.xml"/>
</flow:flow-registry>
– This is definitely legal, but it is generally recommended to use separate directories for each flow– You can also explicitly assign an id, as below where the flow is given an id of cart<flow:flow-location path="/WEB-INF/flows/shoppingCart.xml"
id="cart"/>
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 43620130315
Fast Track to Spring 3.x and Spring Web
Integrating with Spring MVC
Integrate Web Flow with Spring MVC using MVC's DispatcherServlet– Done by defining special Spring Web Flow beans in your context:
– FlowHandlerMapping: A Spring MVC HandlerMapping• Maps request URLs to flows based on flow id
– FlowHandlerAdapter: A Spring MVC HandlerAdapter• Handles the flow requests, & dispatches them to the flow engine
– There are other ways of integrating with Spring MVC, but this is a common (and simple) way
<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping"><property name="flowRegistry" ref="flowRegistry"/><property name="order" value="0"/>
</bean>
<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter"><property name="flowExecutor" ref="flowExecutor" />
</bean>
A Spring MVC handler mapping defines how the DispatcherServlet will map a URL to a controller (handler)
– Configuring a FlowHandlerMapping bean allows the Dispatcher to map application resource paths to flows in a flow registry
– The FlowHandlerMapping reads the flow registry for information on what flows are defined, and those are used to map incoming requests to flows
– For example, accessing the resource path /search.do would resultin a registry query for the flow with id search
The FlowHandlerMapping checks with a flow registry to see if an incoming URL is one that the flow engine is configured to handle
– If it is to be handled by the flow engine, request is passed to the FlowHandlerAdapter to handle, which then delegates to a flow executor
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 43720130315
Fast Track to Spring 3.x and Spring Web
Customizing the Flow Registry
<flow-registry> allows customization of how flows are built– Via the flow-builder-services attribute and a <flow-builder-services> element
– Below we define a customization of how views are handled– We tie into a standard Spring MVC view resolver for this
<bean id="jspViewResolver" <!-- Detail omitted --> </bean>
<flow:flow-registry id="flowRegistry" base-path="/WEB-INF/flows" flow-builder-services="flowBuilderServices">
<!-- Most detail omitted --> </flow:flow-registry>
<flow:flow-builder-services id="flowBuilderServices" view-factory-creator="viewFactoryCreator"/>
<bean id="viewFactoryCreator" class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">
<property name="viewResolvers"><list><ref bean="jspViewResolver"/></list>
</property></bean>
You can use the flow-builder-services attribute to customize the services and settings used to build flows in a flow-registry
– If no flow-builder-services tag is specified, the default service implementations are used
– When the tag is defined, you only need to reference the servicesyou want to customize
<flow-builder-services> can configure the following services– conversion-service: Customizes the conversion service
used by web flow to convert from one type to another when required during flow execution
– expression-parser: Customizes the expression parser used by Web Flow. The default uses the SpEL
– view-factory-creator: Customizes the view factory creator used by web flow to create view factories
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 43820130315
Fast Track to Spring 3.x and Spring Web
Complete Context Configuration (1/3)
Below we show the beginning of the configuration– It's a straightforward Spring MVC configuration– It defines a view resolver, and allows for using annotations
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" … Other Namespaces omitted … >
<!-- Spring MVC configuration --><bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"/><property name="prefix" value="/jsp/"/><property name="suffix" value=".jsp"/>
</bean>
<context:component-scan base-package="com.javatunes"/><context:annotation-config/> <!-- Continued -->
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 43920130315
Fast Track to Spring 3.x and Spring Web
Complete Context Configuration (2/3)
The beans below integrate web flow with the MVC DispatcherServlet– The flow executor and flow registry are also declared
<!-- Continued from previous slide--><bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping"><property name="flowRegistry" ref="flowRegistry"/><property name="order" value="0"/>
</bean>
<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter"><property name="flowExecutor" ref="flowExecutor" />
</bean>
<flow:flow-executor id="flowExecutor" flow-registry="flowRegistry"/>
<flow:flow-registry id="flowRegistry" base-path="/WEB-INF/flows" flow-builder-services="flowBuilderServices">
<flow:flow-location path="/search/search.xml"/></flow:flow-registry> <!-- Continued -->
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 44020130315
Fast Track to Spring 3.x and Spring Web
Complete Context Configuration (3/3)
<flow-builder-services> specifies a view-factory-creator– It uses the jspViewResolver defined earlier in the configuration
That covers the basic web flow configuration when used with Spring MVC– We'll cover more details as we need them
<!-- Continued from previous slide--><flow:flow-builder-services id="flowBuilderServices"
view-factory-creator="viewFactoryCreator"/>
<bean id="viewFactoryCreator"class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator"><property name="viewResolvers">
<list><ref bean="jspViewResolver"/></list></property></bean>
</beans> <!-- End of configuration -->
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 44120130315
Fast Track to Spring 3.x and Spring Web
Overall Request Flow
Spring MVC: dispatches client requests to handlers
Spring MVC handler mapping provided by Web flow – works with flow registry to determine flow requests then maps them to FlowHandlerAdapterSpring MVC controller provided by Web flow –delegates requests to the flow executorExecutes the flow – handling transitions, actions, etc – uses the flow registry to get flow definitionsLoads flow definitions, builds internal representation using FlowBuilderServicesContainer for services needed during flow building
Creates view factories
Maps logical view names to physical resources (e.g. a JSP)
DispatcherServlet
FlowHandlerMapping
FlowHandlerAdapter
FlowExecutor
FlowRegistry
FlowBuilderServices
ViewFactoryCreator
ViewResolver
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 44720130315
Fast Track to Spring 3.x and Spring Web
Working with Data and Actions
Spring Web Flow OverviewDefining Flows
Basic System ConfigurationWorking with Data and Actions
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 44820130315
Fast Track to Spring 3.x and Spring Web
Data Available to a Flow
Two important types of data available to a flow– We'll look at other areas where data is stored later
Flow instance variables: Created when the flow starts– Accessible in the entire flow (and often modified)– Declared using <var> in the flow definition– Often used as model objects, and bound to forms in a JSP
Inputs: Used to pass information into a flow when it is called– Accessible in the entire flow – Declared using <input> in the flow definition– Initialized when flow is called
Neither is required in a flow– They're available when your flow logic needs them
Input can be declared as required– If a call to a flow doesn't include it, then you'll get an exception– The Web Flow engine can also do type conversions on incoming data - which may be in string form
There are a number of other areas where data can be stored– Principally, there are a number of different scopes, that have different lifetimes and accessibilities– We'll look at these shortly
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 44920130315
Fast Track to Spring 3.x and Spring Web
Flow Instance Variables
At bottom, we declare a flow instance variable
– Named searchInfo, of class com.javatunes.web.SearchInfo– This is a JavaBean with two properties (see notes)
• String keyword and Collection<MusicItem> results
– Classes used this way must be serializable and have a no argument constructor• In general, SWF data must be serializable • SWF saves data using serialization during flow execution
These variables are accessible throughout the flow– In the flow definition file and view pages generating flow views
<flow …><var name="searchInfo" class="com.javatunes.web.SearchInfo" />
</flow>
The SearchInfo class definition is below– Note that MusicItem is a simple JavaBean with properties to describe a music item
public class SearchInfo implements Serializable {
private static final long serialVersionUID = 1L;
private String keyword;
public String getKeyword() {return keyword;}
public void setKeyword(String keyword) { this.keyword = keyword; }
private Collection<MusicItem> results;
public Collection<MusicItem> getResults() {return results;}
public void setResults(Collection<MusicItem> results) { this.results = results; }
}
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 45020130315
Fast Track to Spring 3.x and Spring Web
Binding Model Objects to Views
A model object can be bound to a view (see below)– The enterSearchCriteria view-state binds the searchInfo
model to its view (via model="searchInfo")– Usually used with views rendering data controls like forms
Binding the model results in the following behavior– View-to-model binding: On view postback, input values are
bound to model properties– Model validation: After binding, model validation will be invoked
(covered later)– If binding or validation fails, the view is re-rendered
<flow …><var name="searchInfo" class="com.javatunes.web.SearchInfo" />
<view-state id="enterSearchCriteria" view="search" model="searchInfo">…. </view-state>
</flow>
Flow instance variables are created at the start of the flow– They are usually serialized in between requests to the flow, which is why the data must be
serializable– It is also important to know that if you use a complex object which has member variables which
are annotated with @Autowired, these variables are rewired each time the flow resumesModel bindings also allow for type conversions
– The binding system will attempt to convert the input value to the type of the target model property if necessary. Default Converters are registered for common types such as Numbers, primitives, enums, and Dates and are applied automatically. Users also have the ability to register their own converters for user-defined types, and to override the default Converters.[Spring Web Flow Reference Guide]
– You can also create your own converters by writing a class that implements the interface org.springframework.binding.convert.converters.TwoWayConverter and registering it
– See the Spring Web Flow reference manual for more info on how to do this
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 45120130315
Fast Track to Spring 3.x and Spring Web
View Pages and Model Binding
The form at bottom binds to the searchInfo model– It uses the Spring MVC form taglib, which SWF integrates with– modelAttribute="searchInfo" defines the binding– path="keyword" binds the input field to the model's keyword property
The form fires the submitSearch event upon submission– Buttons with names like _eventId_xxx submit a request parameter of
the same name when fired– SWF interprets this as an event of the name xxx– In this case submitSearch
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %><form:form method="post" modelAttribute="searchInfo"><form:input size="20" path="keyword"/><input type="submit" name="_eventId_submitSearch" value="Search"/>
</form:form>
Spring Web Flow uses the Spring MVC form tag library– It does not have a form tag library of its own
You can also specify exactly what bindings are useable in the view, by including a <binder>element in the view state declaration
– Only those properties in the binder will be available, for example to explicitly specify that both the keyword and results property are available, you can do the following
<view-state id="enterSearchCriteria" view="search" model="searchInfo">
<binder>
<binding property="keyword"/>
<binding property="results"/>
<binder>
…. </view-state>
– Each binding element can specify a custom converter (if needed) via the converter attribute, and whether the value is required via the required attribute
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 45220130315
Fast Track to Spring 3.x and Spring Web
Flow Inputs in Flow Definitions
Below top, we declare a flow input named user– required="true" makes it mandatory - a value must be
supplied by a caller
Below center, we show a link supplies the input value – user=Jessica
At bottom, we use the flow variable in a view (a JSP)
<flow …><var name="searchInfo" class="com.javatunes.web.SearchInfo" /><input name="user" required="true"/>…</flow>
<!-- Caller of the flow supplies the flow input --><a href="/javatunes/search.do?user=Jessica">Search</a>
Hi ${user} <!-- input variable also available to views in the flow -->
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 45320130315
Fast Track to Spring 3.x and Spring Web
Actions and Programming in Flow Definitions
SWF uses an Expression Language (EL) and a number of action elements to perform behavior
The standard Spring Expression Language is used– Evaluates expressions to access data and execute methods– Similar to JSP EL– Allows you to, for example, access the keyword property of a searchInfo bean via #{searchInfo.keyword}
There are also three action elements that let you evaluate an expression or perform an action– <evaluate>: Evaluate an expression– <set>: Set the value of a data variable– <render>: Render a fragment of a view
Prior to SWF 2.1, the Unified EL was the default– In SWF 2.1, SpEL was made the default
OGNL (Object-Graph Navigation Language) may also be used as the EL
– This is mostly for backwards compatibility with SWF 1– Most of the syntax of both implementations is the same, and best
practice is to limit your use to that supported by the Unified EL
The Unified EL is a standard Java technology– It is called "Unified" because it combined the syntax of the JSTL
expression language and the JSF expression language
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 45420130315
Fast Track to Spring 3.x and Spring Web
Example of Action: <set>
A view-state transition can perform actions before executing– Below, the <set> will be executed before the transition occurs
<set> has two required attributes– name: The name of the variable to set– value: The value to set the data variable to– Both of these are EL expressions (they are not written with delimiters
like #{} because they will always be expressions *)
<flow …><var name="searchInfo" class="com.javatunes.web.SearchInfo" />
<view-state id="enterSearchCriteria" view="search" model="searchInfo"><transition on="submitSearch" to="viewSearchResults"><set name="searchInfo.results"
value="javaTunesCatalog.findByKeyword(searchInfo.keyword)"/></transition>
</view-state></flow>
EL expressions when used with action elements like set are neverwritten with delimiters like ${}
– Since these values will always be EL expressions, it was decidedthat the use of delimiters would be superflous
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 45520130315
Fast Track to Spring 3.x and Spring Web
Examining an Action: <set>
When the view state below receives the submitSearch event <set> is executed and does the following:– Accesses searchInfo.keyword (which is bound to the requesting
view, and contains the users search input)– Calls javaTunesCatalog.findByKeyword passing searchInfo.keyword as an arg• javaTunesCatalog is a simple catalog bean (see notes)
– Places the return value into the searchInfo.results property
The flow then transitions to the viewSearchResults state– The view (JSP) can use the results e.g.Searched on keyword: ${searchInfo.keyword}
<view-state id="enterSearchCriteria" view="search" model="searchInfo"><transition on="submitSearch" to="viewSearchResults"><set name="searchInfo.results"
value="javaTunesCatalog.findByKeyword(searchInfo.keyword)"/></transition>
</view-state>
javaTunesCatalog is a simple catalog service that we've seen earlier in the course that has two methods:public MusicItem findById(Long id);
public Collection<MusicItem> findByKeyword(String keyword);
– It is declared as a Spring Bean in the normal Spring context definition file– The EL can directly reference Spring beans by name
All view-states and their views in the flow have access to the flow variables– View pages can access the flow variables using the same EL syntax– This lets us access, for example, the searchInfo keyword via ${searchInfo.keyword}– The expression ${fn:length(searchInfo.results)} uses the JSTL function library to get
the length of the results collection– This function library is part of standard JSTL, and is not part of SWF
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 46420130315
Fast Track to Spring 3.x and Spring Web
Review Questions
What does Spring Web Flow provide?
What is a flow?
What are some other important concepts in SWF?
What is a flow registry and a flow executor?
What is a flow instance variable, and how is it used
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 46520130315
Fast Track to Spring 3.x and Spring Web
Lesson Summary
Spring Web Flow addresses the need for defining user interface (UI) flow in a Web application– It allows you to define the UI flow of a Web application in an
explicit, clear, and simple way
A flow encapsulates a sequence of steps within a Web app– Typically defined using XML
Some important elements in a flow are:– State: A point in the flow representing a condition or situation– View: A single page that visualizes (displays) information– Event: An occurrence of some sort that's handled by a state– Transition: A change in state – Usually results in a view navigation– Action: Execution of some business functionality
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.
Notes:
Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 46620130315
Fast Track to Spring 3.x and Spring Web
Lesson Summary
A flow executor handles all flow execution requirements (e.g. executing a transition upon receiving an event in a flow
A flow registry loads flow definitions from XML files
Flow instance variables are created when the flow starts, and are accessible in the entire flow– Declared using <var> in the flow definition– Often used in binding a view to a model
Session 8: Introducing Spring Web Flow
EVALUATION COPY
Unauthorized reproduction or distribution is prohibited.