WA1848 Java EE Programming with Spring 3 Using SpringSource Tool Suite

materialisticrampantInternet and Web Development

Nov 10, 2013 (3 years and 7 months ago)

128 views

EVALUATION ONLY
WA1848 Java EE
Programming with Spring 3
Using SpringSource Tool
Suite
Web Age Solutions Inc.
USA: 1-877-517-6540
Canada: 1-866-206-4644
Web: http://www.webagesolutions.com
EVALUATION ONLY
The following terms are trademarks of other companies:
Java and all Java-based trademarks and logos are trademarks or registered trademarks of
Sun Microsystems, Inc. in the United States, other countries, or both.
Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft
Corporation in the United States, other countries, or both.
UNIX is a registered trademark of The Open Group in the United States and other
countries.
Linux is a trademark of Linus Torvalds in the United States, other countries, or both.
IBM, WebSphere, DB2 and Tivoli are trademarks of the International Business Machines
Corporation in the United States, other countries, or both.
Other company, product, and service names may be trademarks or service marks of
others.
For customizations of this book or other sales inquiries, please contact us at:
USA: 1-877-517-6540, email: getinfousa@webagesolutions.com
Canada: 1-866-206-4644 toll free, email: getinfo@webagesolutions.com
Copyright © 2012 Web Age Solutions Inc.
This publication is protected by the copyright laws of Canada, United States and any
other country where this book is sold. Unauthorized use of this material, including but not
limited to, reproduction of the whole or part of the content, re-sale or transmission
through fax, photocopy or e-mail is prohibited. To obtain authorization for any such
activities, please write to:
Web Age Solutions Inc.
439 University Ave
Suite 820
Toronto
Ontario, M5G 1Y8
EVALUATION ONLY
Table of Contents
Chapter 1 - Introduction to the Spring Framework............................................................15
1.1 What is the Spring Framework?..............................................................................15
1.2 Spring Philosophies.................................................................................................15
1.3 Why Spring?............................................................................................................16
1.4 Spring Modules.......................................................................................................17
1.5 Requirements and Supported Environments...........................................................19
1.6 Using Spring with Servers......................................................................................19
1.7 Role of Spring Container........................................................................................20
1.8 Spring Example.......................................................................................................20
1.9 Spring Example.......................................................................................................21
1.10 Spring Example.....................................................................................................22
1.11 Avoiding Dependency on Spring..........................................................................22
1.12 Additional Spring Projects/Frameworks...............................................................23
1.13 Summary...............................................................................................................24
Chapter 2 - Spring 3 Development Tools..........................................................................25
2.1 SpringSource Tool Suite.........................................................................................25
2.2 Developing Spring 3 Applications With RAD........................................................25
2.3 Sequence of Installation for Spring/RAD/WebSphere...........................................26
2.4 Alternatives to RAD for Spring/WebSphere Development....................................27
2.5 Creating a Spring Project........................................................................................28
2.6 Tools for Spring Beans Configuration Files...........................................................29
2.7 Spring Configuration Validation.............................................................................30
2.8 Spring Web Flow Definition Tools.........................................................................30
2.9 Maven Overview.....................................................................................................31
2.10 Managing Spring JARs with Maven.....................................................................32
2.11 Adding Maven Dependencies...............................................................................32
2.12 Summary...............................................................................................................33
Chapter 3 - Defining and Using Spring Beans...................................................................35
3.1 Spring “Beans”........................................................................................................35
3.2 Spring Containers....................................................................................................35
3.3 Spring Containers....................................................................................................36
3.4 Instantiating the Spring Container..........................................................................37
3.5 Retrieving Spring Beans.........................................................................................37
3.6 Configuring Spring Beans.......................................................................................38
3.7 <bean> Element......................................................................................................39
3.8 Naming Beans.........................................................................................................39
3.9 Setting Bean Properties...........................................................................................40
3.10 Using the Spring XML 'p' Schema........................................................................41
3.11 Creating Beans with a Constructor.......................................................................41
3.12 Resolving Constructor Ambiguity........................................................................42
3.13 Setting Properties vs. Invoking Constructors........................................................43
3.14 Bean Scope............................................................................................................44
3.15 Effect of Bean Scope on Instances........................................................................45
3.16 Summary...............................................................................................................45
EVALUATION ONLY
Chapter 4 - Advanced Spring Bean Configuration............................................................47
4.1 Defining Beans with Annotations...........................................................................47
4.2 Component Stereotype Annotations.......................................................................48
4.3 Spring Component Annotations..............................................................................48
4.4 Bean Scope with Annotations.................................................................................49
4.5 Configuring Classpath Scanning for Spring Beans.................................................50
4.6 Choosing Which Annotations to Use......................................................................52
4.7 Overriding Annotation Configuration with XML...................................................52
4.8 Externalizing Bean Configuration...........................................................................53
4.9 PropertyPlaceholderConfigurer...............................................................................54
4.10 PropertyOverrideConfigurer.................................................................................55
4.11 Inheriting Bean Configuration..............................................................................55
4.12 Lazy Initialization.................................................................................................56
4.13 Declaring Beans from Static Fields.......................................................................57
4.14 Declaring Beans from Object Properties...............................................................57
4.15 Summary...............................................................................................................58
Chapter 5 - Spring Dependency Injection..........................................................................59
5.1 Dependency Injection..............................................................................................59
5.2 Benefits of Dependency Injection...........................................................................59
5.3 Specifying Bean References...................................................................................60
5.4 Constructor Injection...............................................................................................60
5.5 Constructor vs. Setter Injection...............................................................................61
5.6 Injecting Multivalued Properties.............................................................................61
5.7 Other Multivalued Types........................................................................................62
5.8 Specifying the Data Type of Collections................................................................63
5.9 Defining Collections Using Utility Factory Beans.................................................64
5.10 Defining a Reusable Properties From an External File.........................................66
5.11 Bean Scope Effect on Dependency Injection........................................................66
5.12 Autowiring With XML.........................................................................................67
5.13 Autowiring Example.............................................................................................68
5.14 Errors in Autowiring.............................................................................................68
5.15 Excluding a Bean from Autowiring......................................................................69
5.16 Autowiring Multivalued Properties.......................................................................70
5.17 Mixing Explicit and Autowiring...........................................................................71
5.18 Summary...............................................................................................................72
Chapter 6 - Spring Dependency Injection with Annotations.............................................73
6.1 Dependency Injection Annotations.........................................................................73
6.2 @Autowired and @Inject.......................................................................................74
6.3 Locations for @Autowired and @Inject.................................................................75
6.4 Autowiring Multivalued Properties.........................................................................75
6.5 Autowiring by Bean Name with @Resource..........................................................76
6.6 Injecting Named Collections Defined in XML with @Resource...........................77
6.7 Checking Required Dependencies..........................................................................77
6.8 Enforcing Required Properties with XML Autowiring..........................................78
6.9 Multiple @Autowired Constructors........................................................................79
6.10 Multiple Autowiring Matches...............................................................................80
EVALUATION ONLY
6.11 Qualifiers with Annotation-based Autowiring......................................................80
6.12 Adding a Qualifier Value to a Bean Definition....................................................81
6.13 Qualification of Multivalued Properties................................................................82
6.14 Defining Custom @Qualifier Annotations...........................................................83
6.15 Complex Custom @Qualifier Annotations...........................................................84
6.16 Associating Custom Bean Qualifiers with XML..................................................84
6.17 Processing Injection Annotations..........................................................................85
6.18 Overriding Annotation Injection...........................................................................86
6.19 Summary...............................................................................................................87
Chapter 7 - Testing Spring Applications...........................................................................89
7.1 Spring Unit Testing.................................................................................................89
7.2 Configuring Test Projects.......................................................................................89
7.3 Spring TestContext Framework..............................................................................90
7.4 Implementing Test Classes.....................................................................................91
7.5 Loading Spring Configuration with Test Classes...................................................91
7.6 Accessing Spring Components Within Test Classes..............................................92
7.7 Defining Tests to Execute.......................................................................................93
7.8 Isolating Tests Which Modify the Spring Environment.........................................94
7.9 Transactional Testing Support................................................................................94
7.10 Transactional Test Base Classes...........................................................................95
7.11 Avoiding False Positives with ORM Testing........................................................95
7.12 Other Transaction Annotations.............................................................................96
7.13 Other Spring Annotations for JUnit......................................................................97
7.14 Unit Testing Support Classes................................................................................98
7.15 Mock Objects........................................................................................................98
7.16 Summary...............................................................................................................99
Chapter 8 - Introduction to JavaServer Faces..................................................................101
8.1 What is JavaServer Faces (JSF)?..........................................................................101
8.2 Why Use JSF?.......................................................................................................101
8.3 Nature of a JSF Application..................................................................................102
8.4 The Sun Reference Implementation (RI)..............................................................103
8.5 JSF and MVC........................................................................................................103
8.6 JSF and MVC........................................................................................................105
8.7 Faces Servlet.........................................................................................................105
8.8 Faces Servlet.........................................................................................................106
8.9 Faces Servlet.........................................................................................................106
8.10 Managed Bean.....................................................................................................107
8.11 The View.............................................................................................................108
8.12 A Simple JSF Application...................................................................................109
8.13 The Input Form: form.jsp....................................................................................110
8.14 The Result: thanks.jsp.........................................................................................111
8.15 The Controller: AddressBean..............................................................................111
8.16 Page Flow or Navigation Rule............................................................................112
8.17 How Does the Application Work?......................................................................112
8.18 How Does the Application Work?......................................................................113
8.19 Under the Covers: The Rendered Form HTML..................................................114
EVALUATION ONLY
8.20 Under the Covers: The Layout Tree....................................................................115
Chapter 9 - Managed Bean..............................................................................................117
9.1 What is a Managed Bean?.....................................................................................117
9.2 Why Do You Need Managed Beans?...................................................................118
9.3 Managed Bean As a Controller.............................................................................118
9.4 Registering a Managed Bean................................................................................119
9.5 Lifecycle of a Managed Bean...............................................................................120
9.6 Initializing a Managed Bean.................................................................................120
9.7 What Scope to Use?..............................................................................................121
9.8 Value Binding.......................................................................................................121
9.9 Value Binding.......................................................................................................122
9.10 Property Data Conversion...................................................................................123
9.11 Advanced Property Types...................................................................................123
9.12 Advanced Property Types...................................................................................124
9.13 Component Binding............................................................................................125
9.14 Other Binding Types...........................................................................................126
9.15 Basic Input Processing........................................................................................126
9.16 Advanced Input Processing.................................................................................127
9.17 JSF Expression Language...................................................................................128
9.18 Language Basics..................................................................................................128
9.19 Use of Expression in JSF....................................................................................129
9.20 Basic Expression.................................................................................................129
9.21 Property Access Expression................................................................................130
9.22 Map Access Expression......................................................................................131
9.23 Complex Access Expression...............................................................................131
9.24 Predefined Objects..............................................................................................131
9.25 Operators.............................................................................................................131
Chapter 10 - Using JSF with Spring................................................................................133
10.1 JSF Integration Options.......................................................................................133
10.2 DelegatingVariableResolver...............................................................................133
10.3 DelegatingVariableResolver...............................................................................134
10.4 SpringBeanVariableResolver..............................................................................134
10.5 SpringBeanFacesELResolver..............................................................................134
10.6 Spring Bean Scopes.............................................................................................135
10.7 FacesContextUtils...............................................................................................135
10.8 JSF with Spring Web Flow.................................................................................136
Chapter 11 - User Interface Components.........................................................................137
11.1 JSF UI Components............................................................................................137
11.2 JSF UI Components............................................................................................138
11.3 JSF Component Tag Libraries............................................................................138
11.4 Using the Tag Libraries.......................................................................................139
11.5 HTML Tag Library.............................................................................................140
11.6 HTML Tag Library.............................................................................................140
11.7 Identifying Components......................................................................................141
11.8 Component Identifier..........................................................................................141
11.9 Client Identifier...................................................................................................142
EVALUATION ONLY
11.10 Form Input Field Names...................................................................................143
11.11 Define a Form...................................................................................................143
11.12 Labels and Images.............................................................................................144
11.13 Buttons..............................................................................................................145
11.14 Links..................................................................................................................145
11.15 Links..................................................................................................................146
11.16 Adding Parameters to Links..............................................................................147
11.17 Text Input..........................................................................................................147
11.18 Simple Check Box.............................................................................................148
11.19 Check Box Group..............................................................................................149
11.20 Check Box Group Example..............................................................................149
11.21 Radio Button.....................................................................................................150
11.22 List Boxes..........................................................................................................150
11.23 List Boxes..........................................................................................................151
11.24 List Boxes..........................................................................................................152
11.25 Dynamic List Box.............................................................................................152
11.26 Example.............................................................................................................153
11.27 Another Example..............................................................................................153
11.28 JSF Core Library...............................................................................................154
11.29 JSF Core Library - Components.......................................................................155
11.30 JSF Core Library - Components.......................................................................155
11.31 JSF Core Library - Components.......................................................................156
11.32 JSF Core Library - Components.......................................................................157
11.33 JSF Core Library - Components.......................................................................158
11.34 JSF Component Model......................................................................................159
11.35 JSF Component Model......................................................................................159
11.36 Base Class Hierarchy........................................................................................160
11.37 Useful Base Classes..........................................................................................160
11.38 Useful HTML Classes.......................................................................................161
11.39 Useful HTML Classes.......................................................................................161
Chapter 12 - JSF Event Handling....................................................................................163
12.1 Request Processing Phases..................................................................................163
12.2 Action Request Processing Phases......................................................................164
12.3 Action Request Processing Phases......................................................................164
12.4 Action Request Processing Phases......................................................................165
12.5 JSF Event & Listener Model…...........................................................................166
12.6 JSF Event Classes...............................................................................................167
12.7 Event Classes......................................................................................................167
12.8 Event Classes: Hierarchy....................................................................................168
12.9 Action Event Handling........................................................................................168
12.10 Action Event: Example.....................................................................................169
12.11 Action Listener..................................................................................................169
12.12 Value Change Event..........................................................................................170
12.13 Value Change Event Handler............................................................................170
12.14 Value Change Event Handler............................................................................171
12.15 Value Change Event Handler............................................................................172
EVALUATION ONLY
12.16 Listener Classes.................................................................................................173
12.17 Listener Interfaces.............................................................................................173
12.18 Listener Classes: Hierarchy...............................................................................174
12.19 Action Listener Class........................................................................................175
12.20 Value Change Listener Class............................................................................175
12.21 Phase Event Listener.........................................................................................176
12.22 Request Processing Lifecycle...........................................................................177
12.23 Phase Identifiers................................................................................................177
12.24 Phase Identifiers................................................................................................178
Chapter 13 - JSF Navigation............................................................................................179
13.1 JSF Navigation....................................................................................................179
13.2 Example Action Listener.....................................................................................179
13.3 faces-config.xml File...........................................................................................180
13.4 JSF Navigation....................................................................................................181
13.5 JSF Navigation....................................................................................................181
13.6 JSF Navigation....................................................................................................182
13.7 Choosing Between Redirect & Direct Rendering...............................................182
13.8 Navigation Rules: Example.................................................................................182
13.9 Navigation Rules: Example.................................................................................183
13.10 Navigation: Scenarios.......................................................................................184
13.11 Navigation: Scenarios.......................................................................................184
13.12 Navigation: Scenarios.......................................................................................185
13.13 Navigation: Scenarios.......................................................................................185
13.14 Navigation: Scenarios.......................................................................................186
13.15 Navigation: Scenarios.......................................................................................187
13.16 Navigation: Scenarios.......................................................................................188
Chapter 14 - Advanced GUI Components.......................................................................189
14.1 HTML Panel........................................................................................................189
14.2 Applying Styles...................................................................................................190
14.3 Grouping Components........................................................................................190
14.4 Data Table...........................................................................................................191
14.5 Using a Data Table..............................................................................................191
14.6 Data Table Model................................................................................................192
14.7 Data Table Model................................................................................................193
14.8 Using a Data Table..............................................................................................193
14.9 Displaying a Header and Footer Row.................................................................194
14.10 Applying Styles.................................................................................................194
14.11 Adding Links to a Row.....................................................................................195
14.12 Using Component Binding................................................................................195
14.13 Handling Action................................................................................................196
14.14 Using the Data Table Model.............................................................................197
14.15 Handling Action................................................................................................197
Chapter 15 - Entities and Java Persistence API...............................................................199
15.1 Data Persistence..................................................................................................199
15.2 Data Persistence..................................................................................................199
15.3 Java Persistence API...........................................................................................200
EVALUATION ONLY
15.4 Entities.................................................................................................................200
15.5 Session Beans Vs Entities...................................................................................201
15.6 Entities.................................................................................................................201
15.7 Entities.................................................................................................................202
15.8 Persisting and Retrieving Data............................................................................202
15.9 Accessing Entities...............................................................................................203
15.10 EntityManager & Persistence Unit....................................................................203
15.11 Persistence Context...........................................................................................204
15.12 Entities - Example.............................................................................................204
15.13 Entities - Example.............................................................................................205
15.14 persistence.xml – Hibernate Provider...............................................................206
15.15 persistence.xml – Open JPA Provider...............................................................207
15.16 persistence.xml - Toplink..................................................................................207
15.17 Entity Instance Lifecycle...................................................................................208
15.18 Entity Instance Lifecycle...................................................................................208
15.19 Creating EntityManager in Session EJB...........................................................209
15.20 Creating EntityManager in a Plain Java Class..................................................210
15.21 Working With the EntityManager Interface.....................................................210
15.22 Working With the EntityManager Interface.....................................................211
15.23 Transaction Basics............................................................................................211
15.24 Summary...........................................................................................................212
Chapter 16 - Using Spring with JPA or Hibernate..........................................................213
16.1 Spring ORM........................................................................................................213
16.2 Benefits of Using Spring with ORM...................................................................213
16.3 Spring @Repository............................................................................................214
16.4 Using JPA with Spring........................................................................................215
16.5 Configure Spring JPA EntityManagerFactory....................................................216
16.6 Using JNDI to Lookup JPA EntityManagerFactory...........................................216
16.7 LocalContainerEntityManagerFactoryBean.......................................................217
16.8 LocalEntityManagerFactoryBean.......................................................................218
16.9 Application JPA Code.........................................................................................218
16.10 Hibernate...........................................................................................................219
16.11 Hibernate...........................................................................................................220
16.12 Hibernate Session Factory.................................................................................221
16.13 Spring LocalSessionFactoryBean.....................................................................221
16.14 Application Hibernate Code..............................................................................222
16.15 "Classic" Spring ORM Usage...........................................................................223
16.16 Spring JpaTemplate...........................................................................................223
16.17 Spring JpaCallback............................................................................................224
16.18 JpaTemplate Convenience Features..................................................................225
16.19 Spring HibernateTemplate................................................................................225
16.20 Spring HibernateCallback.................................................................................226
16.21 HibernateTemplate Convenience Methods.......................................................226
16.22 Summary...........................................................................................................227
Chapter 17 - JPA Entity Lifecycle...................................................................................229
17.1 Entity Lifecycle...................................................................................................229
EVALUATION ONLY
17.2 When is an Entity Managed or Detached?..........................................................230
17.3 Implementing the CRUD Pattern........................................................................231
17.4 Accessing Entities Using Stateless Session Beans..............................................231
17.5 Inserting Data......................................................................................................232
17.6 Retrieving Data...................................................................................................232
17.7 Updating Data.....................................................................................................233
17.8 Deleting Data......................................................................................................233
17.9 Merging Entities..................................................................................................234
17.10 Merging Entities (example)...............................................................................234
17.11 Life-Cycle Callbacks.........................................................................................235
17.12 Life-Cycle Callbacks.........................................................................................236
17.13 Example: Internal callback................................................................................236
17.14 Example: Internal callback................................................................................236
17.15 External Callback Class....................................................................................237
17.16 Listener Class - Example..................................................................................237
17.17 Synchronizing with Databases..........................................................................238
17.18 Entity Lookup....................................................................................................238
17.19 JPAQL (JPA Query Language).........................................................................239
17.20 Summary...........................................................................................................239
Chapter 18 - Java Persistence Query Language (JPA QL)..............................................241
18.1 JPA Query Language..........................................................................................241
18.2 Basic JPAQL Syntax...........................................................................................241
18.3 Simple SELECT Examples.................................................................................242
18.4 Example of Using JPAQL...................................................................................242
18.5 The SELECT clause............................................................................................243
18.6 Reading Data from Code.....................................................................................244
18.7 The WHERE Clause...........................................................................................245
18.8 The WHERE Clause...........................................................................................246
18.9 The WHERE Clause...........................................................................................246
18.10 The WHERE Clause.........................................................................................247
18.11 Example Using JPAQL from Session EJB.......................................................248
18.12 Named Query....................................................................................................248
18.13 Named Query....................................................................................................249
18.14 Multiple Named Queries...................................................................................249
18.15 Bulk Updates.....................................................................................................250
18.16 Bulk Delete........................................................................................................250
18.17 Running Native SQL Query..............................................................................251
18.18 Native SELECT Query.....................................................................................251
18.19 Native SQL Delete and Insert...........................................................................252
18.20 Named Native Query.........................................................................................253
18.21 Named Native Query.........................................................................................253
18.22 Summary...........................................................................................................253
Chapter 19 - Basic Entity Relationships..........................................................................255
19.1 Relationship Between Entities............................................................................255
19.2 Anatomy of a Relationship..................................................................................256
19.3 Anatomy of a Relationship..................................................................................256
EVALUATION ONLY
19.4 Foreign Key.........................................................................................................257
19.5 Example Schema.................................................................................................258
19.6 One-to-One Unidirectional..................................................................................259
19.7 Creating Entity Instances....................................................................................259
19.8 Traversing the Relationship................................................................................260
19.9 The Cascade Behavior.........................................................................................261
19.10 One-to-One Bidirectional..................................................................................262
19.11 Maintaining Bidirectional Links.......................................................................262
19.12 Simplifying Bidirectional Links........................................................................263
19.13 Traversing the Relationship..............................................................................264
19.14 Summary...........................................................................................................265
Chapter 20 - Complex Entity Relationships....................................................................267
20.1 One-To-Many and Many-To-One.......................................................................267
20.2 Many-to-One Unidirectional...............................................................................268
20.3 Creating Entity Instances....................................................................................269
20.4 Traversing the Relationship................................................................................270
20.5 Modeling One-to-Many......................................................................................271
20.6 Maintaining Bidirectional Links.........................................................................271
20.7 Maintaining Bidirectional Links.........................................................................272
20.8 Maintaining Bidirectional Links.........................................................................273
20.9 Creating Entity Instances....................................................................................273
20.10 Creating Entity Instances..................................................................................274
20.11 Traversing the Relationship..............................................................................274
20.12 Many-to-Many..................................................................................................275
20.13 Modeling Many-to-Many..................................................................................275
20.14 Maintaining Bidirectional Links.......................................................................277
20.15 Maintaining Bidirectional Links.......................................................................277
20.16 Creating Entity Instances..................................................................................278
20.17 Traversing Relationship....................................................................................279
20.18 Unidirectional One-to-Many.............................................................................280
20.19 Modeling Unidirectional One-to-Many............................................................280
20.20 Creating Entity Instances..................................................................................281
20.21 Traversing the Relationship..............................................................................282
20.22 Relationship in JPA QL....................................................................................282
20.23 Fetching Optimizations.....................................................................................283
20.24 Lazy vs. Eager Initialization.............................................................................283
20.25 Lazy Initialization.............................................................................................284
20.26 Various Problems with Lazy Initialization.......................................................284
20.27 Fetch Join Query...............................................................................................285
20.28 Summary...........................................................................................................285
Chapter 21 - Spring, JSF and JPA Integration.................................................................287
21.1 Integrating JSF....................................................................................................287
21.2 JPA......................................................................................................................287
21.3 Spring..................................................................................................................287
21.4 Putting It All Together........................................................................................288
21.5 Simple Application..............................................................................................288
EVALUATION ONLY
21.6 Code the JPA Entity............................................................................................289
21.7 The Managed Bean.............................................................................................289
21.8 Entity as Managed Bean......................................................................................290
21.9 Entity as a Field of the Managed Bean...............................................................290
21.10 Accessing the Entity Manager..........................................................................291
21.11 EntityManager in JSF Managed Bean...............................................................291
21.12 Separate Spring Component Works with EntityManager.................................292
21.13 Separate Spring Component Works with EntityManager.................................293
21.14 Entity As DTO..................................................................................................293
21.15 Managed Bean Scope........................................................................................294
21.16 Summary...........................................................................................................294
Chapter 22 - Spring Web Service Implementation Options............................................295
22.1 Web Services in Spring Applications.................................................................295
22.2 Spring Web Service Options...............................................................................295
22.3 Injecting Spring Components Into Web Service Classes....................................296
22.4 Using Spring with JAX-WS Web Services.........................................................296
22.5 Extending the SpringBeanAutowiringSupport Class..........................................297
22.6 Using a @PostConstruct Initialization Method..................................................298
22.7 Combining @PostConstruct and @Autowired...................................................298
22.8 Comparing Third Party Frameworks with Spring-WS.......................................299
22.9 Comparing Third Party Frameworks with Spring-WS.......................................299
22.10 Summary...........................................................................................................300
Chapter 23 - Spring JMS..................................................................................................301
23.1 Spring JMS..........................................................................................................301
23.2 JmsTemplate.......................................................................................................302
23.3 Connection and Destination................................................................................302
23.4 JmsTemplate Configuration................................................................................303
23.5 Transaction Management....................................................................................304
23.6 Example Transaction Configuration...................................................................304
23.7 Producer Example...............................................................................................305
23.8 Consumer Example.............................................................................................306
23.9 Converting Messages..........................................................................................307
23.10 Converting Messages........................................................................................307
23.11 Converting Messages........................................................................................308
23.12 Message Listener Containers............................................................................309
23.13 Message-Driven POJO's Async Receiver Example..........................................309
23.14 Message-Driven POJO's Async Receiver Configuration..................................310
23.15 Summary...........................................................................................................311
Chapter 24 - Review of New Features in Spring 3.0.......................................................313
24.1 Requirements and Supported Environments.......................................................313
24.2 Using Spring with Servers..................................................................................313
24.3 Packaging............................................................................................................314
24.4 Spring Expression Language...............................................................................314
24.5 Java-based Configuration....................................................................................315
24.6 Java-based Configuration....................................................................................316
24.7 Annotation-based Configuration.........................................................................316
EVALUATION ONLY
24.8 Annotation-based Configuration.........................................................................317
24.9 Spring MVC Changes.........................................................................................317
24.10 New Spring MVC Configuration......................................................................318
24.11 Spring MVC Annotation Example....................................................................319
24.12 Validation..........................................................................................................319
24.13 Summary...........................................................................................................320
EVALUATION ONLY
EVALUATION ONLY
Chapter 1 - Introduction to the Spring Framework
Objectives
Key objectives of this chapter:
 What is the Spring Framework?
 Spring Modules
 Role of Spring Container
