Sunteți pe pagina 1din 780

Reference Documentation

(Work in progress)

Reference Documentation (Work in progress) 3.0.0.RC1 Copyright © 2004-2009 Rod Johnson, Juergen Hoeller, Keith Donald,

3.0.0.RC1

Copyright © 2004-2009 Rod Johnson, Juergen Hoeller, Keith Donald, Colin Sampaleanu, Rob Harrop, Alef Arendsen, Thomas Risberg, Darren Davison, Dmitriy Kopylenko, Mark Pollack, Thierry Templier, Erwin Vervaet, Portia Tung, Ben Hale, Adrian Colyer, John Lewis, Costin Leau, Mark Fisher, Sam Brannen, Ramnivas Laddad, Arjen Poutsma, Chris Beams, Tareq Abed Rabbo

Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.

Spring Framework

Table of Contents

I. Overview of Spring Framework

1

1.

Introduction to Spring Framework

2

1.1. Dependency Injection and Inversion of Control

2

1.2. Modules

3

Core

Container

3

Data

Access/Integration

4

Web

4

AOP and Instrumentation

5

Test

5

1.3. Usage scenarios

5

II. What's New in Spring 3.0

 

10

2.

New Features and Enhancements in Spring 3.0

11

2.1. Java 5

11

2.2. Improved documentation

11

2.3. New getting started tutorial

11

2.4. New module organization and build system

12

2.5. Overview of new features

13

Core APIs updated for Java 5

13

Spring Expression Language

14

The Inversion of Control (IoC) container

14

Java based bean metadata

14

Defining bean metadata within components

16

General purpose type conversion system and UI field formatting system

16

The Data Tier

16

The Web Tier

16

Comprehensive REST support

16

@MVC additions

16

Declarative model validation

17

Early support for Java EE 6

17

Support for embedded databases

17

III. Core Technologies

18

3.

The IoC container

19

3.1. Introduction to the Spring IoC container and beans

19

3.2. Container overview

19

Configuration metadata

20

Instantiating a container

22

Composing XML-based configuration metadata

23

Using the container

24

3.3. Bean overview

24

Naming beans

26

Spring Framework

Aliasing a bean outside the bean definition

26

Instantiating beans

27

Instantiation with a constructor

28

Instantiation with a static factory method

28

Instantiation using an instance factory method

29

3.4. Dependencies

29

Dependency injection

29

Constructor-based dependency injection

30

Setter-based dependency injection

32

Dependency resolution process

33

Examples of dependency injection

34

Dependencies and configuration in detail

36

Straight values (primitives, Strings, and so on)

36

References to other beans (collaborators)

38

Inner beans

39

Collections

39

Null and empty string values

42

XML shortcut with the p-namespace

42

Compound property names

43

Using depends-on

43

Lazy-initialized beans

44

Autowiring collaborators

45

Limitations and disadvantages of autowiring

46

Excluding a bean from autowiring

47

Checking for dependencies

47

Method injection

48

Lookup method injection

49

Arbitrary method replacement

50

3.5. Bean

scopes

52

The singleton scope

53

The prototype scope

54

Singleton beans with prototype-bean dependencies

55

Request, session, and global session scopes

55

Initial web configuration

55

Request scope

56

Session scope

56

Global session scope

57

Scoped beans as dependencies

57

Custom scopes

59

Creating a custom scope

60

Using a custom scope

60

3.6. Customizing the nature of a bean

62

Lifecycle callbacks

62

Initialization callbacks

62

Destruction callbacks

63

Spring Framework

Default initialization and destroy methods

63

Combining lifecycle mechanisms

65

Shutting down the Spring IoC container gracefully in non-web applications 65

ApplicationContextAware and BeanNameAware

66

3.7. Bean definition inheritance

67

3.8. Container extension points

68

Customizing beans using the BeanPostProcessor Interface

69

Example: Hello World, BeanPostProcessor-style

70

Example: The RequiredAnnotationBeanPostProcessor

71

Customizing configuration metadata with BeanFactoryPostProcessor interface

71

Example: the PropertyPlaceholderConfigurer

72

Example: the PropertyOverrideConfigurer

74

Customizing instantiation logic with the FactoryBean Interface

75

3.9. Annotation-based container configuration

76

@Required

76

@Autowired and @Inject

77

Fine-tuning annotation-based autowiring with qualifiers

79

CustomAutowireConfigurer

85

@Resource

85

@PostConstruct and @PreDestroy

87

3.10. Classpath scanning and managed components

