1. Trang chủ
  2. » Giáo án - Bài giảng

Spring Framework Reference

910 1,3K 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 910
Dung lượng 5,47 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Introduction to Spring Framework transaction management .... If you are just getting started with Spring, you may want to begin using the Spring Framework bycreating a Spring Boot based

Trang 1

Rod Johnson , Juergen Hoeller , Keith Donald , Colin Sampaleanu , Rob Harrop , Thomas Risberg , AlefArendsen , Darren Davison , Dmitriy Kopylenko , Mark Pollack , Thierry Templier , Erwin Vervaet , PortiaTung , Ben Hale , Adrian Colyer , John Lewis , Costin Leau , Mark Fisher , Sam Brannen , RamnivasLaddad , Arjen Poutsma , Chris Beams , Tareq Abedrabbo , Andy Clement , Dave Syer , Oliver Gierke ,Rossen Stoyanchev , Phillip Webb , Rob Winch , Brian Clozel , Stephane Nicoll , Sebastien Deleuze

Trang 2

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.

Trang 3

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 17

3 New Features and Enhancements in Spring Framework 4.0 18

3.1 Improved Getting Started Experience 18

3.2 Removed Deprecated Packages and Methods 18

3.3 Java 8 (as well as 6 and 7) 18

3.4 Java EE 6 and 7 19

3.5 Groovy Bean Definition DSL 19

3.6 Core Container Improvements 19

3.7 General Web Improvements 20

3.8 WebSocket, SockJS, and STOMP Messaging 20

3.9 Testing Improvements 21

4 New Features and Enhancements in Spring Framework 4.1 22

4.1 JMS Improvements 22

4.2 Caching Improvements 22

4.3 Web Improvements 23

4.4 WebSocket Messaging Improvements 24

4.5 Testing Improvements 24

5 New Features and Enhancements in Spring Framework 4.2 26

5.1 Core Container Improvements 26

5.2 Data Access Improvements 27

5.3 JMS Improvements 28

5.4 Web Improvements 28

5.5 WebSocket Messaging Improvements 29

5.6 Testing Improvements 29

Trang 4

6 New Features and Enhancements in Spring Framework 4.3 32

6.1 Core Container Improvements 32

6.2 Data Access Improvements 32

6.3 Caching Improvements 32

6.4 JMS Improvements 33

6.5 Web Improvements 33

6.6 WebSocket Messaging Improvements 33

6.7 Testing Improvements 33

6.8 Support for new library and server generations 34

III Core Technologies 36

7 The IoC container 37

7.1 Introduction to the Spring IoC container and beans 37

7.2 Container overview 37

Configuration metadata 38

Instantiating a container 39

Composing XML-based configuration metadata 40

Using the container 41

7.3 Bean overview 41

Naming beans 42

Aliasing a bean outside the bean definition 43

Instantiating beans 44

Instantiation with a constructor 45

Instantiation with a static factory method 45

Instantiation using an instance factory method 45

7.4 Dependencies 47

Dependency Injection 47

Constructor-based dependency injection 47

Setter-based dependency injection 49

Dependency resolution process 50

Examples of dependency injection 51

Dependencies and configuration in detail 53

Straight values (primitives, Strings, and so on) 53

References to other beans (collaborators) 55

Inner beans 56

Collections 56

Null and empty string values 58

XML shortcut with the p-namespace 59

XML shortcut with the c-namespace 60

Compound property names 61

Using depends-on 61

Lazy-initialized beans 61

Autowiring collaborators 62

Limitations and disadvantages of autowiring 63

Excluding a bean from autowiring 64

Method injection 64

Lookup method injection 65

Arbitrary method replacement 67

7.5 Bean scopes 68

The singleton scope 69

Trang 5

Singleton beans with prototype-bean dependencies 71

Request, session, global session, application, and WebSocket scopes 71

Initial web configuration 72

Request scope 72

Session scope 73

Global session scope 73

Application scope 73

Scoped beans as dependencies 74

Custom scopes 76

Creating a custom scope 76

Using a custom scope 77

7.6 Customizing the nature of a bean 78

Lifecycle callbacks 78

Initialization callbacks 79

Destruction callbacks 79

Default initialization and destroy methods 80

Combining lifecycle mechanisms 81

Startup and shutdown callbacks 82

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

ApplicationContextAware and BeanNameAware 84

Other Aware interfaces 85

7.7 Bean definition inheritance 86

7.8 Container Extension Points 88

Customizing beans using a BeanPostProcessor 88

Example: Hello World, BeanPostProcessor-style 89

Example: The RequiredAnnotationBeanPostProcessor 91

Customizing configuration metadata with a BeanFactoryPostProcessor 91

Example: the Class name substitution PropertyPlaceholderConfigurer 92

Example: the PropertyOverrideConfigurer 93

Customizing instantiation logic with a FactoryBean 94

7.9 Annotation-based container configuration 94

@Required 96

@Autowired 96

Fine-tuning annotation-based autowiring with @Primary 99

Fine-tuning annotation-based autowiring with qualifiers 100

Using generics as autowiring qualifiers 105

CustomAutowireConfigurer 106

@Resource 106

@PostConstruct and @PreDestroy 108

7.10 Classpath scanning and managed components 108

@Component and further stereotype annotations 108

Meta-annotations 109

Automatically detecting classes and registering bean definitions 110

Using filters to customize scanning 111

Defining bean metadata within components 112

Naming autodetected components 115

Providing a scope for autodetected components 115

Providing qualifier metadata with annotations 116

7.11 Using JSR 330 Standard Annotations 117

Trang 6

Dependency Injection with @Inject and @Named 117

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

Limitations of JSR-330 standard annotations 119

7.12 Java-based container configuration 120

Basic concepts: @Bean and @Configuration 120

Instantiating the Spring container using AnnotationConfigApplicationContext 121

Simple construction 121

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

Enabling component scanning with scan(String…) 122

Support for web applications with AnnotationConfigWebApplicationContext 123

Using the @Bean annotation 124

Declaring a bean 124

Bean dependencies 125

Receiving lifecycle callbacks 125

Specifying bean scope 127

Customizing bean naming 128

Bean aliasing 128

Bean description 128

Using the @Configuration annotation 128

Injecting inter-bean dependencies 128

Lookup method injection 129

Further information about how Java-based configuration works internally 130

Composing Java-based configurations 131

Using the @Import annotation 131

Conditionally include @Configuration classes or @Bean methods 135

Combining Java and XML configuration 136

7.13 Environment abstraction 138

Bean definition profiles 138

@Profile 139

XML bean definition profiles 141

Activating a profile 141

Default profile 142

PropertySource abstraction 142

@PropertySource 143

Placeholder resolution in statements 144

7.14 Registering a LoadTimeWeaver 144

7.15 Additional Capabilities of the ApplicationContext 145

Internationalization using MessageSource 145

Standard and Custom Events 148

Annotation-based Event Listeners 151

Asynchronous Listeners 153

Ordering Listeners 153

Generic Events 153

Convenient access to low-level resources 154

Convenient ApplicationContext instantiation for web applications 154

Deploying a Spring ApplicationContext as a Java EE RAR file 155

7.16 The BeanFactory 155

Trang 7

Glue code and the evil singleton 157

8 Resources 158

8.1 Introduction 158

