Siêu thị PDFTải ngay đi em, trời tối mất

Thư viện tri thức trực tuyến

Kho tài liệu với 50,000+ tài liệu học thuật

© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Spring framework reference documentation
PREMIUM
Số trang
912
Kích thước
5.5 MB
Định dạng
PDF
Lượt xem
1574

Spring framework reference documentation

Nội dung xem thử

Mô tả chi tiết

Spring Framework Reference Documentation

4.3.7.RELEASE

Rod Johnson , Juergen Hoeller , Keith Donald , Colin Sampaleanu , Rob Harrop , Thomas Risberg , Alef

Arendsen , 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 Abedrabbo , Andy Clement , Dave Syer , Oliver Gierke ,

Rossen Stoyanchev , Phillip Webb , Rob Winch , Brian Clozel , Stephane Nicoll , Sebastien Deleuze

Copyright © 2004-2016

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 Reference Documentation

4.3.7.RELEASE Spring Framework iii

Table of Contents

I. Overview of Spring Framework ................................................................................................ 1

1. Getting Started with Spring ............................................................................................. 2

2. Introduction to the Spring Framework .............................................................................. 3

2.1. Dependency Injection and Inversion of Control ...................................................... 3

2.2. Modules .............................................................................................................. 3

Core Container .................................................................................................. 4

AOP and Instrumentation ................................................................................... 5

Messaging ......................................................................................................... 5

Data Access/Integration ...................................................................................... 5

Web .................................................................................................................. 5

Test ................................................................................................................... 6

2.3. Usage scenarios ................................................................................................. 6

Dependency Management and Naming Conventions ............................................ 9

Spring Dependencies and Depending on Spring ......................................... 11

Maven Dependency Management ............................................................. 11

Maven "Bill Of Materials" Dependency ....................................................... 12

Gradle Dependency Management ............................................................. 12

Ivy Dependency Management ................................................................... 13

Distribution Zip Files ................................................................................. 13

Logging ............................................................................................................ 13

Not Using Commons Logging ................................................................... 14

Using SLF4J ............................................................................................ 14

Using Log4j .............................................................................................. 15

II. What’s New in Spring Framework 4.x .................................................................................... 18

3. New Features and Enhancements in Spring Framework 4.0 ............................................ 19

3.1. Improved Getting Started Experience .................................................................. 19

3.2. Removed Deprecated Packages and Methods .................................................... 19

3.3. Java 8 (as well as 6 and 7) ............................................................................... 19

3.4. Java EE 6 and 7 ............................................................................................... 20

3.5. Groovy Bean Definition DSL .............................................................................. 20

3.6. Core Container Improvements ............................................................................ 20

3.7. General Web Improvements ............................................................................... 21

3.8. WebSocket, SockJS, and STOMP Messaging ..................................................... 21

3.9. Testing Improvements ........................................................................................ 22

4. New Features and Enhancements in Spring Framework 4.1 ............................................ 23

4.1. JMS Improvements ............................................................................................ 23

4.2. Caching Improvements ...................................................................................... 23

4.3. Web Improvements ............................................................................................ 24

4.4. WebSocket Messaging Improvements ................................................................. 25

4.5. Testing Improvements ........................................................................................ 25

5. New Features and Enhancements in Spring Framework 4.2 ............................................ 27

5.1. Core Container Improvements ............................................................................ 27

5.2. Data Access Improvements ................................................................................ 28

5.3. JMS Improvements ............................................................................................ 29

5.4. Web Improvements ............................................................................................ 29

5.5. WebSocket Messaging Improvements ................................................................. 30

5.6. Testing Improvements ........................................................................................ 30

Spring Framework Reference Documentation

4.3.7.RELEASE Spring Framework iv

6. New Features and Enhancements in Spring Framework 4.3 ............................................ 33

6.1. Core Container Improvements ............................................................................ 33

6.2. Data Access Improvements ................................................................................ 33

6.3. Caching Improvements ...................................................................................... 33

6.4. JMS Improvements ............................................................................................ 34

6.5. Web Improvements ............................................................................................ 34

6.6. WebSocket Messaging Improvements ................................................................. 34

6.7. Testing Improvements ........................................................................................ 34

6.8. Support for new library and server generations .................................................... 35

III. Core Technologies .............................................................................................................. 37

7. The IoC container ........................................................................................................ 38

7.1. Introduction to the Spring IoC container and beans .............................................. 38