87

@Component and further stereotype annotations

88

Automatically detecting classes and registering bean definitions

88

Using filters to customize scanning

89

Defining bean metadata within components

90

Naming autodetected components

92

Providing a scope for autodetected components

92

Providing qualifier metadata with annotations

93

3.11. Java-based container configuration

94

Using the @Configuration annotation

94

Using the @Bean annotation

95

Declaring a bean

95

Injecting dependencies

95

Receiving lifecycle callbacks

96

Specifying bean scope

97

Customizing bean naming

98

3.12. Registering a LoadTimeWeaver

99

3.13. Additional Capabilities of the ApplicationContext

99

Internationalization using MessageSource

99

Standard and Custom Events

102

Convenient access to low-level resources

105

Convenient ApplicationContext instantiation for web applications

105

Deploying a Spring ApplicationContext as a J2EE RAR file

106

3.14. The BeanFactory

107

BeanFactory or ApplicationContext?

107

Spring Framework

Glue code and the evil singleton

109

4. Resources

110

4.1. Introduction

110

4.2. The Resource interface

110

4.3. Built-in Resource implementations

111

UrlResource

111

ClassPathResource

112

FileSystemResource

112

ServletContextResource

112

InputStreamResource

112

ByteArrayResource

113

4.4. The ResourceLoader

113

4.5. The ResourceLoaderAware interface

114

4.6. Resources as dependencies

115

4.7. Application contexts and Resource paths

115

Constructing application contexts

115

Constructing ClassPathXmlApplicationContext instances - shortcuts

116

Wildcards in application context constructor resource paths

117

Ant-style Patterns

117

The classpath*: prefix

118

Other notes relating to wildcards

118

FileSystemResource caveats

119

5. Validation, Data-binding, the BeanWrapper, and PropertyEditors

121

5.1. Introduction

121

5.2. Validation using Spring's Validator interface

121

5.3. Resolving codes to error messages

123

5.4. Bean manipulation and the BeanWrapper

123

Setting and getting basic and nested properties

124

Built-in PropertyEditor implementations

125

Registering additional custom PropertyEditors

128

5.5. Spring 3 Type Conversion

131

Converter SPI

131

ConverterFactory

132

ConversionService API

133

Configuring a ConversionService

133

Using a ConversionService programatically

134

5.6. Spring 3 UI Field Formatting

134

Formatter SPI

135

@Formatted

136

Custom Format Annotations

136

AnnotationFormatterFactory

137

FormatterRegistry SPI

138

Configuring a FormatterRegistry

138

Registering field-specific Formatters

139

5.7. Spring 3 Validation

139

Spring Framework

 

Overview of the JSR-303 Bean Validation API

140

Configuring a Bean Validation Implementation

140

Injecting a Validator

141

Configuring Custom Constraints

141

Additional Configuration Options

142

Configuring a DataBinder

142

Spring MVC 3 Validation

143

Triggering @Controller Input Validation

143

Configuring a Validator for use by Spring MVC

143

Configuring a JSR-303 Validator for use by Spring MVC

144

6. Spring Expression Language (SpEL)

145

6.1. Introduction

145

6.2. Feature Overview

145

6.3. Expression Evaluation using Spring's Expression Interface

146

The EvaluationContext interface

148

Type Conversion

148

6.4. Expression support for defining bean definitions

149

XML based configuration

149

Annotation-based configuration

150

6.5. Language Reference

151

Literal expressions

151

Properties, Arrays, Lists, Maps, Indexers

151

Methods

152

Operators

153

Relational operators

153

Logical operators

153

Mathematical operators

154

Assignment

154

Types

155

Constructors

155

Variables

155

The #this variable

156

Functions

156

Ternary Operator (If-Then-Else)

156

The Elvis Operator

157

Safe Navigation operator

158

Collection Selection

158

Collection Projection

159

Expression templating

159

6.6. Classes used in the examples

159

7. Aspect Oriented Programming with Spring

163

7.1.

Introduction

163

AOP concepts

163

Spring AOP capabilities and goals

165

AOP Proxies

166

Spring Framework

7.2. @AspectJ support

167

Enabling @AspectJ Support

167

Declaring an aspect

167

Declaring a pointcut

168

Supported Pointcut Designators

169

Combining pointcut expressions

170

Sharing common pointcut definitions

171

Examples

172

Declaring advice

175

Before advice

175

After returning advice

175

After throwing advice

176

After (finally) advice

177

Around advice

177

Advice parameters

178