8.2 The Resource interface 158

8.3 Built-in Resource implementations 159

UrlResource 159

ClassPathResource 159

FileSystemResource 160

ServletContextResource 160

InputStreamResource 160

ByteArrayResource 160

8.4 The ResourceLoader 160

8.5 The ResourceLoaderAware interface 161

8.6 Resources as dependencies 162

8.7 Application contexts and Resource paths 162

Constructing application contexts 162

Constructing ClassPathXmlApplicationContext instances - shortcuts 163

Wildcards in application context constructor resource paths 163

Ant-style Patterns 164

The Classpath*: portability classpath*: prefix 164

Other notes relating to wildcards 165

FileSystemResource caveats 165

9 Validation, Data Binding, and Type Conversion 167

9.1 Introduction 167

9.2 Validation using Spring’s Validator interface 167

9.3 Resolving codes to error messages 169

9.4 Bean manipulation and the BeanWrapper 170

Setting and getting basic and nested properties 170

Built-in PropertyEditor implementations 172

Registering additional custom PropertyEditors 175

9.5 Spring Type Conversion 177

Converter SPI 177

ConverterFactory 178

GenericConverter 178

ConditionalGenericConverter 179

ConversionService API 179

Configuring a ConversionService 180

Using a ConversionService programmatically 181

9.6 Spring Field Formatting 181

Formatter SPI 182

Annotation-driven Formatting 183

Format Annotation API 184

FormatterRegistry SPI 184

FormatterRegistrar SPI 185

Configuring Formatting in Spring MVC 185

9.7 Configuring a global date & time format 185

9.8 Spring Validation 187

Overview of the JSR-303 Bean Validation API 187

Configuring a Bean Validation Provider 187

Injecting a Validator 188

Trang 8

Configuring Custom Constraints 188

Spring-driven Method Validation 189

Additional Configuration Options 189

Configuring a DataBinder 189

Spring MVC 3 Validation 190

10 Spring Expression Language (SpEL) 191

10.1 Introduction 191

10.2 Feature Overview 191

10.3 Expression Evaluation using Spring’s Expression Interface 192

The EvaluationContext interface 194

Type Conversion 194

Parser configuration 195

SpEL compilation 195

Compiler configuration 196

Compiler limitations 197

10.4 Expression support for defining bean definitions 197

XML based configuration 197

Annotation-based configuration 198

10.5 Language Reference 199

Literal expressions 199

Properties, Arrays, Lists, Maps, Indexers 199

Inline lists 200

Inline Maps 200

Array construction 201

Methods 201

Operators 201

Relational operators 201

Logical operators 202

Mathematical operators 202

Assignment 203

Types 203

Constructors 203

Variables 204

The #this and #root variables 204

Functions 204

Bean references 205

Ternary Operator (If-Then-Else) 205

The Elvis Operator 205

Safe Navigation operator 206

Collection Selection 206

Collection Projection 207

Expression templating 207

10.6 Classes used in the examples 208

11 Aspect Oriented Programming with Spring 212

11.1 Introduction 212

AOP concepts 212

Spring AOP capabilities and goals 214

AOP Proxies 215

11.2 @AspectJ support 215

Trang 9

Enabling @AspectJ Support with Java configuration 215

Enabling @AspectJ Support with XML configuration 216

Declaring an aspect 216

Declaring a pointcut 217

Supported Pointcut Designators 217

Combining pointcut expressions 219

Sharing common pointcut definitions 219

Examples 221

Writing good pointcuts 223

Declaring advice 224

Before advice 224

After returning advice 224

After throwing advice 225

After (finally) advice 226

Around advice 226

Advice parameters 227

Advice ordering 230

Introductions 231

Aspect instantiation models 231

Example 232

11.3 Schema-based AOP support 234

Declaring an aspect 234

Declaring a pointcut 235

Declaring advice 236

Before advice 236

After returning advice 237

After throwing advice 237

After (finally) advice 238

Around advice 238

Advice parameters 239

Advice ordering 240

Introductions 241

Aspect instantiation models 241

Advisors 241

Example 242

11.4 Choosing which AOP declaration style to use 244

Spring AOP or full AspectJ? 244

@AspectJ or XML for Spring AOP? 245

11.5 Mixing aspect types 245

11.6 Proxying mechanisms 246

Understanding AOP proxies 246

11.7 Programmatic creation of @AspectJ Proxies 249

11.8 Using AspectJ with Spring applications 249

Using AspectJ to dependency inject domain objects with Spring 249

Unit testing @Configurable objects 252

Working with multiple application contexts 252

Other Spring aspects for AspectJ 252

Configuring AspectJ aspects using Spring IoC 253

Load-time weaving with AspectJ in the Spring Framework 254

A first example 254

Trang 10

Aspects 257

'META-INF/aop.xml' 257

Required libraries (JARS) 258

Spring configuration 258

Environment-specific configuration 260

11.9 Further Resources 262

12 Spring AOP APIs 263

12.1 Introduction 263

12.2 Pointcut API in Spring 263

Concepts 263

Operations on pointcuts 264

AspectJ expression pointcuts 264

Convenience pointcut implementations 264

Static pointcuts 264

Dynamic pointcuts 265

Pointcut superclasses 266

Custom pointcuts 266

12.3 Advice API in Spring 266

Advice lifecycles 266

Advice types in Spring 266

Interception around advice 266

Before advice 267

Throws advice 268

After Returning advice 269

Introduction advice 270

12.4 Advisor API in Spring 272

12.5 Using the ProxyFactoryBean to create AOP proxies 272

Basics 272

JavaBean properties 273

JDK- and CGLIB-based proxies 274

Proxying interfaces 274

Proxying classes 276

Using 'global' advisors 277

12.6 Concise proxy definitions 277

12.7 Creating AOP proxies programmatically with the ProxyFactory 278

12.8 Manipulating advised objects 279

12.9 Using the "auto-proxy" facility 280

Autoproxy bean definitions 280

BeanNameAutoProxyCreator 280

DefaultAdvisorAutoProxyCreator 281

AbstractAdvisorAutoProxyCreator 282

Using metadata-driven auto-proxying 282

12.10 Using TargetSources 284

Hot swappable target sources 284

Pooling target sources 284

Prototype target sources 286

ThreadLocal target sources 286

12.11 Defining new Advice types 286

12.12 Further resources 287

Trang 11

13 Introduction to Spring Testing 289

14 Unit Testing 290

14.1 Mock Objects 290

Environment 290

JNDI 290

Servlet API 290

Portlet API 290

14.2 Unit Testing support Classes 291

General testing utilities 291

Spring MVC 291

15 Integration Testing 292

15.1 Overview 292

15.2 Goals of Integration Testing 292

Context management and caching 292

Dependency Injection of test fixtures 293

Transaction management 293

Support classes for integration testing 294

15.3 JDBC Testing Support 294

15.4 Annotations 294

Spring Testing Annotations 294

@BootstrapWith 295

@ContextConfiguration 295

@WebAppConfiguration 295

@ContextHierarchy 296

@ActiveProfiles 296

@TestPropertySource 297

@DirtiesContext 297

@TestExecutionListeners 299

@Commit 299

@Rollback 299

@BeforeTransaction 300

@AfterTransaction 300

@Sql 300

@SqlConfig 300

@SqlGroup 301