1.1 What is the Spring Framework?
 Spring is an open-source Java platform that provides infrastructure
support for Java applications
 Spring applications are more
◊ Testable
◊ Flexible
◊ Easier to maintain
◊ Can be used with existing frameworks such as JSF, Struts
 Spring provides many things that are common to many Java applications
so you can concentrate more on what is different about your application
What is the Spring Framework?
The Spring Framework was created by Rod Johnson. It has been an open source project since February
2003.
See http://www.springframework.org for more information.
1.2 Spring Philosophies
 Java EE should be easy to use
◊ Spring started as an alternative to EJB technology when EJB
programming was more difficult and had odd restrictions that had to be
followed
◊ The Java EE programming model has been simplified in the last
EVALUATION ONLY
Chapter 1 - Introduction to the Spring Framework
several versions because of the popularity of frameworks like Spring
 Object-oriented design is more important than the underlying technology
 It is better to code to interfaces than classes
◊ This creates a "loosely coupled" application where what is important is
not the implementation of a component but the functionality it provides
to other components
 Applications should be easy to test
◊ A loosely coupled application can be more easily tested in isolation
 JavaBeans are a good way of assembling applications
Spring Philosophies
The creators of Spring believe that good design is more important than the underlying technology,
whether it be EJB or otherwise. EJB and other frameworks force developers to implement applications
in a certain (restrictive) way. The goal of Spring is to remove these restrictions and allow developers to
implement their objects without thinking about the underlying infrastructure.
Additionally, it should be easy to test your code. Binding your code to a particular technology can
make this difficult. For example, EJB forces you to redeploy to the EJB container in order to run tests.
Spring facilitates easier coding to interfaces. This makes your application loosely coupled, easier to
maintain and easier to test. Objects no longer have to look up their dependencies as the Spring
container will inject their dependencies into them.
JavaBeans is a simple specification. There isn’t a lot that a developer needs to know to create a simple
JavaBean. This allows them to focus on business logic rather than being concerned with infrastructure.
JavaBeans combined with IoC is a powerful model.
1.3 Why Spring?
 Components in enterprise applications require services such as