Advice ordering

181

Introductions

182

Aspect instantiation models

182

Example

183

7.3. Schema-based AOP support

185

Declaring an aspect

185

Declaring a pointcut

186

Declaring advice

187

Before advice

187

After returning advice

188

After throwing advice

189

After (finally) advice

189

Around advice

190

Advice parameters

190

Advice ordering

192

Introductions

192

Aspect instantiation models

193

Advisors

193

Example

194

7.4. Choosing which AOP declaration style to use

196

Spring AOP or full AspectJ?

196

@AspectJ or XML for Spring AOP?

196

7.5. Mixing aspect types

197

7.6. Proxying mechanisms

197

Understanding AOP proxies

198

7.7. Programmatic creation of @AspectJ Proxies

201

7.8. Using AspectJ with Spring applications

201

Using AspectJ to dependency inject domain objects with Spring

202

Unit testing @Configurable objects

204

Working with multiple application contexts

204

Spring Framework

 

Other Spring aspects for AspectJ

205

Configuring AspectJ aspects using Spring IoC

206

Load-time weaving with AspectJ in the Spring Framework

207

A first example

207

Aspects

210

'META-INF/aop.xml'

210

Required libraries (JARS)

211

Spring configuration

211

Environment-specific configuration

213

7.9.

Further Resources

214

8. Spring AOP APIs

216

8.1. Introduction

216

8.2. Pointcut API in Spring

216

Concepts

216

Operations on pointcuts

217

AspectJ expression pointcuts

217

Convenience pointcut implementations

217

Static pointcuts

218

Dynamic pointcuts

219

Pointcut superclasses

219

Custom pointcuts

220

8.3. Advice API in Spring

220

Advice lifecycles

220

Advice types in Spring

220

Interception around advice

221

Before advice

221

Throws advice

222

After Returning advice

223

Introduction advice

224

8.4. Advisor API in Spring

227

8.5. Using the ProxyFactoryBean to create AOP proxies

227

Basics

227

JavaBean properties

228

JDK- and CGLIB-based proxies

229

Proxying interfaces

230

Proxying classes

232

Using 'global' advisors

232

8.6. Concise proxy definitions

233

8.7. Creating AOP proxies programmatically with the ProxyFactory

234

8.8. Manipulating advised objects

234

8.9. Using the "autoproxy" facility

236

Autoproxy bean definitions

236

BeanNameAutoProxyCreator

236

DefaultAdvisorAutoProxyCreator

237

AbstractAdvisorAutoProxyCreator

238

Spring Framework

 

Using metadata-driven auto-proxying

238

8.10.

Using TargetSources

241

Hot swappable target sources

241

Pooling target sources

242

Prototype target sources

243

ThreadLocal target sources

243

8.11.

Defining new Advice types

244

8.12.

Further resources

244

9. Testing

246

9.1. Introduction to testing

246

9.2. Unit testing

246

Mock objects

246

JNDI

246

Servlet API

246

Portlet API

247

Unit testing support classes

247

General utilities

247

Spring MVC

247

9.3. Integration testing

247

Overview

247

Goals of integration testing

248

Context management and caching

248

 

Dependency Injection of test fixtures

249

Transaction management

249

Support classes for integration testing

250

JDBC testing support

250

Annotations

250

Spring TestContext Framework

256

Key abstractions

256

Context management and caching

257

Dependency Injection of test fixtures

259

Transaction management

262

TestContext support classes

264

PetClinic example

267

9.4. Further Resources

269

IV. Data Access

270

10. Transaction Management

271

10.1. Introduction to Spring Framework transaction management

271

10.2. Advantages of the Spring Framework's transaction support model

271

Global transactions

272

Local transactions

272

 

Spring Framework's consistent programming model

272

10.3. Understanding the Spring Framework transaction abstraction

273

10.4. Synchronizing resources with transactions

277

High-level synchronization approach

277

Spring Framework

Low-level synchronization approach

277

TransactionAwareDataSourceProxy

278

10.5. Declarative transaction management

278

Understanding the Spring Framework's declarative transaction implementation 280

Example of declarative transaction implementation

281

Rolling back a declarative transaction

285

Configuring different transactional semantics for different beans

286

<tx:advice/> settings

288

Using @Transactional

289

@Transactional settings

293

Transaction propagation

294

Required

294

RequiresNew

295

Nested

296

Advising transactional operations

296

Using @Transactional with AspectJ

299

10.6. Programmatic transaction management

300

Using the TransactionTemplate