Standard Annotation Support 301

Spring JUnit 4 Testing Annotations 302

@IfProfileValue 302

@ProfileValueSourceConfiguration 302

@Timed 302

@Repeat 303

Meta-Annotation Support for Testing 303

15.5 Spring TestContext Framework 304

Key abstractions 305

TestContext 305

TestContextManager 305

TestExecutionListener 305

Context Loaders 305

Bootstrapping the TestContext framework 306

TestExecutionListener configuration 307

Trang 12

Registering custom TestExecutionListeners 307

Automatic discovery of default TestExecutionListeners 307

Ordering TestExecutionListeners 307

Merging TestExecutionListeners 308

Context management 309

Context configuration with XML resources 310

Context configuration with Groovy scripts 310

Context configuration with annotated classes 311

Mixing XML, Groovy scripts, and annotated classes 312

Context configuration with context initializers 313

Context configuration inheritance 314

Context configuration with environment profiles 315

Context configuration with test property sources 320

Loading a WebApplicationContext 322

Context caching 325

Context hierarchies 326

Dependency injection of test fixtures 328

Testing request and session scoped beans 330

Transaction management 332

Test-managed transactions 332

Enabling and disabling transactions 333

Transaction rollback and commit behavior 334

Programmatic transaction management 334

Executing code outside of a transaction 334

Configuring a transaction manager 335

Demonstration of all transaction-related annotations 335

Executing SQL scripts 336

Executing SQL scripts programmatically 337

Executing SQL scripts declaratively with @Sql 337

TestContext Framework support classes 341

Spring JUnit 4 Runner 341

Spring JUnit 4 Rules 341

JUnit 4 support classes 342

TestNG support classes 342

15.6 Spring MVC Test Framework 343

Server-Side Tests 344

Static Imports 345

Setup Options 345

Performing Requests 346

Defining Expectations 347

Filter Registrations 348

Differences between Out-of-Container and End-to-End Integration Tests 348

Further Server-Side Test Examples 349

HtmlUnit Integration 349

Why HtmlUnit Integration? 350

MockMvc and HtmlUnit 352

MockMvc and WebDriver 354

MockMvc and Geb 359

Client-Side REST Tests 360

Trang 13

Further Examples of Client-side REST Tests 361

15.7 PetClinic Example 362

16 Further Resources 364

V Data Access 365

17 Transaction Management 366

17.1 Introduction to Spring Framework transaction management 366

17.2 Advantages of the Spring Framework’s transaction support model 366

Global transactions 366

Local transactions 367

Spring Framework’s consistent programming model 367

17.3 Understanding the Spring Framework transaction abstraction 368

17.4 Synchronizing resources with transactions 371

High-level synchronization approach 371

Low-level synchronization approach 372

TransactionAwareDataSourceProxy 372

17.5 Declarative transaction management 372

Understanding the Spring Framework’s declarative transaction implementation 374

Example of declarative transaction implementation 374

Rolling back a declarative transaction 378

Configuring different transactional semantics for different beans 379

<tx:advice/> settings 381

Using @Transactional 382

@Transactional settings 387

Multiple Transaction Managers with @Transactional 388

Custom shortcut annotations 389

Transaction propagation 389

Required 389

RequiresNew 390

Nested 390

Advising transactional operations 390

Using @Transactional with AspectJ 393

17.6 Programmatic transaction management 394

Using the TransactionTemplate 394

Specifying transaction settings 396

Using the PlatformTransactionManager 396

17.7 Choosing between programmatic and declarative transaction management 397

17.8 Transaction bound event 397

17.9 Application server-specific integration 397

IBM WebSphere 398

Oracle WebLogic Server 398

17.10 Solutions to common problems 398

Use of the wrong transaction manager for a specific DataSource 398

17.11 Further Resources 398

18 DAO support 400

18.1 Introduction 400

18.2 Consistent exception hierarchy 400

18.3 Annotations used for configuring DAO or Repository classes 401

19 Data access with JDBC 403

19.1 Introduction to Spring Framework JDBC 403

Choosing an approach for JDBC database access 403

Trang 14

Package hierarchy 404

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

JdbcTemplate 405

Examples of JdbcTemplate class usage 405

JdbcTemplate best practices 407

NamedParameterJdbcTemplate 409

SQLExceptionTranslator 411

Executing statements 412

Running queries 413

Updating the database 414

Retrieving auto-generated keys 414

19.3 Controlling database connections 414

DataSource 414

DataSourceUtils 416

SmartDataSource 416

AbstractDataSource 416

SingleConnectionDataSource 416

DriverManagerDataSource 416

TransactionAwareDataSourceProxy 417

DataSourceTransactionManager 417

NativeJdbcExtractor 417

19.4 JDBC batch operations 418

Basic batch operations with the JdbcTemplate 418

Batch operations with a List of objects 419

Batch operations with multiple batches 420

19.5 Simplifying JDBC operations with the SimpleJdbc classes 420

Inserting data using SimpleJdbcInsert 421

Retrieving auto-generated keys using SimpleJdbcInsert 421

Specifying columns for a SimpleJdbcInsert 422

Using SqlParameterSource to provide parameter values 423

Calling a stored procedure with SimpleJdbcCall 423

Explicitly declaring parameters to use for a SimpleJdbcCall 425

How to define SqlParameters 426

Calling a stored function using SimpleJdbcCall 426

Returning ResultSet/REF Cursor from a SimpleJdbcCall 427

19.6 Modeling JDBC operations as Java objects 428

SqlQuery 428

MappingSqlQuery 429

SqlUpdate 430

StoredProcedure 430

19.7 Common problems with parameter and data value handling 433

Providing SQL type information for parameters 433

Handling BLOB and CLOB objects 434

Passing in lists of values for IN clause 435

Handling complex types for stored procedure calls 435

19.8 Embedded database support 437

Why use an embedded database? 437

Creating an embedded database using Spring XML 437

Trang 15

Selecting the embedded database type 438

Using HSQL 438

Using H2 438

Using Derby 438

Testing data access logic with an embedded database 438

Generating unique names for embedded databases 439

Extending the embedded database support 439

19.9 Initializing a DataSource 440

Initializing a database using Spring XML 440

Initialization of other components that depend on the database 441

20 Object Relational Mapping (ORM) Data Access 443

20.1 Introduction to ORM with Spring 443

20.2 General ORM integration considerations 444

Resource and transaction management 444

Exception translation 445

20.3 Hibernate 445

SessionFactory setup in a Spring container 445

Implementing DAOs based on plain Hibernate API 446

Declarative transaction demarcation 447

Programmatic transaction demarcation 449

Transaction management strategies 450

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 456

JdoDialect 457

20.5 JPA 458

Three options for JPA setup in a Spring environment 458

LocalEntityManagerFactoryBean 458

Obtaining an EntityManagerFactory from JNDI 458

LocalContainerEntityManagerFactoryBean 459

Dealing with multiple persistence units 461

Implementing DAOs based on plain JPA 461

Transaction Management 463

JpaDialect 464

21 Marshalling XML using O/X Mappers 465

21.1 Introduction 465

Ease of configuration 465

Consistent Interfaces 465

Consistent Exception Hierarchy 465

21.2 Marshaller and Unmarshaller 465

Marshaller 465

Unmarshaller 466