transactions, security and distributed computing
 As much as possible, these services should be kept separate from
application business logic
 EJB was created to address this need and make enterprise application
development easier
 While EJB solved many of these issues, it introduced new complications
16
EVALUATION ONLY
Chapter 1 - Introduction to the Spring Framework
◊ Many of these issues were solved with EJB 3.0 but existed when
Spring was first developed and gained popularity
 EJBs also required the use of a Java EE "application server" environment
◊ With Spring you can leverage the benefits in "standalone" Java
applications like Applets or Java Swing GUI programs
◊ When Spring was first created many of the J2EE Application Servers
had a reputation as "heavyweight" also
 Spring also provides many utility functions not found in the Java EE
specifications
1.4 Spring Modules
17
EVALUATION ONLY
Chapter 1 - Introduction to the Spring Framework
Spring Modules
The above diagram comes from the current Spring 3.0 documentation.
The Spring Framework consists of features organized into about 20 modules. These modules are
grouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming),
Instrumentation, and Test, as shown in the above diagram.
An application can utilize one of the modules without having to use other modules. For example, an
application could use the Spring AOP module but not use Spring MVC.
Modules can build on one another as illustrated on the slide. All modules are built on the core
container and utilities module.
• Core Container – Contains the core functionality of Spring. This includes the Core (IoC and
Dependency Injection features), Beans (BeanFactory), Context (ApplicationContext), and
Expression Language modules (querying and manipulating an object graph at runtime).
• Data Access/Integration - The Data Access/Integration layer consists of the JDBC, ORM,
OXM, JMS and Transaction modules.
◦ JDBC – Provides facilities that allow developers to write code that does not contain
complex JDBC setup/teardown/exception handling logic. Also contains an enhanced
exception hierarchy with more descriptive database error messages for many database
vendors.
◦ ORM – This module facilitates easy integration with some popular ORM frameworks
including JPA, Hibernate, iBATIS and JDO.
◦ OXM – This module provides an abstraction layer that supports Object/XML mapping
implementations for JAXB, Castor, XMLBeans, JiBX and XStream.
◦ JMS – This module contains features for producing and consuming messages.
◦ Transaction – This module supports programmatic and declarative transaction management
for classes that implement special interfaces and for all your POJOs.
• Web – This Web layer consists of the Web, Web-Servlet, Web-Struts, and Web-Portlet
modules.
◦ Web – This module featuring initialization of the IoC container using servlet listeners and a
web-oriented application context. It also contains the web-related parts of Spring's remoting
support.
◦ Web-Servlet – This module contains Spring's model-view-controller (MVC) implementation
for web applications.
◦ Web-Struts – This module contains the support classes for integrating a classic Struts web
tier within a Spring application. Note that this support is now deprecated as of Spring 3.0.
Consider migrating your application to Struts 2.0 and its Spring integration or to a Spring
MVC solution.
18
EVALUATION ONLY
Chapter 1 - Introduction to the Spring Framework
◦ Web-Portlet – This module provides the MVC implementation to be used in a portlet
environment and mirrors the functionality of Web-Servlet module.
• AOP and Instrumentation
◦ AOP – Provides support for aspect-oriented programming and metadata programming
using source code level annotations.
◦ Aspects – Provides separate integration with AspectJ.
◦ Instrumentation – This module provides class instrumentation support and classloader
implementations to be used in certain application servers.
1.5 Requirements and Supported Environments
 One of the major changes is that Spring 3.0 requires a Java SE 5 or Java