7.2. Container overview ............................................................................................ 38

Configuration metadata ..................................................................................... 39

Instantiating a container .................................................................................... 40

Composing XML-based configuration metadata .......................................... 41

The Groovy Bean Definition DSL .............................................................. 42

Using the container .......................................................................................... 43

7.3. Bean overview ................................................................................................... 43

Naming beans .................................................................................................. 44

Aliasing a bean outside the bean definition ................................................ 45

Instantiating beans ........................................................................................... 46

Instantiation with a constructor .................................................................. 47

Instantiation with a static factory method .................................................... 47

Instantiation using an instance factory method ........................................... 47

7.4. Dependencies ................................................................................................... 49

Dependency Injection ....................................................................................... 49

Constructor-based dependency injection .................................................... 49

Setter-based dependency injection ............................................................ 51

Dependency resolution process ................................................................. 52

Examples of dependency injection ............................................................. 53

Dependencies and configuration in detail ........................................................... 55

Straight values (primitives, Strings, and so on) ........................................... 55

References to other beans (collaborators) .................................................. 57

Inner beans .............................................................................................. 58

Collections ............................................................................................... 58

Null and empty string values ..................................................................... 60

XML shortcut with the p-namespace .......................................................... 61

XML shortcut with the c-namespace .......................................................... 62

Compound property names ....................................................................... 63

Using depends-on ............................................................................................ 63

Lazy-initialized beans ....................................................................................... 63

Autowiring collaborators .................................................................................... 64

Limitations and disadvantages of autowiring ............................................... 65

Excluding a bean from autowiring .............................................................. 66

Method injection ............................................................................................... 66

Lookup method injection ........................................................................... 67

Arbitrary method replacement ................................................................... 69

7.5. Bean scopes ..................................................................................................... 70

The singleton scope ......................................................................................... 71

Spring Framework Reference Documentation

4.3.7.RELEASE Spring Framework v

The prototype scope ......................................................................................... 72

Singleton beans with prototype-bean dependencies ............................................ 73

Request, session, global session, application, and WebSocket scopes ................. 73

Initial web configuration ............................................................................ 74

Request scope ......................................................................................... 74

Session scope .......................................................................................... 75

Global session scope ............................................................................... 75

Application scope ..................................................................................... 75

Scoped beans as dependencies ................................................................ 76

Custom scopes ................................................................................................ 78

Creating a custom scope .......................................................................... 78

Using a custom scope .............................................................................. 79

7.6. Customizing the nature of a bean ....................................................................... 80

Lifecycle callbacks ............................................................................................ 80

Initialization callbacks ............................................................................... 81

Destruction callbacks ................................................................................ 81

Default initialization and destroy methods .................................................. 82

Combining lifecycle mechanisms ............................................................... 83

Startup and shutdown callbacks ................................................................ 84

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

................................................................................................................. 86

ApplicationContextAware and BeanNameAware ................................................. 86

Other Aware interfaces ..................................................................................... 87

7.7. Bean definition inheritance ................................................................................. 88

7.8. Container Extension Points ................................................................................ 90

Customizing beans using a BeanPostProcessor ................................................. 90

Example: Hello World, BeanPostProcessor-style ........................................ 91

Example: The RequiredAnnotationBeanPostProcessor ............................... 93

Customizing configuration metadata with a BeanFactoryPostProcessor ................ 93

Example: the Class name substitution PropertyPlaceholderConfigurer .......... 94

Example: the PropertyOverrideConfigurer .................................................. 95

Customizing instantiation logic with a FactoryBean ............................................. 96

7.9. Annotation-based container configuration ............................................................ 96

@Required ....................................................................................................... 98

@Autowired ..................................................................................................... 98

Fine-tuning annotation-based autowiring with @Primary .................................... 101

Fine-tuning annotation-based autowiring with qualifiers ..................................... 102

Using generics as autowiring qualifiers ............................................................ 107

CustomAutowireConfigurer .............................................................................. 108

@Resource .................................................................................................... 108

@PostConstruct and @PreDestroy .................................................................. 110

7.10. Classpath scanning and managed components ................................................ 110

@Component and further stereotype annotations ............................................. 110

Meta-annotations ............................................................................................ 111

Automatically detecting classes and registering bean definitions ........................ 112

Using filters to customize scanning .................................................................. 113

Defining bean metadata within components ..................................................... 114

Naming autodetected components ................................................................... 117

Providing a scope for autodetected components ............................................... 117