XmlMappingException 467

21.3 Using Marshaller and Unmarshaller 467

21.4 XML Schema-based Configuration 469

21.5 JAXB 469

Jaxb2Marshaller 469

Trang 16

XML Schema-based Configuration 470

21.6 Castor 470

CastorMarshaller 470

Mapping 471

XML Schema-based Configuration 471

21.7 XMLBeans 472

XmlBeansMarshaller 472

XML Schema-based Configuration 472

21.8 JiBX 472

JibxMarshaller 473

XML Schema-based Configuration 473

21.9 XStream 473

XStreamMarshaller 473

VI The Web 475

22 Web MVC framework 476

22.1 Introduction to Spring Web MVC framework 476

Features of Spring Web MVC 476

Pluggability of other MVC implementations 478

22.2 The DispatcherServlet 478

Special Bean Types In the WebApplicationContext 482

Default DispatcherServlet Configuration 483

DispatcherServlet Processing Sequence 483

22.3 Implementing Controllers 485

Defining a controller with @Controller 485

Mapping Requests With @RequestMapping 486

Composed @RequestMapping Variants 487

@Controller and AOP Proxying 488

New Support Classes for @RequestMapping methods in Spring MVC 3.1 488

URI Template Patterns 489

URI Template Patterns with Regular Expressions 490

Path Patterns 490

Path Pattern Comparison 491

Path Patterns with Placeholders 491

Suffix Pattern Matching 491

Suffix Pattern Matching and RFD 491

Matrix Variables 492

Consumable Media Types 494

Producible Media Types 494

Request Parameters and Header Values 495

HTTP HEAD and HTTP OPTIONS 495

Defining @RequestMapping handler methods 496

Supported method argument types 496

Supported method return types 498

Binding request parameters to method parameters with @RequestParam 499

Mapping the request body with the @RequestBody annotation 500

Mapping the response body with the @ResponseBody annotation 501

Creating REST Controllers with the @RestController annotation 502

Using HttpEntity 502

Using @ModelAttribute on a method 502

Trang 17

Using @SessionAttributes to store model attributes in the HTTP session

between requests 505

Using @SessionAttribute to access pre-existing global session attributes 506

Using @RequestAttribute to access request attributes 506

Working with "application/x-www-form-urlencoded" data 506

Mapping cookie values with the @CookieValue annotation 507

Mapping request header attributes with the @RequestHeader annotation 507

Method Parameters And Type Conversion 508

Customizing WebDataBinder initialization 508

Advising controllers with @ControllerAdvice and @RestControllerAdvice 509

Jackson Serialization View Support 510

Jackson JSONP Support 511

Asynchronous Request Processing 512

Exception Handling for Async Requests 513

Intercepting Async Requests 514

HTTP Streaming 514

HTTP Streaming With Server-Sent Events 514

HTTP Streaming Directly To The OutputStream 515

Configuring Asynchronous Request Processing 515

Testing Controllers 516

22.4 Handler mappings 516

Intercepting requests with a HandlerInterceptor 517

22.5 Resolving views 519

Resolving views with the ViewResolver interface 519

Chaining ViewResolvers 521

Redirecting to Views 521

RedirectView 522

The redirect: prefix 523

The forward: prefix 523

ContentNegotiatingViewResolver 523

22.6 Using flash attributes 525

22.7 Building URIs 526

Building URIs to Controllers and methods 527

Building URIs to Controllers and methods from views 528

22.8 Using locales 529

Obtaining Time Zone Information 529

AcceptHeaderLocaleResolver 529

CookieLocaleResolver 529

SessionLocaleResolver 530

LocaleChangeInterceptor 530

22.9 Using themes 530

Overview of themes 530

Defining themes 531

Theme resolvers 531

22.10 Spring’s multipart (file upload) support 532

Introduction 532

Using a MultipartResolver with Commons FileUpload 532

Using a MultipartResolver with Servlet 3.0 532

Handling a file upload in a form 533

Handling a file upload request from programmatic clients 534

Trang 18

22.11 Handling exceptions 535

HandlerExceptionResolver 535

@ExceptionHandler 535

Handling Standard Spring MVC Exceptions 536

Annotating Business Exceptions With @ResponseStatus 537

Customizing the Default Servlet Container Error Page 537

22.12 Web Security 538

22.13 Convention over configuration support 538

The Controller ControllerClassNameHandlerMapping 538

The Model ModelMap (ModelAndView) 539

The View - RequestToViewNameTranslator 540

22.14 HTTP caching support 541

Cache-Control HTTP header 542

HTTP caching support for static resources 542

Support for the Cache-Control, ETag and Last-Modified response headers in Controllers 543

Shallow ETag support 544

22.15 Code-based Servlet container initialization 545

22.16 Configuring Spring MVC 546

Enabling the MVC Java Config or the MVC XML Namespace 547

Customizing the Provided Configuration 548

Conversion and Formatting 549

Validation 550

Interceptors 551

Content Negotiation 552

View Controllers 553

View Resolvers 553

Serving of Resources 554

Falling Back On the "Default" Servlet To Serve Resources 557

Path Matching 558

Message Converters 559

Advanced Customizations with MVC Java Config 560

Advanced Customizations with the MVC Namespace 561

23 View technologies 562

23.1 Introduction 562

23.2 Thymeleaf 562

23.3 Groovy Markup Templates 562

Configuration 562

Example 563

23.4 Velocity & FreeMarker 563

Dependencies 563

Context configuration 563

Creating templates 564

Advanced configuration 564

velocity.properties 564

FreeMarker 565

Bind support and form handling 565

The bind macros 565

Simple binding 566

Trang 19

HTML escaping and XHTML compliance 570

23.5 JSP & JSTL 570

View resolvers 571

'Plain-old' JSPs versus JSTL 571

Additional tags facilitating development 571

Using Spring’s form tag library 571

Configuration 572

The form tag 572

The input tag 573

The checkbox tag 573

The checkboxes tag 575

The radiobutton tag 576

The radiobuttons tag 576

The password tag 576

The select tag 576

The option tag 577

The options tag 577

The textarea tag 578

The hidden tag 578

The errors tag 578

HTTP Method Conversion 580

HTML5 Tags 581

23.6 Script templates 581

Dependencies 582

How to integrate script based templating 582

23.7 XML Marshalling View 584

23.8 Tiles 584

Dependencies 584

How to integrate Tiles 584

UrlBasedViewResolver 585

ResourceBundleViewResolver 585

SimpleSpringPreparerFactory and SpringBeanPreparerFactory 586

23.9 XSLT 586

My First Words 587

Bean definitions 587

Standard MVC controller code 587

Document transformation 588

23.10 Document views (PDF/Excel) 588

Introduction 588

Configuration and setup 589

Document view definitions 589

Controller code 589

Subclassing for Excel views 589

Subclassing for PDF views 591

23.11 JasperReports 591

Dependencies 591

Configuration 591

Configuring the ViewResolver 592

Configuring the Views 592

About Report Files 592

Trang 20

Using JasperReportsMultiFormatView 592

Populating the ModelAndView 593

Working with Sub-Reports 594

Configuring Sub-Report Files 594

Configuring Sub-Report Data Sources 595

Configuring Exporter Parameters 595

23.12 Feed Views 596

23.13 JSON Mapping View 596