300

Specifying transaction settings

301

Using the PlatformTransactionManager

302

10.7. Choosing between programmatic and declarative transaction management

303

10.8. Application server-specific integration

303

IBM WebSphere

304

BEA WebLogic Server

304

Oracle OC4J

304

10.9. Solutions to common problems

304

Use of the wrong transaction manager for a specific DataSource

304

10.10. Further Resources

304

11. DAO support

306

11.1. Introduction

306

11.2. Consistent exception hierarchy

306

11.3. Annotations used for configuring DAO or Repository classes

307

12. Data access with JDBC

309

12.1. Introduction to Spring Framework JDBC

309

Choosing an approach for JDBC database access

309

Package hierarchy

310

12.2. Using the JDBC core classes to control basic JDBC processing and error handling

 

311

JdbcTemplate

311

Examples of JdbcTemplate class usage

312

JdbcTemplate best practices

314

NamedParameterJdbcTemplate

315

SimpleJdbcTemplate

317

SQLExceptionTranslator

319

Executing statements

320

Spring Framework

Running queries

321

Updating the database

322

Retrieving auto-generated keys

322

12.3. Controlling database connections

323

DataSource

323

DataSourceUtils

324

SmartDataSource

324

AbstractDataSource

325

SingleConnectionDataSource

325

DriverManagerDataSource

325

TransactionAwareDataSourceProxy

325

DataSourceTransactionManager

326

NativeJdbcExtractor

326

12.4. JDBC batch operations

327

Batch operations with the JdbcTemplate

327

Batch operations with the SimpleJdbcTemplate

328

12.5. Simplifying JDBC operations with the SimpleJdbc classes

329

Inserting data using SimpleJdbcInsert

329

Retrieving auto-generated keys using SimpleJdbcInsert

330

Specifying columns for a SimpleJdbcInsert

330

Using SqlParameterSource to provide parameter values

331

Calling a stored procedure with SimpleJdbcCall

332

Explicitly declaring parameters to use for a SimpleJdbcCall

334

How to define SqlParameters

335

Calling a stored function using SimpleJdbcCall

335

Returning ResultSet/REF Cursor from a SimpleJdbcCall

336

12.6. Modeling JDBC operations as Java objects

337

SqlQuery

338

MappingSqlQuery

338

SqlUpdate

339

StoredProcedure

340

12.7. Common problems with parameter and data value handling

343

Providing SQL type information for parameters

343

Handling BLOB and CLOB objects

343

Passing in lists of values for IN clause

345

Handling complex types for stored procedure calls

345

12.8. Embedded database support

347

Why use an embedded database?

347

Creating an embedded database instance using Spring XML

347

Creating an embedded database instance programmatically

347

Extending the embedded database support

347

Using HSQL

348

Using H2

348

Using Derby

348

Testing data access logic with an embedded database

348

Spring Framework

13. Object Relational Mapping (ORM) Data Access

350

13.1. Introduction to ORM with Spring

350

13.2. General ORM integration considerations

351

Resource and transaction management

351

Exception translation

352

13.3. Hibernate

353

SessionFactory setup in a Spring container

353

Implementing DAOs based on plain Hibernate 3 API

354

Declarative transaction demarcation

355

Programmatic transaction demarcation

357

Transaction management strategies

358

Comparing container-managed and locally defined resources

360

Spurious application server warnings with Hibernate

361

13.4. JDO

362

PersistenceManagerFactory setup

362

Implementing DAOs based on the plain JDO API

363

Transaction management

365

JdoDialect

366

13.5. JPA

367

Three options for JPA setup in a Spring environment

367

LocalEntityManagerFactoryBean

367

Obtaining an EntityManagerFactory from JNDI

368

LocalContainerEntityManagerFactoryBean

368

Dealing with multiple persistence units

372

Implementing DAOs based on plain JPA

373

Transaction Management

375

JpaDialect

376

13.6. iBATIS SQL Maps

377

Setting up the SqlMapClient

377

Using SqlMapClientTemplate and SqlMapClientDaoSupport

379

Implementing DAOs based on plain iBATIS API

379

14. Marshalling XML using O/X Mappers

381

14.1. Introduction

381

14.2. Marshaller and Unmarshaller

381

Marshaller

381

Unmarshaller

382

XmlMappingException

383

14.3. Using Marshaller and Unmarshaller

383

14.4. XML Schema-based Configuration

385

14.5. JAXB

386

Jaxb2Marshaller

386

XML Schema-based Configuration