Providing qualifier metadata with annotations ................................................... 118

Spring Framework Reference Documentation

4.3.7.RELEASE Spring Framework vi

7.11. Using JSR 330 Standard Annotations ............................................................. 119

Dependency Injection with @Inject and @Named ............................................. 119

@Named and @ManagedBean: standard equivalents to the @Component

annotation ...................................................................................................... 120

Limitations of JSR-330 standard annotations .................................................... 121

7.12. Java-based container configuration ................................................................. 122

Basic concepts: @Bean and @Configuration ................................................... 122

Instantiating the Spring container using AnnotationConfigApplicationContext ....... 123

Simple construction ................................................................................ 123

Building the container programmatically using register(Class<?>…) ........... 124

Enabling component scanning with scan(String…) .................................... 124

Support for web applications with AnnotationConfigWebApplicationContext

............................................................................................................... 125

Using the @Bean annotation .......................................................................... 126

Declaring a bean .................................................................................... 126

Bean dependencies ................................................................................ 127

Receiving lifecycle callbacks ................................................................... 127

Specifying bean scope ............................................................................ 129

Customizing bean naming ....................................................................... 130

Bean aliasing ......................................................................................... 130

Bean description ..................................................................................... 130

Using the @Configuration annotation ............................................................... 130

Injecting inter-bean dependencies ............................................................ 130

Lookup method injection ......................................................................... 131

Further information about how Java-based configuration works internally.... 132

Composing Java-based configurations ............................................................. 133

Using the @Import annotation ................................................................. 133

Conditionally include @Configuration classes or @Bean methods .............. 137

Combining Java and XML configuration ................................................... 138

7.13. Environment abstraction ................................................................................. 140

Bean definition profiles ................................................................................... 140

@Profile ................................................................................................. 141

XML bean definition profiles ............................................................................ 143

Activating a profile .................................................................................. 143

Default profile ......................................................................................... 144

PropertySource abstraction ............................................................................. 144

@PropertySource ........................................................................................... 145

Placeholder resolution in statements ................................................................ 146

7.14. Registering a LoadTimeWeaver ...................................................................... 146

7.15. Additional Capabilities of the ApplicationContext .............................................. 147

Internationalization using MessageSource ........................................................ 147

Standard and Custom Events .......................................................................... 150

Annotation-based Event Listeners ............................................................ 153

Asynchronous Listeners .......................................................................... 155

Ordering Listeners .................................................................................. 155

Generic Events ....................................................................................... 155

Convenient access to low-level resources ........................................................ 156

Convenient ApplicationContext instantiation for web applications ....................... 156

Deploying a Spring ApplicationContext as a Java EE RAR file ........................... 157

7.16. The BeanFactory ........................................................................................... 157

Spring Framework Reference Documentation

4.3.7.RELEASE Spring Framework vii

BeanFactory or ApplicationContext? ................................................................ 158

Glue code and the evil singleton ..................................................................... 159

8. Resources .................................................................................................................. 160

8.1. Introduction ..................................................................................................... 160

8.2. The Resource interface .................................................................................... 160

8.3. Built-in Resource implementations .................................................................... 161

UrlResource ................................................................................................... 161

ClassPathResource ........................................................................................ 161

FileSystemResource ....................................................................................... 162

ServletContextResource .................................................................................. 162

InputStreamResource ..................................................................................... 162

ByteArrayResource ......................................................................................... 162

8.4. The ResourceLoader ....................................................................................... 162

8.5. The ResourceLoaderAware interface ................................................................ 163

8.6. Resources as dependencies ............................................................................. 164

8.7. Application contexts and Resource paths .......................................................... 164

Constructing application contexts ..................................................................... 164

Constructing ClassPathXmlApplicationContext instances - shortcuts .......... 165

Wildcards in application context constructor resource paths ............................... 165

Ant-style Patterns ................................................................................... 166

The Classpath*: portability classpath*: prefix ............................................ 166

Other notes relating to wildcards ............................................................. 167

FileSystemResource caveats .......................................................................... 167

9. Validation, Data Binding, and Type Conversion ............................................................ 169

9.1. Introduction ..................................................................................................... 169

9.2. Validation using Spring’s Validator interface ...................................................... 169

9.3. Resolving codes to error messages .................................................................. 171

9.4. Bean manipulation and the BeanWrapper ......................................................... 172

Setting and getting basic and nested properties ............................................... 172

Built-in PropertyEditor implementations ............................................................ 174