SE 6 environment
◊ Spring 3.0 will not work in a Java JDK 1.4 environment or earlier
 Much of the Spring codebase has been revised to take advantage of Java
5 features like Generics and annotations
◊ You will find methods in the Spring API like the following from the
BeanFactory interface that use generics for strongly typed return values
T getBean(Class<T> requiredType)
T getBean(String name, Class<T> requiredType)
Map<String, T> getBeansOfType(Class<T> type)
1.6 Using Spring with Servers
 Spring 3.0 is compatible with Java EE servers as long as they also use
Java SE 5 or above
◊ WebLogic Server 9.x, 10.x, 11g, 12
◊ WebSphere 6.1, 7.0, and 8.0
◊ JBoss 4.2, 5.0, 5.1, 6.0, and 7.0
◊ Glassfish v1, v2, and v3
 For those that may want to use a non-Java EE server environment Spring
19
EVALUATION ONLY
Chapter 1 - Introduction to the Spring Framework
3.0 is also compatible with some of the servers provided or supported by
SpringSource
◊ SpringSource tc Server 6.0.19A and later
◊ SpringSource dm Server 2.0
◊ Tomcat 5.0, 5.5, 6.0, and 7.0
1.7 Role of Spring Container
 Typically in a Spring application, if you look just at the code of the