23.14 XML Mapping View 597

24 Integrating with other web frameworks 598

24.1 Introduction 598

24.2 Common configuration 599

24.3 JavaServer Faces 1.2 600

SpringBeanFacesELResolver (JSF 1.2+) 600

FacesContextUtils 600

24.4 Apache Struts 2.x 600

24.5 Tapestry 5.x 601

24.6 Further Resources 601

25 Portlet MVC Framework 602

25.1 Introduction 602

Controllers - The C in MVC 603

Views - The V in MVC 603

Web-scoped beans 603

25.2 The DispatcherPortlet 603

25.3 The ViewRendererServlet 605

25.4 Controllers 606

AbstractController and PortletContentGenerator 607

Other simple controllers 608

Command Controllers 608

PortletWrappingController 609

25.5 Handler mappings 609

PortletModeHandlerMapping 610

ParameterHandlerMapping 610

PortletModeParameterHandlerMapping 611

Adding HandlerInterceptors 611

HandlerInterceptorAdapter 612

ParameterMappingInterceptor 612

25.6 Views and resolving them 612

25.7 Multipart (file upload) support 612

Using the PortletMultipartResolver 613

Handling a file upload in a form 613

25.8 Handling exceptions 617

25.9 Annotation-based controller configuration 617

Setting up the dispatcher for annotation support 617

Defining a controller with @Controller 618

Mapping requests with @RequestMapping 618

Supported handler method arguments 620

Binding request parameters to method parameters with @RequestParam 622

Providing a link to data from the model with @ModelAttribute 622

Trang 21

Customizing WebDataBinder initialization 623

Customizing data binding with @InitBinder 623

Configuring a custom WebBindingInitializer 624

25.10 Portlet application deployment 624

26 WebSocket Support 625

26.1 Introduction 625

WebSocket Fallback Options 625

A Messaging Architecture 626

Sub-Protocol Support in WebSocket 626

Should I Use WebSocket? 626

26.2 WebSocket API 627

Create and Configure a WebSocketHandler 627

Customizing the WebSocket Handshake 628

WebSocketHandler Decoration 629

Deployment Considerations 629

Configuring the WebSocket Engine 630

Configuring allowed origins 632

26.3 SockJS Fallback Options 633

Overview of SockJS 633

Enable SockJS 634

HTTP Streaming in IE 8, 9: Ajax/XHR vs IFrame 635

Heartbeat Messages 636

Servlet 3 Async Requests 636

CORS Headers for SockJS 637

SockJS Client 637

26.4 STOMP Over WebSocket Messaging Architecture 639

Overview of STOMP 639

Enable STOMP over WebSocket 640

Flow of Messages 642

Annotation Message Handling 644

Sending Messages 646

Simple Broker 646

Full-Featured Broker 646

Connections To Full-Featured Broker 647

Using Dot as Separator in @MessageMapping Destinations 648

Authentication 649

User Destinations 650

Listening To ApplicationContext Events and Intercepting Messages 651

STOMP Client 652

WebSocket Scope 654

Configuration and Performance 655

Runtime Monitoring 658

Testing Annotated Controller Methods 659

27 CORS Support 660

27.1 Introduction 660

27.2 Controller method CORS configuration 660

27.3 Global CORS configuration 661

JavaConfig 661

XML namespace 662

27.4 Advanced Customization 662

Trang 22

27.5 Filter based CORS support 662VII Integration 664

28 Remoting and web services using Spring 66528.1 Introduction 66528.2 Exposing services using RMI 666Exporting the service using the RmiServiceExporter 666Linking in the service at the client 66728.3 Using Hessian or Burlap to remotely call services via HTTP 667Wiring up the DispatcherServlet for Hessian and co 667Exposing your beans by using the HessianServiceExporter 668Linking in the service on the client 668Using Burlap 669Applying HTTP basic authentication to a service exposed through Hessian or

Burlap 66928.4 Exposing services using HTTP invokers 669Exposing the service object 669Linking in the service at the client 67028.5 Web services 671Exposing servlet-based web services using JAX-WS 671Exporting standalone web services using JAX-WS 672Exporting web services using the JAX-WS RI’s Spring support 673Accessing web services using JAX-WS 67328.6 JMS 674Server-side configuration 675Client-side configuration 67528.7 AMQP 67628.8 Auto-detection is not implemented for remote interfaces 67628.9 Considerations when choosing a technology 67628.10 Accessing RESTful services on the Client 677RestTemplate 677Working with the URI 680Dealing with request and response headers 681Jackson JSON Views support 681HTTP Message Conversion 681StringHttpMessageConverter 682FormHttpMessageConverter 682ByteArrayHttpMessageConverter 682MarshallingHttpMessageConverter 682MappingJackson2HttpMessageConverter 682MappingJackson2XmlHttpMessageConverter 683SourceHttpMessageConverter 683BufferedImageHttpMessageConverter 683Async RestTemplate 683

29 Enterprise JavaBeans (EJB) integration 68529.1 Introduction 68529.2 Accessing EJBs 685Concepts 685Accessing local SLSBs 685Accessing remote SLSBs 687

Trang 23

29.3 Using Spring’s EJB implementation support classes 688EJB 3 injection interceptor 688

30 JMS (Java Message Service) 68930.1 Introduction 68930.2 Using Spring JMS 689JmsTemplate 689Connections 690Caching Messaging Resources 690SingleConnectionFactory 691CachingConnectionFactory 691Destination Management 691Message Listener Containers 692SimpleMessageListenerContainer 692DefaultMessageListenerContainer 693Transaction management 69330.3 Sending a Message 694Using Message Converters 695SessionCallback and ProducerCallback 69630.4 Receiving a message 696Synchronous Reception 696Asynchronous Reception - Message-Driven POJOs 696the SessionAwareMessageListener interface 697the MessageListenerAdapter 697Processing messages within transactions 69930.5 Support for JCA Message Endpoints 70030.6 Annotation-driven listener endpoints 701Enable listener endpoint annotations 702Programmatic endpoints registration 702Annotated endpoint method signature 703Response management 70430.7 JMS namespace support 705

31 JMX 71031.1 Introduction 71031.2 Exporting your beans to JMX 710Creating an MBeanServer 712Reusing an existing MBeanServer 712Lazy-initialized MBeans 713Automatic registration of MBeans 713Controlling the registration behavior 71331.3 Controlling the management interface of your beans 714the MBeanInfoAssembler Interface 715Using Source-Level Metadata (Java annotations) 715Source-Level Metadata Types 717the AutodetectCapableMBeanInfoAssembler interface 718Defining management interfaces using Java interfaces 719Using MethodNameBasedMBeanInfoAssembler 72031.4 Controlling the ObjectNames for your beans 721Reading ObjectNames from Properties 721Using the MetadataNamingStrategy 722Configuring annotation based MBean export 722

Trang 24

31.5 JSR-160 Connectors 723Server-side Connectors 723Client-side Connectors 724JMX over Burlap/Hessian/SOAP 72431.6 Accessing MBeans via Proxies 72431.7 Notifications 725Registering Listeners for Notifications 725Publishing Notifications 72831.8 Further Resources 729