Registering additional custom PropertyEditors .......................................... 177

9.5. Spring Type Conversion ................................................................................... 179

Converter SPI ................................................................................................ 179

ConverterFactory ............................................................................................ 180

GenericConverter ........................................................................................... 180

ConditionalGenericConverter ................................................................... 181

ConversionService API ................................................................................... 181

Configuring a ConversionService ..................................................................... 182

Using a ConversionService programmatically ................................................... 183

9.6. Spring Field Formatting .................................................................................... 183

Formatter SPI ................................................................................................. 184

Annotation-driven Formatting ........................................................................... 185

Format Annotation API ............................................................................ 186

FormatterRegistry SPI ..................................................................................... 186

FormatterRegistrar SPI ................................................................................... 187

Configuring Formatting in Spring MVC ............................................................. 187

9.7. Configuring a global date & time format ............................................................ 187

9.8. Spring Validation ............................................................................................. 189

Overview of the JSR-303 Bean Validation API ................................................. 189

Configuring a Bean Validation Provider ............................................................ 189

Spring Framework Reference Documentation

4.3.7.RELEASE Spring Framework viii

Injecting a Validator ................................................................................ 190

Configuring Custom Constraints .............................................................. 190

Spring-driven Method Validation .............................................................. 191

Additional Configuration Options .............................................................. 191

Configuring a DataBinder ................................................................................ 191

Spring MVC 3 Validation ................................................................................. 192

10. Spring Expression Language (SpEL) ......................................................................... 193

10.1. Introduction .................................................................................................... 193

10.2. Feature Overview ........................................................................................... 193

10.3. Expression Evaluation using Spring’s Expression Interface ............................... 194

The EvaluationContext interface ...................................................................... 196

Type Conversion .................................................................................... 196

Parser configuration ........................................................................................ 197

SpEL compilation ............................................................................................ 197

Compiler configuration ............................................................................ 198

Compiler limitations ................................................................................ 199

10.4. Expression support for defining bean definitions ............................................... 199

XML based configuration ................................................................................ 199

Annotation-based configuration ........................................................................ 200

10.5. Language Reference ...................................................................................... 201

Literal expressions .......................................................................................... 201

Properties, Arrays, Lists, Maps, Indexers ......................................................... 201

Inline lists ....................................................................................................... 202

Inline Maps .................................................................................................... 202

Array construction ........................................................................................... 203

Methods ......................................................................................................... 203

Operators ....................................................................................................... 203

Relational operators ................................................................................ 203

Logical operators .................................................................................... 204

Mathematical operators ........................................................................... 204

Assignment .................................................................................................... 205

Types ............................................................................................................. 205

Constructors ................................................................................................... 205

Variables ........................................................................................................ 206

The #this and #root variables .................................................................. 206

Functions ....................................................................................................... 206

Bean references ............................................................................................. 207

Ternary Operator (If-Then-Else) ....................................................................... 207

The Elvis Operator ......................................................................................... 207

Safe Navigation operator ................................................................................ 208

Collection Selection ........................................................................................ 208

Collection Projection ....................................................................................... 209

Expression templating ..................................................................................... 209

10.6. Classes used in the examples ........................................................................ 210

11. Aspect Oriented Programming with Spring ................................................................. 214

11.1. Introduction .................................................................................................... 214

AOP concepts ................................................................................................ 214

Spring AOP capabilities and goals ................................................................... 216

AOP Proxies .................................................................................................. 217

11.2. @AspectJ support .......................................................................................... 217

Spring Framework Reference Documentation

4.3.7.RELEASE Spring Framework ix

Enabling @AspectJ Support ............................................................................ 217

Enabling @AspectJ Support with Java configuration ................................. 217

Enabling @AspectJ Support with XML configuration ................................. 218

Declaring an aspect ........................................................................................ 218

Declaring a pointcut ........................................................................................ 219

Supported Pointcut Designators .............................................................. 219

Combining pointcut expressions .............................................................. 221

Sharing common pointcut definitions ........................................................ 221

Examples ............................................................................................... 223

Writing good pointcuts ............................................................................ 225

Declaring advice ............................................................................................. 226

Before advice ......................................................................................... 226

After returning advice .............................................................................. 226

After throwing advice .............................................................................. 227

After (finally) advice ................................................................................ 228

Around advice ........................................................................................ 228

Advice parameters .................................................................................. 229

Advice ordering ...................................................................................... 232