application itself, there may seem to be something missing
◊ All of your application components are very generic and loosely
coupled but the question arises "How do they link up with each other?"
 The missing piece is the role of the Spring container, which takes the code
of your application components, along with configuration meta-data and
configures an environment where component instances are initialized and
linked together according to this configuration
 The configuration of a Spring application can be provided in multiple ways
◊ XML files – This was the original way to provide configuration
◊ Annotations in source code – Now that Spring 3 requires Java SE 5 this
is more popular
◊ Java @Configuration classes – This used to be a separate project to
allow this but is now part of the regular Spring framework
1.8 Spring Example
 This simple example will show one of the core features of Spring,
Dependency Injection
 The core of this example is built around an interface for a component that
will calculate taxes
public interface TaxCalculator {
public double calculateTax(double amount);}
 Of course there will also need to be a implementation of the interface to
20
EVALUATION ONLY
Chapter 1 - Introduction to the Spring Framework
actually do anything
public class SalesTaxCalculator implements TaxCalculator {
private double taxRate = 0.05;// default rate
public double calculateTax(double amount) {
return amount * taxRate;
} }
 There is also another Java component that uses the TaxCalculator
component
◊ Notice that this class does not refer to the SalesTaxCalculator class
public class Register {
private TaxCalculator taxCalc;
public double computeTotal(double beforeTax) {
return beforeTax +
taxCalc.calculateTax(beforeTax);
} }
1.9 Spring Example
 Looking at the code from the previous slide there are some questions:
◊ How do we avoid a NullPointerException in the Register class when
using the 'taxCalc' field?
◊ How is the SalesTaxCalculator class used to calculate the tax when the
Register class doesn't refer to it?
 The missing piece is the configuration that can be provided to the Spring
container to link the two components
◊ The example below is simplified somewhat but you can see the Spring
configuration indicates the 'salesTaxCalc' bean should be used as the
'taxCalc' property of the 'register' bean
<beans ... >
<bean id="salesTaxCalc"
class="SalesTaxCalculator" />
<bean id="registerBean" class="Register">
<property name="taxCalc"
ref="salesTaxCalc" />
</bean>
21
EVALUATION ONLY
Chapter 1 - Introduction to the Spring Framework
</beans>
Spring Example
The Spring XML syntax given would also assume there is a 'setTaxCalc' method in the 'Register' class
although this is not the only way to link the two components.
1.10 Spring Example
 You could then initialize a Spring environment using the above
configuration and obtain the "registerBean" from Spring with the link to the
other component already initialized
ApplicationContext context = new
ClassPathXmlApplicationContext("springConfig.xml");
// get the bean
Register register =
context.getBean("registerBean", Register.class);
// use the bean
double total = register.computeTotal(18.45);
 Besides providing XML configuration you could also:
◊ Use Spring annotations like @Component to declare the Java classes
as a Spring component and @Autowired to initialize the 'taxCalc' field
◊ Use Spring Java Configuration with the @Configuration annotation on a
class to indicate it executes Java code to initialize Spring components
and the @Bean annotation on methods that execute Java statements
and return configured Spring components
1.11 Avoiding Dependency on Spring
 One of the goals of Spring is to be "non-intrusive" so it should be possible
to use the code that you write with another framework that provides similar
behavior and move away from Spring if desired
 Although this might not be a purely painless prospect there are a few
things you can do to help ensure this:
◊ Make as many Java classes and components contain only "standard"
Java code
22
EVALUATION ONLY
Chapter 1 - Introduction to the Spring Framework
 The classes from the example accomplished this
◊ If you reference Spring from your code try to limit it to annotations only
 Even annotations would mean a Spring 'import' statement in your
code but annotations are just added at the class/method/field level to
enable certain Spring features
 Other frameworks might provide similar annotations that would be a