32 JCA CCI 73132.1 Introduction 73132.2 Configuring CCI 731Connector configuration 731ConnectionFactory configuration in Spring 732Configuring CCI connections 732Using a single CCI connection 73332.3 Using Spring’s CCI access support 734Record conversion 734the CciTemplate 734DAO support 736Automatic output record generation 737Summary 737Using a CCI Connection and Interaction directly 738Example for CciTemplate usage 73832.4 Modeling CCI access as operation objects 740MappingRecordOperation 740MappingCommAreaOperation 741Automatic output record generation 742Summary 742Example for MappingRecordOperation usage 742Example for MappingCommAreaOperation usage 74432.5 Transactions 746

33 Email 74733.1 Introduction 74733.2 Usage 747Basic MailSender and SimpleMailMessage usage 748Using the JavaMailSender and the MimeMessagePreparator 74833.3 Using the JavaMail MimeMessageHelper 749Sending attachments and inline resources 750Attachments 750Inline resources 750Creating email content using a templating library 751

A Velocity-based example 751

34 Task Execution and Scheduling 75434.1 Introduction 75434.2 The Spring TaskExecutor abstraction 754TaskExecutor types 754Using a TaskExecutor 75534.3 The Spring TaskScheduler abstraction 756

Trang 25

Trigger implementations 757TaskScheduler implementations 75834.4 Annotation Support for Scheduling and Asynchronous Execution 758Enable scheduling annotations 758The @Scheduled annotation 759The @Async annotation 760Executor qualification with @Async 761Exception management with @Async 76134.5 The task namespace 762The 'scheduler' element 762The 'executor' element 762The 'scheduled-tasks' element 76334.6 Using the Quartz Scheduler 764Using the JobDetailFactoryBean 764Using the MethodInvokingJobDetailFactoryBean 765Wiring up jobs using triggers and the SchedulerFactoryBean 765

35 Dynamic language support 76735.1 Introduction 76735.2 A first example 76735.3 Defining beans that are backed by dynamic languages 769Common concepts 769The <lang:language/> element 770Refreshable beans 770Inline dynamic language source files 772Understanding Constructor Injection in the context of dynamic-language-

backed beans 773JRuby beans 774Groovy beans 775Customizing Groovy objects via a callback 776BeanShell beans 77835.4 Scenarios 779Scripted Spring MVC Controllers 779Scripted Validators 78035.5 Bits and bobs 780AOP - advising scripted beans 780Scoping 78135.6 Further Resources 781

36 Cache Abstraction 78236.1 Introduction 78236.2 Understanding the cache abstraction 78236.3 Declarative annotation-based caching 783

@Cacheable annotation 783Default Key Generation 784Custom Key Generation Declaration 784Default Cache Resolution 785Custom cache resolution 785Synchronized caching 786Conditional caching 786Available caching SpEL evaluation context 787

@CachePut annotation 788

Trang 26

@CacheEvict annotation 788

@Caching annotation 789

@CacheConfig annotation 789Enable caching annotations 790Using custom annotations 79236.4 JCache (JSR-107) annotations 793Features summary 793Enabling JSR-107 support 79436.5 Declarative XML-based caching 79536.6 Configuring the cache storage 795JDK ConcurrentMap-based Cache 796Ehcache-based Cache 796Caffeine Cache 796Guava Cache 797GemFire-based Cache 797JSR-107 Cache 797Dealing with caches without a backing store 79836.7 Plugging-in different back-end caches 79836.8 How can I set the TTL/TTI/Eviction policy/XXX feature? 798VIII Appendices 799

37 Migrating to Spring Framework 4.x 800

38 Spring Annotation Programming Model 801

39 Classic Spring Usage 80239.1 Classic ORM usage 802Hibernate 802The HibernateTemplate 802Implementing Spring-based DAOs without callbacks 80339.2 JMS Usage 804JmsTemplate 805Asynchronous Message Reception 805Connections 805Transaction Management 805

40 Classic Spring AOP Usage 80640.1 Pointcut API in Spring 806Concepts 806Operations on pointcuts 807AspectJ expression pointcuts 807Convenience pointcut implementations 807Static pointcuts 807Dynamic pointcuts 808Pointcut superclasses 809Custom pointcuts 80940.2 Advice API in Spring 809Advice lifecycles 809Advice types in Spring 810Interception around advice 810Before advice 810Throws advice 811After Returning advice 812

Trang 27

40.3 Advisor API in Spring 81540.4 Using the ProxyFactoryBean to create AOP proxies 816Basics 816JavaBean properties 816JDK- and CGLIB-based proxies 817Proxying interfaces 818Proxying classes 820Using 'global' advisors 82140.5 Concise proxy definitions 82140.6 Creating AOP proxies programmatically with the ProxyFactory 82240.7 Manipulating advised objects 82240.8 Using the "autoproxy" facility 824Autoproxy bean definitions 824BeanNameAutoProxyCreator 824DefaultAdvisorAutoProxyCreator 825AbstractAdvisorAutoProxyCreator 826Using metadata-driven auto-proxying 82640.9 Using TargetSources 828Hot swappable target sources 828Pooling target sources 829Prototype target sources 830ThreadLocal target sources 83040.10 Defining new Advice types 83140.11 Further resources 831

41 XML Schema-based configuration 83241.1 Introduction 83241.2 XML Schema-based configuration 832Referencing the schemas 832the util schema 833

<jee:jndi-lookup/> (simple) 839

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

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

<jee:jndi-lookup/> (complex) 840

<jee:local-slsb/> (simple) 841

<jee:local-slsb/> (complex) 841

<jee:remote-slsb/> 841the lang schema 842the jms schema 842the tx (transaction) schema 843the aop schema 843the context schema 844

<property-placeholder/> 844

<annotation-config/> 844

Trang 28

<component-scan/> 844

<load-time-weaver/> 845

<spring-configured/> 845

<mbean-export/> 845the tool schema 845the jdbc schema 845the cache schema 845the beans schema 846

42 Extensible XML authoring 84742.1 Introduction 84742.2 Authoring the schema 84742.3 Coding a NamespaceHandler 84842.4 BeanDefinitionParser 84942.5 Registering the handler and the schema 850'META-INF/spring.handlers' 850'META-INF/spring.schemas' 85142.6 Using a custom extension in your Spring XML configuration 85142.7 Meatier examples 851Nesting custom tags within custom tags 851Custom attributes on 'normal' elements 85542.8 Further Resources 857

43 spring JSP Tag Library 85843.1 Introduction 85843.2 The argument tag 85843.3 The bind tag 85843.4 The escapeBody tag 85943.5 The eval tag 85943.6 The hasBindErrors tag 86043.7 The htmlEscape tag 86043.8 The message tag 86043.9 The nestedPath tag 86143.10 The param tag 86243.11 The theme tag 86243.12 The transform tag 86343.13 The url tag 863

44 spring-form JSP Tag Library 86544.1 Introduction 86544.2 The button tag 86544.3 The checkbox tag 86644.4 The checkboxes tag 86744.5 The errors tag 86844.6 The form tag 86944.7 The hidden tag 87044.8 The input tag 87144.9 The label tag 87244.10 The option tag 87344.11 The options tag 87444.12 The password tag 87544.13 The radiobutton tag 876

Trang 29

44.15 The select tag 87944.16 The textarea tag 880

Trang 30