Introductions ................................................................................................... 233

Aspect instantiation models ............................................................................. 233

Example ......................................................................................................... 234

11.3. Schema-based AOP support .......................................................................... 236

Declaring an aspect ........................................................................................ 236

Declaring a pointcut ........................................................................................ 237

Declaring advice ............................................................................................. 238

Before advice ......................................................................................... 238

After returning advice .............................................................................. 239

After throwing advice .............................................................................. 239

After (finally) advice ................................................................................ 240

Around advice ........................................................................................ 240

Advice parameters .................................................................................. 241

Advice ordering ...................................................................................... 242

Introductions ................................................................................................... 243

Aspect instantiation models ............................................................................. 243

Advisors ......................................................................................................... 243

Example ......................................................................................................... 244

11.4. Choosing which AOP declaration style to use .................................................. 246

Spring AOP or full AspectJ? ........................................................................... 246

@AspectJ or XML for Spring AOP? ................................................................. 247

11.5. Mixing aspect types ....................................................................................... 247

11.6. Proxying mechanisms .................................................................................... 248

Understanding AOP proxies ............................................................................ 248

11.7. Programmatic creation of @AspectJ Proxies ................................................... 251

11.8. Using AspectJ with Spring applications ........................................................... 251

Using AspectJ to dependency inject domain objects with Spring ........................ 251

Unit testing @Configurable objects .......................................................... 254

Working with multiple application contexts ................................................ 254

Other Spring aspects for AspectJ .................................................................... 254

Configuring AspectJ aspects using Spring IoC ................................................. 255

Load-time weaving with AspectJ in the Spring Framework ................................. 256

Spring Framework Reference Documentation

4.3.7.RELEASE Spring Framework x

A first example ....................................................................................... 256

Aspects .................................................................................................. 259

'META-INF/aop.xml' ................................................................................ 259

Required libraries (JARS) ........................................................................ 260

Spring configuration ................................................................................ 260

Environment-specific configuration ........................................................... 262

11.9. Further Resources ......................................................................................... 264

12. Spring AOP APIs ...................................................................................................... 265

12.1. Introduction .................................................................................................... 265

12.2. Pointcut API in Spring .................................................................................... 265

Concepts ........................................................................................................ 265

Operations on pointcuts .................................................................................. 266

AspectJ expression pointcuts .......................................................................... 266

Convenience pointcut implementations ............................................................ 266

Static pointcuts ....................................................................................... 266

Dynamic pointcuts .................................................................................. 267

Pointcut superclasses ..................................................................................... 268

Custom pointcuts ............................................................................................ 268

12.3. Advice API in Spring ...................................................................................... 268

Advice lifecycles ............................................................................................. 268

Advice types in Spring .................................................................................... 268

Interception around advice ...................................................................... 268

Before advice ......................................................................................... 269

Throws advice ........................................................................................ 270

After Returning advice ............................................................................ 271

Introduction advice .................................................................................. 272

12.4. Advisor API in Spring ..................................................................................... 274

12.5. Using the ProxyFactoryBean to create AOP proxies ......................................... 274

Basics ............................................................................................................ 274

JavaBean properties ....................................................................................... 275

JDK- and CGLIB-based proxies ...................................................................... 276

Proxying interfaces ......................................................................................... 276

Proxying classes ............................................................................................ 278

Using 'global' advisors .................................................................................... 279

12.6. Concise proxy definitions ................................................................................ 279

12.7. Creating AOP proxies programmatically with the ProxyFactory .......................... 280

12.8. Manipulating advised objects .......................................................................... 281

12.9. Using the "auto-proxy" facility ......................................................................... 282

Autoproxy bean definitions .............................................................................. 282

BeanNameAutoProxyCreator ................................................................... 282

DefaultAdvisorAutoProxyCreator .............................................................. 283

AbstractAdvisorAutoProxyCreator ............................................................ 284

Using metadata-driven auto-proxying ............................................................... 284

12.10. Using TargetSources .................................................................................... 286

Hot swappable target sources ......................................................................... 286

Pooling target sources .................................................................................... 286

Prototype target sources ................................................................................. 288

ThreadLocal target sources ............................................................................. 288

12.11. Defining new Advice types ............................................................................ 288

12.12. Further resources ......................................................................................... 289

Spring Framework Reference Documentation

4.3.7.RELEASE Spring Framework xi

IV. Testing ............................................................................................................................. 290