replacement
◊ Avoid extending Spring classes or implementing Spring interfaces with
your code
 This would create code that is more directly linked to Spring
 If you need to do this "hide" these classes from other parts of the
application to limit the amount of code that is Spring-aware
1.12 Additional Spring Projects/Frameworks
 Spring also provides many additional projects and frameworks for things
like web applications, web services, etc
◊ Spring MVC – A web application framework part of the core "web"
module
◊ Spring Web Flow – A separate project with a model for "wizard-like"
web application interactions
◊ Spring Security – A security framework for web or non-web Java
applications
◊ Spring Web Services – A Spring implementation of web services
◊ Spring Integration – A Spring implementation of Enterprise Integration
patterns
◊ Many others - http://www.springsource.org/projects
 If you want to avoid dependence on Spring look to see if you can
implement the same functionality with Java standards without depending
on Spring
23
EVALUATION ONLY
Chapter 1 - Introduction to the Spring Framework
1.13 Summary
 Spring is a modular Java application framework
 One of the prime functions is the ability to instantiate and configure Java
components that can then be linked into other parts of the application
24
EVALUATION ONLY
Chapter 2 - Spring 3 Development Tools
Objectives
Key objectives of this chapter
 Overview of Spring Tools in SpringSource Tool Suite
2.1 SpringSource Tool Suite
 SpringSource Tool Suite is a Eclipse-based tool that specializes in
developing Spring applications
 It is available as a free download
◊ http://www.springsource.com/products/sts
 The tool requires a Java JDK 1.5 or above for installation
 Besides installing the standard Eclipse Java EE tools and Spring tools it
also installs
◊ Eclipse plugins for Maven and AspectJ
◊ SpringSource dm Server tools
◊ SpringSource tc Server runtime (based on Tomcat)
◊ Spring Roo tools
◊ Groovy & Grails tools
 The tool provides a Spring perspective and some Spring-specific views
2.2 Developing Spring 3 Applications With RAD
 When developing applications for WebSphere it is common to use RAD
(Rational Application Developer)
 The RAD software does not include Spring tools by itself
 It is possible to install a combination of RAD and SpringSource Tool Suite
to combine Spring and WebSphere tools
◊ This is possible because the RAD installation can extend an existing
installation of Eclipse (in this case SpringSource Tool Suite)
EVALUATION ONLY
Chapter 2 - Spring 3 Development Tools
◊ It is critical to match the version of the Eclipse platform used by both so
currently this can only be done with RAD 8 and a version of
SpringSource Tool Suite that uses Eclipse 3.6
 RAD 8 supports development for WebSphere 6.1, 7.0, and 8.0
 In order to allow RAD to install the WebSphere tools though the extended
Eclipse installation must use an IBM JDK
◊ You can get this by installing a WebSphere server environment, like
WebSphere Application Server for Developers first
Developing Spring 3 Applications With RAD
WebSphere Application Server for Developers is a free installation of a WAS server environment that
is not an expiring trial edition.
Spring 3.0 will not run on WebSphere 6.0 even though RAD 8 does have tools for WAS 6.0.
2.3 Sequence of Installation for Spring/RAD/WebSphere
 Install the WebSphere test server such as WAS for Developers
◊ This makes the test server and the IBM JDK available
 Install SpringSource Tool Suite using the JDK installed by the WebSphere
server when prompted
 Install RAD 8 indicating to extend the Eclipse software installed with
SpringSource Tool Suite
26
EVALUATION ONLY
Chapter 2 - Spring 3 Development Tools
Sequence of Installation for Spring/RAD/WebSphere
When installing RAD, make sure the 'WebSphere Application Server development tools' for the
WebSphere version you will be using are installed. If SpringSource Tool Suite does not use the IBM
JDK the RAD install will not allow you to install these tools.
2.4 Alternatives to RAD for Spring/WebSphere Development
 It is no longer required that you use RAD to develop WebSphere
applications
 MyEclipse has a few different editions that support WebSphere and Spring
development
◊ MyEclipse Blue is the main WebSphere edition and does have the
same basic tools as SpringSource Tool Suite
◊ MyEclipse “Bling” has all the features of MyEclipse Blue and the more
advanced Spring tools of the MyEclipse Spring edition
 Blue + Spring = Bling :)
◊ MyEclipse software is not free but cheaper than RAD
27
EVALUATION ONLY
Chapter 2 - Spring 3 Development Tools
2.5 Creating a Spring Project
 There are a few different ways to
add Spring capabilities to a
project
◊ New Spring Project
 Basically a Java project with
Spring tools enabled
◊ New Spring Template Project
 Common project types
 Uses Maven for
dependencies
 This is the only project type
that will automatically
include Spring JAR files
◊ Add 'Spring Nature' to existing
project
28
EVALUATION ONLY
Chapter 2 - Spring 3 Development Tools
2.6 Tools for Spring Beans Configuration Files
 A wizard can help create Spring
XML configuration files
◊ Letting the wizard add some of
the many Spring XML
namespace settings can
greatly simplify the process
 An editor can help add standard
Spring configuration tags to the
file
◊ Selecting an individual bean
definition allows setting many
other properties
 A "Beans Graph" in the editor can
show how different beans relate
29
EVALUATION ONLY
Chapter 2 - Spring 3 Development Tools
2.7 Spring Configuration Validation
 Validation of Spring projects
includes verification that Spring
bean definitions refer to valid Java
classes and that references to
other Spring beans is valid
 Defining Spring 'Config Sets' can
allow validation of Spring beans
between multiple files
◊ This is important since Spring
configuration is often split into
multiple files for modularity
◊ Access this setting by using
Spring → Beans Support
properties of a project
2.8 Spring Web Flow Definition Tools
 A wizard can create a new Web
Flow definition file
◊ An option can use Web Flow 2
syntax
◊ The flow definition file can be
linked to configuration files for
validation
 A graphical editor is provided for
Web Flow definition files
◊ Graphical representation of
flow states can be created by
using the 'Palette' view
30
EVALUATION ONLY
Chapter 2 - Spring 3 Development Tools
2.9 Maven Overview
 Maven is a build system that can perform a lot of features
◊ One of the most useful features for Spring projects is the ability to
manage the library JARs a project depends on
◊ Many open source projects have been structured to provide Maven
information
 Maven is based on a "Project Object Model" or POM
◊ There are lots of project settings that are often provided with pom.xml
 One of the important Maven project properties is the external
dependencies of a project
◊ This is important because many open source projects, including Spring,
depend on other projects so when you include these projects you may
need to include other JARs
◊ The Maven information of an open source project can tell you what
other JAR libraries are required
 When getting project dependencies with Maven you can either go out to
the internet or create a local repository mirror
 Besides the "Central" Maven repository there is a SpringSource
"Enterprise Bundle Repository" that you can use to get Spring and other
Spring dependencies
Maven Overview
We won't be focusing on all the features of Maven but mainly the ability to manage project
dependencies.
Configuration of internet proxy settings, local storage of Maven artifacts, and Maven repositories,
including mirror repositories can all be configured by a Maven settings file.
You can find out more info about the SpringSource Enterprise Bundle Repository here:
https://ebr.springsource.com/repository/app/
http://blog.springsource.com/2009/12/02/obtaining-spring-3-artifacts-with-maven/
31
EVALUATION ONLY
Chapter 2 - Spring 3 Development Tools
2.10 Managing Spring JARs with Maven
 SpringSource Tool Suite installs a version of Maven
 It also includes Eclipse plug-ins for Maven that can let Maven provide