The Spring Framework is a lightweight solution and a potential one-stop-shop for building yourenterprise-ready applications However, Spring is modular, allowing you to use only those parts that youneed, without having to bring in the rest You can use the IoC container, with any web framework ontop, but you can also use only the Hibernate integration code or the JDBC abstraction layer The SpringFramework supports declarative transaction management, remote access to your logic through RMI orweb services, and various options for persisting your data It offers a full-featured MVC framework, andenables you to integrate AOP transparently into your software.

Spring is designed to be non-intrusive, meaning that your domain logic code generally has nodependencies on the framework itself In your integration layer (such as the data access layer), somedependencies on the data access technology and the Spring libraries will exist However, it should beeasy to isolate these dependencies from the rest of your code base

This document is a reference guide to Spring Framework features If you have any requests, comments,

or questions on this document, please post them on the user mailing list Questions on the Frameworkitself should be asked on StackOverflow (see https://spring.io/questions)

Trang 31

1 Getting Started with Spring

This reference guide provides detailed information about the Spring Framework It providescomprehensive documentation for all features, as well as some background about the underlying

concepts (such as "Dependency Injection") that Spring has embraced.

If you are just getting started with Spring, you may want to begin using the Spring Framework bycreating a Spring Boot based application Spring Boot provides a quick (and opinionated) way to create

a production-ready Spring based application It is based on the Spring Framework, favors conventionover configuration, and is designed to get you up and running as quickly as possible

You can use start.spring.io to generate a basic project or follow one of the "Getting Started" guides likethe Getting Started Building a RESTful Web Service one As well as being easier to digest, these guides

are very task focused, and most of them are based on Spring Boot They also cover other projects from

the Spring portfolio that you might want to consider when solving a particular problem

Trang 32

2 Introduction to the Spring Framework

The Spring Framework is a Java platform that provides comprehensive infrastructure support fordeveloping Java applications Spring handles the infrastructure so you can focus on your application.Spring enables you to build applications from "plain old Java objects" (POJOs) and to apply enterpriseservices non-invasively to POJOs This capability applies to the Java SE programming model and tofull and partial Java EE

Examples of how you, as an application developer, can benefit from the Spring platform:

• Make a Java method execute in a database transaction without having to deal with transaction APIs

• Make a local Java method a remote procedure without having to deal with remote APIs

• Make a local Java method a management operation without having to deal with JMX APIs

• Make a local Java method a message handler without having to deal with JMS APIs

2.1 Dependency Injection and Inversion of Control

A Java application — a loose term that runs the gamut from constrained, embedded applications to n-tier,server-side enterprise applications — typically consists of objects that collaborate to form the application

proper Thus the objects in an application have dependencies on each other.

Although the Java platform provides a wealth of application development functionality, it lacks themeans to organize the basic building blocks into a coherent whole, leaving that task to architects and

developers Although you can use design patterns such as Factory, Abstract Factory, Builder, Decorator, and Service Locator to compose the various classes and object instances that make up an application,

these patterns are simply that: best practices given a name, with a description of what the pattern does,where to apply it, the problems it addresses, and so forth Patterns are formalized best practices that

you must implement yourself in your application.

The Spring Framework Inversion of Control (IoC) component addresses this concern by providing a

formalized means of composing disparate components into a fully working application ready for use.The Spring Framework codifies formalized design patterns as first-class objects that you can integrateinto your own application(s) Numerous organizations and institutions use the Spring Framework in this

manner to engineer robust, maintainable applications.

Background

"The question is, what aspect of control are [they] inverting?" Martin Fowler posed this question

about Inversion of Control (IoC) on his site in 2004 Fowler suggested renaming the principle to

make it more self-explanatory and came up with Dependency Injection.

2.2 Modules

The Spring Framework consists of features organized into about 20 modules These modules aregrouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming),

Trang 33

Figure 2.1 Overview of the Spring Framework

The following sections list the available modules for each feature along with their artifact names and the

topics they cover Artifact names correlate to artifact IDs used in Dependency Management tools

to decouple the configuration and specification of dependencies from your actual program logic.The Context (spring-context) module builds on the solid base provided by the Core and Beans

modules: it is a means to access objects in a framework-style manner that is similar to a JNDIregistry The Context module inherits its features from the Beans module and adds support forinternationalization (using, for example, resource bundles), event propagation, resource loading, and thetransparent creation of contexts by, for example, a Servlet container The Context module also supportsJava EE features such as EJB, JMX, and basic remoting The ApplicationContext interface isthe focal point of the Context module spring-context-support provides support for integratingcommon third-party libraries into a Spring application context for caching (EhCache, Guava, JCache),mailing (JavaMail), scheduling (CommonJ, Quartz) and template engines (FreeMarker, JasperReports,Velocity)

The spring-expression module provides a powerful Expression Language for querying andmanipulating an object graph at runtime It is an extension of the unified expression language (unifiedEL) as specified in the JSP 2.1 specification The language supports setting and getting property values,property assignment, method invocation, accessing the content of arrays, collections and indexers,

Trang 34

logical and arithmetic operators, named variables, and retrieval of objects by name from Spring’s IoCcontainer It also supports list projection and selection as well as common list aggregations.

AOP and Instrumentation

The spring-aop module provides an AOP Alliance-compliant aspect-oriented programmingimplementation allowing you to define, for example, method interceptors and pointcuts to cleanlydecouple code that implements functionality that should be separated Using source-level metadatafunctionality, you can also incorporate behavioral information into your code, in a manner similar to that

of NET attributes

The separate spring-aspects module provides integration with AspectJ

The spring-instrument module provides class instrumentation support and classloaderimplementations to be used in certain application servers The spring-instrument-tomcat modulecontains Spring’s instrumentation agent for Tomcat

Messaging

Spring Framework 4 includes a spring-messaging module with key abstractions from the Spring

Integration project such as Message, MessageChannel, MessageHandler, and others to serve as afoundation for messaging-based applications The module also includes a set of annotations for mappingmessages to methods, similar to the Spring MVC annotation based programming model

Data Access/Integration

The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS, and Transaction modules.

The spring-jdbc module provides a JDBC-abstraction layer that removes the need to do tediousJDBC coding and parsing of database-vendor specific error codes

The spring-tx module supports programmatic and declarative transaction management for classes

that implement special interfaces and for all your POJOs (Plain Old Java Objects).

The spring-orm module provides integration layers for popular object-relational mapping APIs,including JPA, JDO, and Hibernate Using the spring-orm module you can use all of these O/R-mapping frameworks in combination with all of the other features Spring offers, such as the simpledeclarative transaction management feature mentioned previously

The spring-oxm module provides an abstraction layer that supports Object/XML mapping

implementations such as JAXB, Castor, XMLBeans, JiBX and XStream

The spring-jms module (Java Messaging Service) contains features for producing and consumingmessages Since Spring Framework 4.1, it provides integration with the spring-messaging module

Trang 35

The spring-webmvc module (also known as the Web-Servlet module) contains Spring’s view-controller (MVC) and REST Web Services implementation for web applications Spring’s MVCframework provides a clean separation between domain model code and web forms and integrates withall of the other features of the Spring Framework.

model-The spring-webmvc-portlet module (also known as the Web-Portlet module) provides the MVCimplementation to be used in a Portlet environment and mirrors the functionality of the spring-webmvcmodule

Test