13. Introduction to Spring Testing .................................................................................... 291

14. Unit Testing .............................................................................................................. 292

14.1. Mock Objects ................................................................................................. 292

Environment ................................................................................................... 292

JNDI .............................................................................................................. 292

Servlet API ..................................................................................................... 292

Portlet API ..................................................................................................... 292

14.2. Unit Testing support Classes .......................................................................... 293

General testing utilities ................................................................................... 293

Spring MVC ................................................................................................... 293

15. Integration Testing .................................................................................................... 294

15.1. Overview ....................................................................................................... 294

15.2. Goals of Integration Testing ............................................................................ 294

Context management and caching .................................................................. 294

Dependency Injection of test fixtures ............................................................... 295

Transaction management ................................................................................ 295

Support classes for integration testing ............................................................. 296

15.3. JDBC Testing Support ................................................................................... 296

15.4. Annotations ................................................................................................... 296

Spring Testing Annotations ............................................................................. 296

@BootstrapWith ..................................................................................... 297

@ContextConfiguration ........................................................................... 297

@WebAppConfiguration .......................................................................... 297

@ContextHierarchy ................................................................................. 298

@ActiveProfiles ...................................................................................... 298

@TestPropertySource ............................................................................. 299

@DirtiesContext ..................................................................................... 299

@TestExecutionListeners ........................................................................ 301

@Commit ............................................................................................... 301

@Rollback .............................................................................................. 301

@BeforeTransaction ............................................................................... 302

@AfterTransaction .................................................................................. 302

@Sql ..................................................................................................... 302

@SqlConfig ............................................................................................ 302

@SqlGroup ............................................................................................ 303

Standard Annotation Support .......................................................................... 303

Spring JUnit 4 Testing Annotations .................................................................. 304

@IfProfileValue ....................................................................................... 304

@ProfileValueSourceConfiguration .......................................................... 304

@Timed ................................................................................................. 304

@Repeat ................................................................................................ 305

Meta-Annotation Support for Testing ................................................................ 305

15.5. Spring TestContext Framework ....................................................................... 306

Key abstractions ............................................................................................. 307

TestContext ............................................................................................ 307

TestContextManager ............................................................................... 307

TestExecutionListener ............................................................................. 307

Context Loaders ..................................................................................... 307

Bootstrapping the TestContext framework ........................................................ 308

Spring Framework Reference Documentation

4.3.7.RELEASE Spring Framework xii

TestExecutionListener configuration ................................................................. 309

Registering custom TestExecutionListeners .............................................. 309

Automatic discovery of default TestExecutionListeners .............................. 309

Ordering TestExecutionListeners ............................................................. 309

Merging TestExecutionListeners .............................................................. 310

Context management ...................................................................................... 311

Context configuration with XML resources ................................................ 312

Context configuration with Groovy scripts ................................................. 312

Context configuration with annotated classes ........................................... 313

Mixing XML, Groovy scripts, and annotated classes .................................. 314

Context configuration with context initializers ............................................ 315

Context configuration inheritance ............................................................. 316

Context configuration with environment profiles ........................................ 317

Context configuration with test property sources ....................................... 322

Loading a WebApplicationContext ........................................................... 324

Context caching ...................................................................................... 327

Context hierarchies ................................................................................. 328

Dependency injection of test fixtures ................................................................ 330

Testing request and session scoped beans ...................................................... 332

Transaction management ................................................................................ 334

Test-managed transactions ..................................................................... 334

Enabling and disabling transactions ......................................................... 335

Transaction rollback and commit behavior ................................................ 336

Programmatic transaction management ................................................... 336

Executing code outside of a transaction ................................................... 336

Configuring a transaction manager .......................................................... 337

Demonstration of all transaction-related annotations ................................. 337

Executing SQL scripts .................................................................................... 338

Executing SQL scripts programmatically .................................................. 339

Executing SQL scripts declaratively with @Sql ......................................... 339

TestContext Framework support classes .......................................................... 343

Spring JUnit 4 Runner ............................................................................ 343

Spring JUnit 4 Rules .............................................................................. 343

JUnit 4 support classes ........................................................................... 344

TestNG support classes .......................................................................... 344

15.6. Spring MVC Test Framework .......................................................................... 345

Server-Side Tests ........................................................................................... 346

Static Imports ......................................................................................... 347

Setup Options ........................................................................................ 347

Performing Requests .............................................................................. 348

Defining Expectations ............................................................................. 349