entries on the project classpath from the Maven dependencies
◊ Right now the Eclipse tools and Maven compete somewhat for who is
in charge of building the project since both can do this
◊ When adding Maven to an Eclipse project like a "Dynamic Web Project"
Maven may alter some of the project settings that may need to be fixed
 One way to use Maven and Eclipse is to use the regular Eclipse tools for
the project but add Maven to manage the dependencies
 The build path of the Eclipse project can include JARs configured as
Maven dependencies
Managing Spring JARs with Maven
The integration between Maven Eclipse tools and the rest of the Eclipse tools is something that will
hopefully be better in future versions of Eclipse. Ideally you would be able to configure how much of
the build process Maven would be involved with instead of it just assuming that Maven is doing the
build.
2.11 Adding Maven Dependencies
 Within the Maven pom.xml file you would indicate the external
dependencies of the project
 In the configuration of the dependency the groupId, artifactId, and
version will differ depending on the dependency you are using and
32
EVALUATION ONLY
Chapter 2 - Spring 3 Development Tools
perhaps the Maven repository
<dependency>
<groupId>org.springframework</groupId>
<artifactId>org.springframework.context</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
 Since Maven can calculate the hierarchy of dependencies you often only
have to indicate the top level features that you are using with your
application
◊ The dependency above would automatically include other parts of the
Spring framework required by the Spring Context module
Adding Maven Dependencies
One of the primary benefits of using Maven to manage dependencies is you can ignore many of the
low-level dependencies that are not directly needed for your project. This simplifies the process of
including open source projects, like Spring or Hibernate, that may depend on other libraries to function
but are not JARs you necessarily need to be directly aware of.
2.12 Summary
 The SpringSource Tool Suite is an easy integration of Spring and Eclipse
tools
 The tools available can simplify development of Spring applications
 Validation of Spring configuration can reduce time spent troubleshooting
application problems
33
EVALUATION ONLY
EVALUATION ONLY
Chapter 3 - Defining and Using Spring Beans
Objectives
Key objectives of this chapter
 Spring "Beans"
 Spring Containers
 Configuring Spring beans
 Using bean constructors
 Bean scope
3.1 Spring “Beans”
 The core concept in the Spring framework is the concept of a “bean”
◊ A Spring “bean” is a Java component managed by a Spring container
 The Spring container is an environment that can instantiate, assemble,
and manage Spring beans according to configuration “metadata”
◊ This configuration metadata might be provided by several means
including XML configuration files or annotations
 Spring “beans” are meant to be “regular POJOs” (Plain Old Java Objects)
◊ This is often the same as the concept of “JavaBean” although that term
can refer to the formal JavaBean specification
 Spring beans often are classes that implement interfaces
◊ This allows other parts of the application that use them to only see the
interface and allow the ability to provide a different implementation of
the interface in the future.
◊ This is just a Java best practice that Spring makes much easier to
realize
3.2 Spring Containers
 There are several different Spring container implementations
 All implement one of two interfaces:
EVALUATION ONLY
Chapter 3 - Defining and Using Spring Beans
◊ org.springframework.beans.factory.BeanFactory
◊ org.springframework.context.ApplicationContext
 The main difference between the implementations is often how the
container obtains the configuration of Spring beans
Spring Containers
Spring containers are responsible for implementing IoC, wiring, configuration and bean lifecycle
management.
There are two basic types of containers: BeanFactory and ApplicationContext.
3.3 Spring Containers
 BeanFactory
◊ Implementation of Factory design pattern
 Creates many types of beans
◊ Performs dependency injection
◊ Manages life-cycle by calling initialization and destruction methods on
beans
 ApplicationContext
◊ Subinterface of BeanFactory
◊ Provides additional features such as internationalization and event
publishing
◊ Preferred over BeanFactory
Spring Containers
BeanFactory implementations lazily load beans. That is, beans are created and initialized when they
are first needed (i.e. when getBean is first called). An ApplicationContext will preload singleton beans
so they are ready when they are first accessed.
36
EVALUATION ONLY
Chapter 3 - Defining and Using Spring Beans
3.4 Instantiating the Spring Container
 When using a Spring Container you instantiate one of the container
implementations, providing the bean configuration source, and then call
the 'getBean' method to retrieve a bean
ApplicationContext context = new
ClassPathXmlApplicationContext("spring-beans.xml");
// get the bean
CustomerManager manager =
(CustomerManager)context.getBean("customerManager");
// use the bean
manager.updateProfile(customer);
 Popular implementations of ApplicationContext include:
◊ ClassPathXmlApplicationContext – Gets context definitions from an
XML file on the class path
◊ FileSystemXmlApplicationContext – Gets context definitions from an
XML file in the filesystem
◊ XmlWebApplicationContext – Special web application context
Instantiating the Spring Container
In the example above the name of the configuration file, 'spring-beans.xml', is not a special file name.
The file name can be anything and is provided by a constructor argument.
The last line in the example above uses a 'customer' variable that is assumed to be defined in the code.
The line is mainly intended to show that beans are used for application functionality once obtained
from the Spring container.
3.5 Retrieving Spring Beans
 There are various methods available to retrieve beans
Object getBean(String name)
<T> T getBean(String name, Class<T> type)
<T> T getBean(Class<T> type)
◊ Can be used if there is exactly one bean of the type given
 Supplying the class in some way is suggested as the bean returned is
automatically of that type using Java generics
37
EVALUATION ONLY
Chapter 3 - Defining and Using Spring Beans
CustomerManager manager = context.getBean(
"customerManager", CustomerManager.class);
 There are also ways to query information about beans without actually
retrieving any bean
boolean containsBean(String name)
String[] getAliases(String name)
Class<?> getType(String name)
boolean isPrototype(String name)
boolean isSingleton(String name)
boolean isTypeMatch(String name, Class targetType)
3.6 Configuring Spring Beans
 Bean configuration information could come from any source (database,
properties file, etc) but XML is most common
 Spring containers that support XML sources:
◊ XmlBeanFactory
◊ ClassPathXmlApplicationContext
◊ FileSystemXmlApplicationContext
◊ XmlWebApplicationContext
 Although there do exist XML DTD definitions from prior versions of Spring
the current method for Spring XML configuration is using XML schemas
◊ There are also several different XML schemas that can be used for
advanced configuration
 Spring beans are configured as <bean /> elements inside a top-level
<beans /> element.
<beans xmlns="http://www.springframework.org/schema/beans"
...>
<bean ...> ... </bean>
<bean ...> ... </bean>
</beans>
38
EVALUATION ONLY
Chapter 3 - Defining and Using Spring Beans
3.7 <bean> Element
 According to the Spring XML schema there are no required attributes or
child elements of the <bean> element
◊ In reality you will need at least some configuration details so that the
Spring container knows how to create and configure the bean when
requested by the application
 The most common attribute required is the 'class' attribute which indicates
the concrete class which is the bean implementation
◊ This is important because application code often uses an interface that
the bean implements
 Another common attribute is to somehow give the bean a name
◊ This is often done with the 'id' attribute
<bean id="generator"
class="com.webage.bean.BasicProductCodeGenerator"/>
3.8 Naming Beans
 Spring beans must have a unique name which is used to retrieve them
from the Spring container
◊ If a name is not provided for a bean using some other means the
Spring container will generate a unique name automatically
 This is most often provided with the XML 'id' attribute since XML editors
can help validate that the 'id' attribute is unique within the XML
configuration
 The 'name' attribute can also be used to provide a name since some
characters are not allowed in the 'id' attribute
◊ The restrictions for what characters can be placed in the 'id' attribute
are often not that important since using special characters in the bean
name would only make it harder to use the name
 Spring beans can also be provided multiple name using two techniques