The spring-test module supports the unit testing and integration testing of Spring components withJUnit or TestNG It provides consistent loading of Spring ApplicationContexts and caching of thosecontexts It also provides mock objects that you can use to test your code in isolation

2.3 Usage scenarios

The building blocks described previously make Spring a logical choice in many scenarios, fromembedded applications that run on resource-constrained devices to full-fledged enterprise applicationsthat use Spring’s transaction management functionality and web framework integration

Figure 2.2 Typical full-fledged Spring web application

Spring’s declarative transaction management features make the web application fully transactional,just as it would be if you used EJB container-managed transactions All your custom business logiccan be implemented with simple POJOs and managed by Spring’s IoC container Additional servicesinclude support for sending email and validation that is independent of the web layer, which lets youchoose where to execute validation rules Spring’s ORM support is integrated with JPA, Hibernate andJDO; for example, when using Hibernate, you can continue to use your existing mapping files andstandard Hibernate SessionFactory configuration Form controllers seamlessly integrate the web-

Trang 36

layer with the domain model, removing the need for ActionForms or other classes that transform HTTPparameters to values for your domain model.

Figure 2.3 Spring middle-tier using a third-party web framework

Sometimes circumstances do not allow you to completely switch to a different framework The Spring

Framework does not force you to use everything within it; it is not an all-or-nothing solution Existing

front-ends built with Struts, Tapestry, JSF or other UI frameworks can be integrated with a based middle-tier, which allows you to use Spring transaction features You simply need to wire up yourbusiness logic using an ApplicationContext and use a WebApplicationContext to integrateyour web layer

Trang 37

Spring-Figure 2.4 Remoting usage scenario

When you need to access existing code through web services, you can use Spring’s Hessian-,Burlap-, Rmi- or JaxRpcProxyFactory classes Enabling remote access to existing applications

is not difficult

Figure 2.5 EJBs - Wrapping existing POJOs

The Spring Framework also provides an access and abstraction layer for Enterprise JavaBeans,enabling you to reuse your existing POJOs and wrap them in stateless session beans for use in scalable,fail-safe web applications that might need declarative security

Trang 38

Dependency Management and Naming Conventions

Dependency management and dependency injection are different things To get those nice features ofSpring into your application (like dependency injection) you need to assemble all the libraries needed (jarfiles) and get them onto your classpath at runtime, and possibly at compile time These dependenciesare not virtual components that are injected, but physical resources in a file system (typically) Theprocess of dependency management involves locating those resources, storing them and adding them

to classpaths Dependencies can be direct (e.g my application depends on Spring at runtime), or indirect(e.g my application depends on commons-dbcp which depends on commons-pool) The indirectdependencies are also known as "transitive" and it is those dependencies that are hardest to identifyand manage

If you are going to use Spring you need to get a copy of the jar libraries that comprise the pieces ofSpring that you need To make this easier Spring is packaged as a set of modules that separate thedependencies as much as possible, so for example if you don’t want to write a web application youdon’t need the spring-web modules To refer to Spring library modules in this guide we use a shorthandnaming convention spring-* or spring-*.jar, where * represents the short name for the module(e.g spring-core, spring-webmvc, spring-jms, etc.) The actual jar file name that you use is

normally the module name concatenated with the version number (e.g spring-core-4.3.4.RELEASE.jar).

Each release of the Spring Framework will publish artifacts to the following places:

• Maven Central, which is the default repository that Maven queries, and does not require any specialconfiguration to use Many of the common libraries that Spring depends on also are availablefrom Maven Central and a large section of the Spring community uses Maven for dependencymanagement, so this is convenient for them The names of the jars here are in the form spring-*-

<version>.jar and the Maven groupId is org.springframework

• In a public Maven repository hosted specifically for Spring In addition to the final GA releases, thisrepository also hosts development snapshots and milestones The jar file names are in the same form

as Maven Central, so this is a useful place to get development versions of Spring to use with otherlibraries deployed in Maven Central This repository also contains a bundle distribution zip file thatcontains all Spring jars bundled together for easy download

So the first thing you need to decide is how to manage your dependencies: we generally recommend theuse of an automated system like Maven, Gradle or Ivy, but you can also do it manually by downloadingall the jars yourself

You will find bellow the list of Spring artifacts For a more complete description of each modules, seeSection 2.2, “Modules”

Table 2.1 Spring Framework Artifacts

org.springframework spring-aop Proxy-based AOP supportorg.springframework spring-aspects AspectJ based aspects

org.springframework spring-beans Beans support, including

Groovyorg.springframework spring-context Application context runtime,

including scheduling and

Trang 39

GroupId ArtifactId Description

org.springframework spring-context-support Support classes for integrating

common third-party librariesinto a Spring application contextorg.springframework spring-core Core utilities, used by many

other Spring modulesorg.springframework spring-expression Spring Expression Language

(SpEL)org.springframework spring-instrument Instrumentation agent for JVM

bootstrappingorg.springframework spring-instrument-tomcat Instrumentation agent for

Tomcatorg.springframework spring-jdbc JDBC support package,

including DataSource setup andJDBC access support

org.springframework spring-jms JMS support package, including

helper classes to send andreceive JMS messagesorg.springframework spring-messaging Support for messaging

architectures and protocolsorg.springframework spring-orm Object/Relational Mapping,

including JPA and Hibernatesupport

org.springframework spring-oxm Object/XML Mapping

org.springframework spring-test Support for unit testing and

integration testing Springcomponents

org.springframework spring-tx Transaction infrastructure,

including DAO support and JCAintegration

org.springframework spring-web Web support packages,

including client and webremoting

org.springframework spring-webmvc REST Web Services and

model-view-controllerimplementation for webapplications

org.springframework spring-webmvc-portlet MVC implementation to be used

in a Portlet environment

Trang 40

GroupId ArtifactId Description

org.springframework spring-websocket WebSocket and SockJS

implementations, includingSTOMP support

Spring Dependencies and Depending on Spring

Although Spring provides integration and support for a huge range of enterprise and other external tools,

it intentionally keeps its mandatory dependencies to an absolute minimum: you shouldn’t have to locateand download (even automatically) a large number of jar libraries in order to use Spring for simple usecases For basic dependency injection there is only one mandatory external dependency, and that isfor logging (see below for a more detailed description of logging options)

Next we outline the basic steps needed to configure an application that depends on Spring, first withMaven and then with Gradle and finally using Ivy In all cases, if anything is unclear, refer to thedocumentation of your dependency management system, or look at some sample code - Spring itselfuses Gradle to manage dependencies when it is building, and our samples mostly use Gradle or Maven

Maven Dependency Management

If you are using Maven for dependency management you don’t even need to supply the loggingdependency explicitly For example, to create an application context and use dependency injection toconfigure an application, your Maven dependencies will look like this:

<dependencies>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>4.3.4.RELEASE</version>

<scope>runtime</scope>

<repositories>

<repository>

<id>io.spring.repo.maven.release</id>

<url>http://repo.spring.io/release/</url>

<snapshots><enabled>false</enabled></snapshots>

<id>io.spring.repo.maven.milestone</id>

<url>http://repo.spring.io/milestone/</url>

<snapshots><enabled>false</enabled></snapshots>

Ngày đăng: 30/11/2017, 23:30

TỪ KHÓA LIÊN QUAN

w