386

14.6. Castor

387

CastorMarshaller

387

Mapping

387

Spring Framework

14.7. XMLBeans

388

XmlBeansMarshaller

388

XML Schema-based Configuration

388

14.8. JiBX

389

JibxMarshaller

389

XML Schema-based Configuration

389

14.9. XStream

390

XStreamMarshaller

390

V. The Web

391

15. Web MVC framework

392

15.1. Introduction to Spring Web MVC framework

392

Features of Spring Web MVC

393

Pluggability of other MVC implementations

394

15.2. The DispatcherServlet

394

15.3. Implementing Controllers

399

Defining a controller with @Controller

400

Mapping requests with @RequestMapping

400

URI Templates

402

Advanced @RequestMapping options

403

Supported handler method arguments and return types

404

Binding request parameters to method parameters with @RequestParam

407

Mapping the request body with the @RequestBody annotation

407

Mapping the response body with the @ResponseBody annotation

408

Providing a link to data from the model with @ModelAttribute

408

Specifying attributes to store in a session with @SessionAttributes

409

Mapping cookie values with the @CookieValue annotation

410

Mapping request header attributes with the @RequestHeader annotation

410

Customizing WebDataBinder initialization

411

15.4. Handler mappings

412

Intercepting requests - the HandlerInterceptor interface

413

15.5. Resolving views

414

Resolving views with the ViewResolver interface

414

Chaining ViewResolvers

416

Redirecting to views

417

RedirectView

417

The redirect: prefix

418

The forward: prefix

418

ContentNegotiatingViewResolver

418

15.6. Using locales

421

AcceptHeaderLocaleResolver

421

CookieLocaleResolver

421

SessionLocaleResolver

422

LocaleChangeInterceptor

422

15.7. Using themes

422

Overview of themes

422

Spring Framework

Defining themes

423

Theme resolvers

423

15.8. Spring's multipart (fileupload) support

424

Introduction

424

Using the MultipartResolver

424

Handling a file upload in a form

425

15.9. Handling exceptions

428

HandlerExceptionResolver

428

@ExceptionHandler

428

15.10.

Convention over configuration support

429

The Controller ControllerClassNameHandlerMapping

429

The Model ModelMap (ModelAndView)

430

The View - RequestToViewNameTranslator

432

15.11. ETag support

433

15.12. More Spring Web MVC Resources

434

16. View technologies

435

16.1. Introduction

435

16.2. JSP & JSTL

435

View resolvers

435

'Plain-old' JSPs versus JSTL

436

Additional tags facilitating development

436

Using Spring's form tag library

436

Configuration

436

The form tag

436

The input tag

438

The checkbox tag

438

The checkboxes tag

440

The radiobutton tag

440

The radiobuttons tag

440

The password tag

441

The select tag

441

The option tag

442

The options tag

442

The textarea tag

443

The hidden tag

443

The errors tag

443

HTTP Method Conversion

445

16.3. Tiles

446

Dependencies

446

How to integrate Tiles

447

UrlBasedViewResolver

447

ResourceBundleViewResolver

447

SimpleSpringPreparerFactory and SpringBeanPreparerFactory

448

16.4. Velocity & FreeMarker

449

Dependencies

449

Spring Framework

Context configuration

449

Creating templates

450

Advanced configuration

450

velocity.properties

450

FreeMarker

451

Bind support and form handling

451

The bind macros

451

Simple binding

452

Form input generation macros

453

HTML escaping and XHTML compliance

457

16.5. XSLT

457

My First Words

458

Bean definitions

458

Standard MVC controller code

458

Convert the model data to XML

458

Defining the view properties

459

Document transformation

460

Summary

460

16.6. Document views (PDF/Excel)

461

Introduction

461

Configuration and setup

461

Document view definitions

461

Controller code

461

Subclassing for Excel views

462

Subclassing for PDF views

463

16.7. JasperReports

463

Dependencies

464

Configuration

464

Configuring the ViewResolver

464

Configuring the Views

464

About Report Files

465

Using JasperReportsMultiFormatView

465

Populating the ModelAndView

466

Working with Sub-Reports

467

Configuring Sub-Report Files

467

Configuring Sub-Report Data Sources

468

Configuring Exporter Parameters

468

16.8. Feed Views

469

16.9. XML Marshalling View

470

17. Integrating with other web frameworks

471

17.1. Introduction

471

17.2. Common configuration

472

17.3. JavaServer Faces 1.1 and 1.2

473