Filter Registrations .................................................................................. 350

Differences between Out-of-Container and End-to-End Integration Tests.... 350

Further Server-Side Test Examples ......................................................... 351

HtmlUnit Integration ........................................................................................ 351

Why HtmlUnit Integration? ...................................................................... 352

MockMvc and HtmlUnit ........................................................................... 354

MockMvc and WebDriver ........................................................................ 356

MockMvc and Geb ................................................................................. 361

Client-Side REST Tests .................................................................................. 362

Spring Framework Reference Documentation

4.3.7.RELEASE Spring Framework xiii

Static Imports ......................................................................................... 363

Further Examples of Client-side REST Tests ............................................ 363

15.7. PetClinic Example .......................................................................................... 364

16. Further Resources .................................................................................................... 366

V. Data Access ...................................................................................................................... 367

17. Transaction Management .......................................................................................... 368

17.1. Introduction to Spring Framework transaction management .............................. 368

17.2. Advantages of the Spring Framework’s transaction support model ..................... 368

Global transactions ......................................................................................... 368

Local transactions ........................................................................................... 369

Spring Framework’s consistent programming model ......................................... 369

17.3. Understanding the Spring Framework transaction abstraction ............................ 370

17.4. Synchronizing resources with transactions ....................................................... 373

High-level synchronization approach ................................................................ 373

Low-level synchronization approach ................................................................. 374

TransactionAwareDataSourceProxy ................................................................. 374

17.5. Declarative transaction management ............................................................... 374

Understanding the Spring Framework’s declarative transaction implementation... 376

Example of declarative transaction implementation ........................................... 376

Rolling back a declarative transaction .............................................................. 380

Configuring different transactional semantics for different beans ........................ 381

<tx:advice/> settings ....................................................................................... 383

Using @Transactional ..................................................................................... 384

@Transactional settings .......................................................................... 389

Multiple Transaction Managers with @Transactional ................................. 390

Custom shortcut annotations ................................................................... 391

Transaction propagation .................................................................................. 391

Required ................................................................................................ 391

RequiresNew .......................................................................................... 392

Nested ................................................................................................... 392

Advising transactional operations ..................................................................... 392

Using @Transactional with AspectJ ................................................................. 395

17.6. Programmatic transaction management ........................................................... 396

Using the TransactionTemplate ....................................................................... 396

Specifying transaction settings ................................................................ 398

Using the PlatformTransactionManager ............................................................ 398

17.7. Choosing between programmatic and declarative transaction management ........ 399

17.8. Transaction bound event ................................................................................ 399

17.9. Application server-specific integration .............................................................. 399

IBM WebSphere ............................................................................................. 400

Oracle WebLogic Server ................................................................................. 400

17.10. Solutions to common problems ..................................................................... 400

Use of the wrong transaction manager for a specific DataSource ....................... 400

17.11. Further Resources ....................................................................................... 400

18. DAO support ............................................................................................................ 402

18.1. Introduction .................................................................................................... 402

18.2. Consistent exception hierarchy ....................................................................... 402

18.3. Annotations used for configuring DAO or Repository classes ............................ 403

19. Data access with JDBC ............................................................................................ 405

19.1. Introduction to Spring Framework JDBC .......................................................... 405

Spring Framework Reference Documentation

4.3.7.RELEASE Spring Framework xiv

Choosing an approach for JDBC database access ........................................... 405

Package hierarchy .......................................................................................... 406

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

handling ................................................................................................................. 407

JdbcTemplate ................................................................................................. 407

Examples of JdbcTemplate class usage ................................................... 407

JdbcTemplate best practices ................................................................... 409

NamedParameterJdbcTemplate ....................................................................... 411

SQLExceptionTranslator .................................................................................. 413

Executing statements ...................................................................................... 414

Running queries ............................................................................................. 415

Updating the database .................................................................................... 416

Retrieving auto-generated keys ....................................................................... 416

19.3. Controlling database connections .................................................................... 416

DataSource .................................................................................................... 416

DataSourceUtils .............................................................................................. 418

SmartDataSource ........................................................................................... 418

AbstractDataSource ........................................................................................ 418

SingleConnectionDataSource .......................................................................... 418

DriverManagerDataSource .............................................................................. 418

TransactionAwareDataSourceProxy ................................................................. 419

DataSourceTransactionManager ...................................................................... 419

NativeJdbcExtractor ........................................................................................ 419

19.4. JDBC batch operations .................................................................................. 420