◊ Multiple bean names in the 'name' attribute separated by a comma,
semicolon, or white space
39
EVALUATION ONLY
Chapter 3 - Defining and Using Spring Beans
<bean name=”generator,myBean” ... />
◊ Defining a bean <alias> element mapping another name to the bean
<alias name=”generator” alias=”myBeanAlias” />
Naming Beans
It is often best not to rely on the container generating a name for the bean. The exception to this rule is
when the bean is retrieved only based on the type of bean and therefore the bean name is irrelevant.
Notice in the <alias> element above the 'name' attribute is the actual name of the bean as defined
elsewhere and the 'alias' attribute is the new alias that can also be used to retrieve the bean.
3.9 Setting Bean Properties
 If a Spring bean class exposes 'setter' methods those can be used to set
bean properties from the Spring configuration
◊ This is called “setter injection”
 This is done with a child <property> element within the <bean> element
◊ The code:
public class ConversionCalculator {
private double conversionFactor;
public void setConversionFactor(double value) {
conversionFactor = value;
}
◊ Would allow the following Spring configuration:
<bean id=”converter” class=”...ConversionCalculator”>
<property name=”conversionFactor”>
<value>0.465</value>
</property>
OR
<property name=”conversionFactor” value=”0.564”/>
</bean>
Setting Bean Properties
It is critical that the bean class contains a 'setter' method for the property described in the XML
configuration.
40
EVALUATION ONLY
Chapter 3 - Defining and Using Spring Beans
The choice between providing the value as an attribute of the <property> element or as a nested
element is often just preference. Only properties with single values have the choice of either style
though so the nested <value> element might provide a more consistent and only slightly more verbose
way of defining property values.
3.10 Using the Spring XML 'p' Schema
 Another way to set property values is to use the Spring 'p' schema to
define the property value directly in the <bean> element as an attribute
with the name of the property being the name of the attribute
<bean id=”converter” class=”...ConversionCalculator”
p:conversionFactor=”0.456” />
◊ Using this method there is no nested <property> element
 This requires adding the 'p' schema to the XML namespaces of the
configuration file
<beans ... // other XML namespaces
xmlns:p="http://www.springframework.org/schema/p" >
 One downside of this approach is that Spring XML configuration editors in
development IDEs will likely not be able to provide a way to easily set the
property name and value
◊ A nested <property> element would provide editor support like below
Using the Spring XML 'p' Schema
If you were to use an "inline" property with the 'p' schema syntax and a nested <property> element this
would throw an exception as it is not allowed.
3.11 Creating Beans with a Constructor
 An alternate way to define Spring beans is to provide constructor
arguments that will be used to call a constructor of the bean class
◊ The arguments are supplied by nested <constructor-arg> elements
41
EVALUATION ONLY
Chapter 3 - Defining and Using Spring Beans
instead of <property> elements
◊ There can be multiple arguments that will be resolved by position
 This constructor:
public Product(String name, double price) { ... }
 Could be configured using:
<bean ...>
<constructor-arg>
<value>Barbie doll</value>
</constructor-arg>
<constructor-arg>
<value>12.99</value>
</constructor-arg>
OR
<constructor-arg value="Barbie doll"/>
<constructor-arg value="12.99"/>
</bean>
Creating Beans with a Constructor
Note that when no <constructor-arg> elements are used the class must have a "default" constructor with
no arguments as that will be the constructor called by Spring before setting properties.
3.12 Resolving Constructor Ambiguity
 There are some situations where Spring may not be able to resolve the
proper constructor to invoke
◊ This can cause either exceptions or unintended behavior
◊ You can use different techniques to prevent this
 You can supply an 'index' to indicate the position of the argument
<constructor-arg index="1" value="12.99"/>
<constructor-arg index="0" value="Barbie doll"/>
 You can specify the type of the argument using the 'type' attribute
◊ The default type of an argument will be String unless specified
◊ Specifying the type is often required if more than one constructor exists
42
EVALUATION ONLY
Chapter 3 - Defining and Using Spring Beans
with the specified number of arguments
◊ When using 'type' the order in the configuration does not have to match
the declared order of arguments in the constructor
<constructor-arg type="java.lang.String"
value="Barbie doll"/>
<constructor-arg type="double" value="12.99"/>
Resolving Constructor Ambiguity
Indicating the index or a constructor argument is obviously not usually of much use since you can often
simply rearrange the arguments in the configuration file.
When using the 'type' attribute you supply the fully qualified Java class or the primitive type of the
argument.
There are times when you might need to use both the 'type' and 'index' attributes to correctly match the
intended constructor. This might be needed if the class had the following three constructors.
public Product(String name, double price) { ... }
public Product(double price, String description) { ... }
public Product(String name, String description) { ... }
Without any extra attributes the constructor arguments would likely be taken as Strings and the third
constructor would be invoked. By supplying only the 'type' attributes either of the first two
constructors might be called. By indicating 'type' and 'index' the desired constructor could be invoked.
3.13 Setting Properties vs. Invoking Constructors
 Since both mechanisms can be used to define Spring beans the question
often arises "Is it better to set properties or invoke constructors?"
 There are pros and cons of both approaches and the choice often comes
down to the situation or the preferences and conventions of developers
 Using Constructors - Pros
◊ Providing constructors is one way to indicate required properties for
different ways of object instantiation
◊ Constructors guarantee an object is never in an "unconfigured" state
 Using Constructors - Cons
◊ Working with constructor arguments can be more difficult because they
43
EVALUATION ONLY
Chapter 3 - Defining and Using Spring Beans
are not referred to by name but by type and position
 Setting properties – Pros
◊ Easier to configure beans in various ways
 Setting properties – Cons
◊ Sometimes adding 'setter' methods just for configuration and no other
purpose doesn't make sense
Setting Properties vs. Invoking Constructors
Sometimes the choice between the two is made for you if you can't modify the code.
Having code that has constructors for providing initial values rather than having a default constructor
and 'setter' methods makes more "sense" in the code.
With Spring 3 there are various ways to indicate a property is required, even if you are not using
constructors so this advantage is less of an argument for using constructors.
Spring 3 also has other ways to initialize a property, even without a 'setter' method or using a
constructor using annotations.
3.14 Bean Scope
 Spring containers can create beans at one of several “scopes”
◊ Singleton – available in all Spring applications
◊ Prototype – available in all Spring applications
◊ Request – only for web-based Spring applications
◊ Session – only for web-based Spring applications
◊ Global Session – only for portlet-based Spring applications
 Bean scope is set using the 'scope' attribute
◊ Default is singleton
<bean id=”converter” class=”...ConversionCalculator”
scope="prototype">
44
EVALUATION ONLY
Chapter 3 - Defining and Using Spring Beans
3.15 Effect of Bean Scope on Instances
 Singleton vs. prototype
◊ Singleton will result in one bean for the container
 Every future request for the same bean name will return the same
instance
 The Spring container retains references to singleton instances so
they can be returned in the future
 Singleton scope is often used for stateless components
 If using an ApplicationContext singleton beans are often initialized
when the container starts up
◊ Prototype acts as a template for new beans
 A new instance is created and initialized every time the bean is
retrieved from the container
 The Spring container retains no reference to the instance since it will
not be required once the bean is created and returned to the code
getting the bean
 Prototype scope is often used for stateful components
 Other scopes
◊ The other scopes in web/portlet applications are first searched to see if
the bean already exists and is then created and stored in that scope if it
doesn't exist
3.16 Summary
 One of the core features of Spring is to provide a container that can create
and configure Spring "beans" based on configuration
 Spring bean configuration can set properties of the bean with various ways
to provide property configuration
 Spring beans can also be created by invoking constructors
 Spring bean scope can have important impact on application behavior
45
EVALUATION ONLY