DelegatingVariableResolver (JSF 1.1/1.2)

474

SpringBeanVariableResolver (JSF 1.1/1.2)

474

Spring Framework

SpringBeanFacesELResolver (JSF 1.2+)

475

FacesContextUtils

475

17.4. Apache Struts 1.x and 2.x

475

ContextLoaderPlugin

476

DelegatingRequestProcessor

477

DelegatingActionProxy

477

ActionSupport Classes

478

17.5. WebWork 2.x

478

17.6. Tapestry 3.x and 4.x

479

Injecting Spring-managed beans

480

Dependency Injecting Spring Beans into Tapestry pages

481

Component definition files

482

Adding abstract accessors

483

Dependency Injecting Spring Beans into Tapestry pages - Tapestry 4.x style

 

485

17.7. Further Resources

486

18. Portlet MVC Framework

488

18.1. Introduction

488

Controllers - The C in MVC

489

Views - The V in MVC

489

Web-scoped beans

490

18.2. The DispatcherPortlet

490

18.3. The ViewRendererServlet

492

18.4. Controllers

493

AbstractController and PortletContentGenerator

494

Other simple controllers

495

Command Controllers

495

PortletWrappingController

496

18.5. Handler mappings

497

PortletModeHandlerMapping

498

ParameterHandlerMapping

498

PortletModeParameterHandlerMapping

498

Adding HandlerInterceptors

499

HandlerInterceptorAdapter

500

ParameterMappingInterceptor

500

18.6. Views and resolving them

500

18.7. Multipart (file upload) support

501

Using the PortletMultipartResolver

501

Handling a file upload in a form

502

18.8. Handling exceptions

505

18.9. Annotation-based controller configuration

505

Setting up the dispatcher for annotation support

505

Defining a controller with @Controller

506

Mapping requests with @RequestMapping

506

Supported handler method arguments

508

Spring Framework

Binding request parameters to method parameters with @RequestParam

509

Providing a link to data from the model with @ModelAttribute

510

Specifying attributes to store in a Session with @SessionAttributes

511

Customizing WebDataBinder initialization

511

Customizing data binding with @InitBinder

511

Configuring a custom WebBindingInitializer

512

18.10. Portlet application deployment

512

VI. Integration

513

19. Remoting and web services using Spring

514

19.1. Introduction

514

19.2. Exposing services using RMI

515

Exporting the service using the RmiServiceExporter

515

Linking in the service at the client

516

19.3. Using Hessian or Burlap to remotely call services via HTTP

517

Wiring up the DispatcherServlet for Hessian and

517

Exposing your beans by using the HessianServiceExporter

517

Linking in the service on the client

518

Using Burlap

518

Applying HTTP basic authentication to a service exposed through Hessian or Burlap

519

19.4. Exposing services using HTTP invokers

519

Exposing the service object

519

Linking in the service at the client

520

19.5. Web services

521

Exposing servlet-based web services using JAX-RPC

522

Accessing web services using JAX-RPC

522

Registering JAX-RPC Bean Mappings

524

Registering your own JAX-RPC Handler

525

Exposing servlet-based web services using JAX-WS

525

Exporting standalone web services using JAX-WS

526

Exporting web services using the JAX-WS RI's Spring support

527

Accessing web services using JAX-WS

527

Exposing web services using XFire

528

19.6. JMS

529

Server-side configuration

530

Client-side configuration

531

19.7. Auto-detection is not implemented for remote interfaces

531

19.8. Considerations when choosing a technology

532

19.9. Accessing RESTful services on the Client

532

RestTemplate

533

HTTP Message Conversion

535

StringHttpMessageConverter

536

FormHttpMessageConverter

536

ByteArrayMessageConverter

536

MarshallingHttpMessageConverter

536

Spring Framework

SourceHttpMessageConverter

536

BufferedImageHttpMessageConverter

536

20. Enterprise JavaBeans (EJB) integration

538

20.1. Introduction

538

20.2. Accessing EJBs

538

Concepts

538

Accessing local SLSBs

539

Accessing remote SLSBs

540

Accessing EJB 2.x SLSBs versus EJB 3 SLSBs

541

20.3. Using Spring's EJB implementation support classes

541

EJB 2.x base classes

541

EJB 3 injection interceptor

543

21. JMS (Java Message Service)

545

21.1. Introduction

545

21.2. Using Spring JMS

545

JmsTemplate

545

Connections

546

Caching Messaging Resources

547

SingleConnectionFactory

547

CachingConnectionFactory

547