Basic batch operations with the JdbcTemplate ................................................. 420

Batch operations with a List of objects ............................................................. 421

Batch operations with multiple batches ............................................................ 422

19.5. Simplifying JDBC operations with the SimpleJdbc classes ................................ 422

Inserting data using SimpleJdbcInsert .............................................................. 423

Retrieving auto-generated keys using SimpleJdbcInsert .................................... 423

Specifying columns for a SimpleJdbcInsert ...................................................... 424

Using SqlParameterSource to provide parameter values ................................... 425

Calling a stored procedure with SimpleJdbcCall ............................................... 425

Explicitly declaring parameters to use for a SimpleJdbcCall ............................... 427

How to define SqlParameters .......................................................................... 428

Calling a stored function using SimpleJdbcCall ................................................. 428

Returning ResultSet/REF Cursor from a SimpleJdbcCall ................................... 429

19.6. Modeling JDBC operations as Java objects ..................................................... 430

SqlQuery ........................................................................................................ 430

MappingSqlQuery ........................................................................................... 431

SqlUpdate ...................................................................................................... 432

StoredProcedure ............................................................................................. 432

19.7. Common problems with parameter and data value handling .............................. 435

Providing SQL type information for parameters ................................................. 435

Handling BLOB and CLOB objects .................................................................. 436

Passing in lists of values for IN clause ............................................................ 437

Handling complex types for stored procedure calls ........................................... 437

19.8. Embedded database support .......................................................................... 439

Why use an embedded database? .................................................................. 439

Creating an embedded database using Spring XML .......................................... 439

Spring Framework Reference Documentation

4.3.7.RELEASE Spring Framework xv

Creating an embedded database programmatically ........................................... 439

Selecting the embedded database type ........................................................... 440

Using HSQL ........................................................................................... 440

Using H2 ................................................................................................ 440

Using Derby ........................................................................................... 440

Testing data access logic with an embedded database ..................................... 440

Generating unique names for embedded databases ......................................... 441

Extending the embedded database support ...................................................... 441

19.9. Initializing a DataSource ................................................................................. 442

Initializing a database using Spring XML .......................................................... 442

Initialization of other components that depend on the database .................. 443

20. Object Relational Mapping (ORM) Data Access .......................................................... 445

20.1. Introduction to ORM with Spring ..................................................................... 445

20.2. General ORM integration considerations ......................................................... 446

Resource and transaction management ........................................................... 446

Exception translation ....................................................................................... 447

20.3. Hibernate ....................................................................................................... 447

SessionFactory setup in a Spring container ...................................................... 447

Implementing DAOs based on plain Hibernate API ........................................... 448

Declarative transaction demarcation ................................................................ 449

Programmatic transaction demarcation ............................................................ 450

Transaction management strategies ................................................................ 451

Comparing container-managed and locally defined resources ............................ 452

Spurious application server warnings with Hibernate ......................................... 453

20.4. JDO .............................................................................................................. 454

PersistenceManagerFactory setup ................................................................... 454

Implementing DAOs based on the plain JDO API ............................................. 455

Transaction management ................................................................................ 457

JdoDialect ...................................................................................................... 458

20.5. JPA ............................................................................................................... 458

Three options for JPA setup in a Spring environment ........................................ 458

LocalEntityManagerFactoryBean .............................................................. 458

Obtaining an EntityManagerFactory from JNDI ......................................... 459

LocalContainerEntityManagerFactoryBean ............................................... 459

Dealing with multiple persistence units ..................................................... 461

Implementing DAOs based on JPA: EntityManagerFactory and EntityManager.... 462

Spring-driven JPA transactions ........................................................................ 464

JpaDialect and JpaVendorAdapter ................................................................... 464

Setting up JPA with JTA transaction management ............................................ 464

21. Marshalling XML using O/X Mappers ......................................................................... 466

21.1. Introduction .................................................................................................... 466

Ease of configuration ...................................................................................... 466

Consistent Interfaces ...................................................................................... 466

Consistent Exception Hierarchy ....................................................................... 466

21.2. Marshaller and Unmarshaller .......................................................................... 466

Marshaller ...................................................................................................... 466

Unmarshaller .................................................................................................. 467

XmlMappingException ..................................................................................... 468

21.3. Using Marshaller and Unmarshaller ................................................................. 468

21.4. XML Schema-based Configuration .................................................................. 470

Tải ngay đi em, còn do dự, trời tối mất!