Destination Management

547

Message Listener Containers

548

SimpleMessageListenerContainer

549

DefaultMessageListenerContainer

549

ServerSessionMessageListenerContainer

549

Transaction management

549

21.3. Sending a Message

550

Using Message Converters

551

SessionCallback and ProducerCallback

552

21.4. Receiving a message

552

Synchronous Reception

552

Asynchronous Reception - Message-Driven POJOs

552

The SessionAwareMessageListener interface

553

The MessageListenerAdapter

554

Processing messages within transactions

555

21.5. Support for JCA Message Endpoints

556

21.6. JMS Namespace Support

558

22. JMX

563

22.1. Introduction

563

22.2. Exporting your beans to JMX

563

Creating an MBeanServer

564

Reusing an existing MBeanServer

565

Lazy-initialized MBeans

566

Automatic registration of MBeans

566

Controlling the registration behavior

566

Spring Framework

22.3. Controlling the management interface of your beans

568

The MBeanInfoAssembler Interface

568

Using source-Level metadata

568

Using JDK 5.0 Annotations

571

Source-Level Metadata Types

572

The AutodetectCapableMBeanInfoAssembler interface

574

 

Defining management interfaces using Java interfaces

574

Using MethodNameBasedMBeanInfoAssembler

576

22.4. Controlling the ObjectNames for your beans

576

Reading ObjectNames from Properties

577

Using the MetadataNamingStrategy

577

The <context:mbean-export/> element

578

22.5. JSR-160 Connectors

579

Server-side Connectors

579

Client-side Connectors

580

JMX over Burlap/Hessian/SOAP

580

22.6. Accessing MBeans via Proxies

580

22.7. Notifications

581

Registering Listeners for Notifications

581

Publishing Notifications

584

22.8. Further Resources

586

23. JCA CCI

587

23.1.

Introduction

587

23.2.

Configuring CCI

587

Connector configuration

587

ConnectionFactory configuration in Spring

588

Configuring CCI connections

589

Using a single CCI connection

589

23.3.

Using Spring's CCI access support

590

Record conversion

590

The CciTemplate

591

DAO support

592

Automatic output record generation

593

Summary

593

Using a CCI Connection and Interaction directly

594

Example for CciTemplate usage

595

23.4.

Modeling CCI access as operation objects

597

MappingRecordOperation

597

MappingCommAreaOperation

598

Automatic output record generation

598

Summary

598

Example for MappingRecordOperation usage

599

Example for MappingCommAreaOperation usage

601

23.5.

Transactions

602

24. Email

604

Spring Framework

24.1. Introduction

604

24.2. Usage

604

Basic MailSender and SimpleMailMessage usage

605

Using the JavaMailSender and the MimeMessagePreparator

606

24.3. Using the JavaMail MimeMessageHelper

607

Sending attachments and inline resources

607

Attachments

607

Inline resources

608

Creating email content using a templating library

608

A Velocity-based example

609

25. Task Execution and Scheduling

611

25.1. Introduction

611

25.2. The Spring TaskExecutor abstraction

611

TaskExecutor types

611

Using a TaskExecutor

613

25.3. The Spring TaskScheduler abstraction

614

The Trigger interface

614

Trigger implementations

615

TaskScheduler implementations

615

25.4. The Task Namespace

616

The 'scheduler' element

616

The 'executor' element

616

The 'scheduled-tasks' element

617

25.5. Annotation Support for Scheduling and Asynchronous Execution

618

The @Scheduled Annotation

618

The @Async Annotation

618

The <annotation-driven> Element

619

25.6. Using the OpenSymphony Quartz Scheduler

619

Using the JobDetailBean

619

Using the MethodInvokingJobDetailFactoryBean

620

Wiring up jobs using triggers and the SchedulerFactoryBean

621

25.7. Using JDK Timer support

622

Creating custom timers

622

Using the MethodInvokingTimerTaskFactoryBean

623

Wrapping up: setting up the tasks using the TimerFactoryBean

623

26. Dynamic language support

625

26.1. Introduction

625

26.2. A first example

625

26.3. Defining beans that are backed by dynamic languages

627

Common concepts

627

The <lang:language/> element

628

Refreshable beans

628

Inline dynamic language source files

631

Understanding Constructor Injection in the context of dynamic-language-backed beans

631

Spring Framework

JRuby beans

632

Groovy beans

634

Customising Groovy objects via a callback

636

BeanShell beans

637

26.4. Scenarios

638

Scripted Spring MVC Controllers

638

Scripted Validators

639

26.5. Bits and bobs

640

AOP - advising scripted beans

640

Scoping

640

26.6. Further Resources

641

27. Annotations and Source Level Metadata Support

642

27.1. Introduction

642

27.2. Annotations

642

@Required

642

Other @Annotations in Spring

644

VII. Appendices

645

A. Classic Spring Usage

646

A.1. Classic ORM usage

646

Hibernate

646

The HibernateTemplate

646

Implementing Spring-based DAOs without callbacks

647

JDO

648

JdoTemplate and JdoDaoSupport

648

JPA

649

JpaTemplate and JpaDaoSupport

649

A.2. Classic Spring MVC

650

A.3. JMS Usage

651

JmsTemplate

651

Asynchronous Message Reception

651

Connections

652

Transaction Management

652

B. Classic Spring AOP Usage

653

B.1.

653

B.2. Pointcut API in Spring

653

Concepts

653

Operations on pointcuts

654

AspectJ expression pointcuts

654

Convenience pointcut implementations

654

Static pointcuts

654

Dynamic pointcuts

656

Pointcut superclasses

656

Custom pointcuts

657

B.3. Advice API in Spring

657

Advice lifecycles

657

Spring Framework

Advice types in Spring

657

Interception around advice

657

Before advice

658

Throws advice

659

After Returning advice

660

Introduction advice

661

B.4. Advisor API in Spring

664

B.5. Using the ProxyFactoryBean to create AOP proxies

664

Basics

664

JavaBean properties

665

JDK- and CGLIB-based proxies

666

Proxying interfaces

667

Proxying classes

669

Using 'global' advisors

669

B.6. Concise proxy definitions

670

B.7. Creating AOP proxies programmatically with the ProxyFactory

671

B.8. Manipulating advised objects

671

B.9. Using the "autoproxy" facility

673

Autoproxy bean definitions

673

BeanNameAutoProxyCreator

673

DefaultAdvisorAutoProxyCreator

674

AbstractAdvisorAutoProxyCreator

675

Using metadata-driven auto-proxying

675

B.10. Using TargetSources

678

Hot swappable target sources

678

Pooling target sources

679

Prototype target sources

680

ThreadLocal target sources

680

B.11. Defining new Advice types

681

B.12. Further resources

681

C. XML Schema-based configuration

683

C.1. Introduction

683

C.2. XML Schema-based configuration

684

Referencing the schemas

684

The util schema

685

<util:constant/>

685

<util:property-path/>

687

<util:properties/>

688

<util:list/>

689

<util:map/>

690

<util:set/>

690

The jee schema

691

<jee:jndi-lookup/> (simple)

692

<jee:jndi-lookup/> (with single JNDI environment setting)

692

<jee:jndi-lookup/> (with multiple JNDI environment settings)

692

Spring Framework

<jee:jndi-lookup/> (complex)

693

<jee:local-slsb/> (simple)

693

<jee:local-slsb/> (complex)

693

<jee:remote-slsb/>

694

The lang schema

694

The jms schema

695

The tx (transaction) schema

695

The aop schema

696

The context schema

696

<property-placeholder/>

697

<annotation-config/>

697

<component-scan/>

697

<load-time-weaver/>

697

<spring-configured/>

698

<mbean-export/>

698

The tool schema

698

The beans schema

698

C.3. Setting up your IDE

699

Setting up Eclipse

699

Setting up IntelliJ IDEA

702

Integration issues

706

XML parsing errors in the Resin v.3 application server

706

D. Extensible XML authoring

707

D.1. Introduction

707

D.2. Authoring the schema

707

D.3. Coding a NamespaceHandler

709

D.4. Coding a BeanDefinitionParser

709

D.5. Registering the handler and the schema

710

'META-INF/spring.handlers'

711

'META-INF/spring.schemas'

711

D.6. Using a custom extension in your Spring XML configuration

711

D.7. Meatier examples

712

Nesting custom tags within custom tags

712

Custom attributes on 'normal' elements

715

D.8. Further Resources

717

E. spring-beans-2.0.dtd

718

F. spring.tld

729

F.1. Introduction

729

F.2. The bind tag

729

F.3. The escapeBody tag

730

F.4. The hasBindErrors tag

730

F.5. The htmlEscape tag

730

F.6. The message tag

731

F.7. The nestedPath tag

731

F.8. The theme tag

732

Spring Framework

F.9. The transform tag

732

G. spring-form.tld

734

G.1. Introduction