• Tidak ada hasil yang ditemukan

spring framework reference

N/A
N/A
Protected

Academic year: 2017

Membagikan "spring framework reference"

Copied!
913
0
0

Teks penuh

(1)

4.3.9.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 ,

(2)
(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. Framework 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

Using Log4j 1.2 or 2.x ... 14

Avoiding Commons Logging ... 15

Using SLF4J with Log4j or Logback ... 15

Using JUL (java.util.logging) ... 16

Commons Logging on WebSphere ... 17

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 ... 29

5.3. JMS Improvements ... 29

(4)

5.5. WebSocket Messaging Improvements ... 30

5.6. Testing Improvements ... 31

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 ... 34

6.4. JMS Improvements ... 34

6.5. Web Improvements ... 34

6.6. WebSocket Messaging Improvements ... 35

6.7. Testing Improvements ... 35

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

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

(5)

7.5. Bean scopes ... 70

The singleton scope ... 71

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

(6)

Providing a scope for autodetected components ... 117

Providing qualifier metadata with annotations ... 118

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 ... 144

Default profile ... 144

PropertySource abstraction ... 145

@PropertySource ... 146

Placeholder resolution in statements ... 147

7.14. Registering a LoadTimeWeaver ... 147

7.15. Additional Capabilities of the ApplicationContext ... 148

Internationalization using MessageSource ... 148

Standard and Custom Events ... 151

Annotation-based Event Listeners ... 154

Asynchronous Listeners ... 156

Ordering Listeners ... 156

Generic Events ... 156

Convenient access to low-level resources ... 157

(7)

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

7.16. The BeanFactory ... 158

BeanFactory or ApplicationContext? ... 159

Glue code and the evil singleton ... 160

8. Resources ... 161

8.1. Introduction ... 161

8.2. The Resource interface ... 161

8.3. Built-in Resource implementations ... 162

UrlResource ... 162

ClassPathResource ... 162

FileSystemResource ... 163

ServletContextResource ... 163

InputStreamResource ... 163

ByteArrayResource ... 163

8.4. The ResourceLoader ... 163

8.5. The ResourceLoaderAware interface ... 164

8.6. Resources as dependencies ... 165

8.7. Application contexts and Resource paths ... 165

Constructing application contexts ... 165

Constructing ClassPathXmlApplicationContext instances - shortcuts ... 166

Wildcards in application context constructor resource paths ... 166

Ant-style Patterns ... 167

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

Other notes relating to wildcards ... 168

FileSystemResource caveats ... 168

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

9.1. Introduction ... 170

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

9.3. Resolving codes to error messages ... 172

9.4. Bean manipulation and the BeanWrapper ... 173

Setting and getting basic and nested properties ... 173

Built-in PropertyEditor implementations ... 175

Registering additional custom PropertyEditors ... 178

9.5. Spring Type Conversion ... 180

Converter SPI ... 180

ConverterFactory ... 181

GenericConverter ... 181

ConditionalGenericConverter ... 182

ConversionService API ... 182

Configuring a ConversionService ... 183

Using a ConversionService programmatically ... 184

9.6. Spring Field Formatting ... 184

Formatter SPI ... 185

Annotation-driven Formatting ... 186

Format Annotation API ... 187

FormatterRegistry SPI ... 187

FormatterRegistrar SPI ... 188

Configuring Formatting in Spring MVC ... 188

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

(8)

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

Configuring a Bean Validation Provider ... 190

Injecting a Validator ... 191

Configuring Custom Constraints ... 191

Spring-driven Method Validation ... 192

Additional Configuration Options ... 192

Configuring a DataBinder ... 192

Spring MVC 3 Validation ... 193

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

10.1. Introduction ... 194

10.2. Feature Overview ... 194

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

The EvaluationContext interface ... 197

Type Conversion ... 197

Parser configuration ... 198

SpEL compilation ... 198

Compiler configuration ... 199

Compiler limitations ... 200

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

XML based configuration ... 200

Annotation-based configuration ... 201

10.5. Language Reference ... 202

Literal expressions ... 202

Properties, Arrays, Lists, Maps, Indexers ... 202

Inline lists ... 203

Inline Maps ... 203

Array construction ... 204

Methods ... 204

Operators ... 204

Relational operators ... 204

Logical operators ... 205

Mathematical operators ... 205

Assignment ... 206

Types ... 206

Constructors ... 206

Variables ... 207

The #this and #root variables ... 207

Functions ... 207

Expression templating ... 210

10.6. Classes used in the examples ... 211

11. Aspect Oriented Programming with Spring ... 215

11.1. Introduction ... 215

AOP concepts ... 215

(9)

AOP Proxies ... 218

11.2. @AspectJ support ... 218

Enabling @AspectJ Support ... 218

Enabling @AspectJ Support with Java configuration ... 218

Enabling @AspectJ Support with XML configuration ... 219

Declaring an aspect ... 219

Declaring a pointcut ... 220

Supported Pointcut Designators ... 220

Combining pointcut expressions ... 222

Sharing common pointcut definitions ... 222

Examples ... 224

Aspect instantiation models ... 234

Example ... 235

11.3. Schema-based AOP support ... 237

Declaring an aspect ... 237

Aspect instantiation models ... 244

Advisors ... 244

Example ... 245

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

Spring AOP or full AspectJ? ... 247

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

11.5. Mixing aspect types ... 248

11.6. Proxying mechanisms ... 249

Understanding AOP proxies ... 249

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

11.8. Using AspectJ with Spring applications ... 252

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

Unit testing @Configurable objects ... 255

Working with multiple application contexts ... 255

(10)

Configuring AspectJ aspects using Spring IoC ... 256

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

A first example ... 257

12.2. Pointcut API in Spring ... 266

Concepts ... 266

Operations on pointcuts ... 267

AspectJ expression pointcuts ... 267

Convenience pointcut implementations ... 267

Static pointcuts ... 267

Interception around advice ... 269

Before advice ... 270

Throws advice ... 271

After Returning advice ... 272

Introduction advice ... 273

12.4. Advisor API in Spring ... 275

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

Basics ... 275

JavaBean properties ... 276

JDK- and CGLIB-based proxies ... 277

Proxying interfaces ... 277

Proxying classes ... 279

Using 'global' advisors ... 280

12.6. Concise proxy definitions ... 280

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

12.8. Manipulating advised objects ... 282

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

Autoproxy bean definitions ... 283

BeanNameAutoProxyCreator ... 283

DefaultAdvisorAutoProxyCreator ... 284

AbstractAdvisorAutoProxyCreator ... 285

Using metadata-driven auto-proxying ... 285

12.10. Using TargetSources ... 287

Hot swappable target sources ... 287

Pooling target sources ... 287

Prototype target sources ... 289

(11)

12.11. Defining new Advice types ... 289

12.12. Further resources ... 290

IV. Testing ... 291

13. Introduction to Spring Testing ... 292

14. Unit Testing ... 293

14.2. Unit Testing support Classes ... 294

General testing utilities ... 294

Spring MVC ... 294

15. Integration Testing ... 295

15.1. Overview ... 295

15.2. Goals of Integration Testing ... 295

Context management and caching ... 295

Dependency Injection of test fixtures ... 296

Transaction management ... 296

Support classes for integration testing ... 297

15.3. JDBC Testing Support ... 297

15.4. Annotations ... 297

Spring Testing Annotations ... 297

@BootstrapWith ... 298

@ContextConfiguration ... 298

@WebAppConfiguration ... 298

@ContextHierarchy ... 299

@ActiveProfiles ... 299

@TestPropertySource ... 300

@DirtiesContext ... 300

@TestExecutionListeners ... 302

@Commit ... 302

@Rollback ... 302

@BeforeTransaction ... 303

@AfterTransaction ... 303

@Sql ... 303

@SqlConfig ... 303

@SqlGroup ... 304

Standard Annotation Support ... 304

Spring JUnit 4 Testing Annotations ... 305

@IfProfileValue ... 305

@ProfileValueSourceConfiguration ... 305

@Timed ... 305

@Repeat ... 306

Meta-Annotation Support for Testing ... 306

15.5. Spring TestContext Framework ... 307

Key abstractions ... 308

TestContext ... 308

TestContextManager ... 308

(12)

Context Loaders ... 308

Bootstrapping the TestContext framework ... 309

TestExecutionListener configuration ... 310

Registering custom TestExecutionListeners ... 310

Automatic discovery of default TestExecutionListeners ... 310

Ordering TestExecutionListeners ... 310

Merging TestExecutionListeners ... 311

Context management ... 312

Context configuration with XML resources ... 313

Context configuration with Groovy scripts ... 313

Context configuration with annotated classes ... 314

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

Context configuration with context initializers ... 316

Context configuration inheritance ... 317

Context configuration with environment profiles ... 318

Context configuration with test property sources ... 323

Loading a WebApplicationContext ... 325

Context caching ... 328

Context hierarchies ... 329

Dependency injection of test fixtures ... 331

Testing request and session scoped beans ... 333

Transaction management ... 335

Test-managed transactions ... 335

Enabling and disabling transactions ... 336

Transaction rollback and commit behavior ... 337

Programmatic transaction management ... 337

Executing code outside of a transaction ... 337

Configuring a transaction manager ... 338

Demonstration of all transaction-related annotations ... 338

Executing SQL scripts ... 339

Executing SQL scripts programmatically ... 340

Executing SQL scripts declaratively with @Sql ... 340

TestContext Framework support classes ... 344

Spring JUnit 4 Runner ... 344

Spring JUnit 4 Rules ... 344

JUnit 4 support classes ... 345

TestNG support classes ... 345

15.6. Spring MVC Test Framework ... 346

Server-Side Tests ... 347

Static Imports ... 348

Setup Options ... 348

Performing Requests ... 349

Defining Expectations ... 350

Filter Registrations ... 351

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

Further Server-Side Test Examples ... 352

HtmlUnit Integration ... 352

Why HtmlUnit Integration? ... 353

MockMvc and HtmlUnit ... 355

(13)

MockMvc and Geb ... 362

Client-Side REST Tests ... 363

Static Imports ... 364

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

15.7. PetClinic Example ... 365

16. Further Resources ... 367

V. Data Access ... 368

17. Transaction Management ... 369

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

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

Global transactions ... 369

Local transactions ... 370

Spring Framework’s consistent programming model ... 370

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

17.4. Synchronizing resources with transactions ... 374

High-level synchronization approach ... 374

Low-level synchronization approach ... 375

TransactionAwareDataSourceProxy ... 375

17.5. Declarative transaction management ... 375

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

Example of declarative transaction implementation ... 377

Rolling back a declarative transaction ... 381

Configuring different transactional semantics for different beans ... 382

<tx:advice/> settings ... 384

Using @Transactional ... 385

@Transactional settings ... 390

Multiple Transaction Managers with @Transactional ... 391

Custom shortcut annotations ... 392

Transaction propagation ... 392

Required ... 392

RequiresNew ... 393

Nested ... 393

Advising transactional operations ... 393

Using @Transactional with AspectJ ... 396

17.6. Programmatic transaction management ... 397

Using the TransactionTemplate ... 397

Specifying transaction settings ... 399

Using the PlatformTransactionManager ... 399

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

17.8. Transaction bound event ... 400

17.9. Application server-specific integration ... 400

IBM WebSphere ... 401

Oracle WebLogic Server ... 401

17.10. Solutions to common problems ... 401

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

17.11. Further Resources ... 401

18. DAO support ... 403

18.1. Introduction ... 403

18.2. Consistent exception hierarchy ... 403

(14)

19. Data access with JDBC ... 406

19.1. Introduction to Spring Framework JDBC ... 406

Choosing an approach for JDBC database access ... 406

Package hierarchy ... 407

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

JdbcTemplate ... 408

Examples of JdbcTemplate class usage ... 408

JdbcTemplate best practices ... 410

NamedParameterJdbcTemplate ... 412

SQLExceptionTranslator ... 414

Executing statements ... 415

Running queries ... 416

Updating the database ... 417

Retrieving auto-generated keys ... 417

19.3. Controlling database connections ... 417

DataSource ... 417

DataSourceUtils ... 419

SmartDataSource ... 419

AbstractDataSource ... 419

SingleConnectionDataSource ... 419

DriverManagerDataSource ... 419

TransactionAwareDataSourceProxy ... 420

DataSourceTransactionManager ... 420

NativeJdbcExtractor ... 420

19.4. JDBC batch operations ... 421

Basic batch operations with the JdbcTemplate ... 421

Batch operations with a List of objects ... 422

Batch operations with multiple batches ... 423

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

Inserting data using SimpleJdbcInsert ... 424

Retrieving auto-generated keys using SimpleJdbcInsert ... 424

Specifying columns for a SimpleJdbcInsert ... 425

Using SqlParameterSource to provide parameter values ... 426

Calling a stored procedure with SimpleJdbcCall ... 426

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

How to define SqlParameters ... 429

Calling a stored function using SimpleJdbcCall ... 429

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

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

SqlQuery ... 431

MappingSqlQuery ... 432

SqlUpdate ... 433

StoredProcedure ... 433

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

Providing SQL type information for parameters ... 436

Handling BLOB and CLOB objects ... 437

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

Handling complex types for stored procedure calls ... 438

(15)

Why use an embedded database? ... 440

Creating an embedded database using Spring XML ... 440

Creating an embedded database programmatically ... 440

Selecting the embedded database type ... 441

Using HSQL ... 441

Using H2 ... 441

Using Derby ... 441

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

Generating unique names for embedded databases ... 442

Extending the embedded database support ... 442

19.9. Initializing a DataSource ... 443

Initializing a database using Spring XML ... 443

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

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

20.1. Introduction to ORM with Spring ... 446

20.2. General ORM integration considerations ... 447

Resource and transaction management ... 447

Exception translation ... 448

20.3. Hibernate ... 448

SessionFactory setup in a Spring container ... 448

Implementing DAOs based on plain Hibernate API ... 449

Declarative transaction demarcation ... 450

Programmatic transaction demarcation ... 451

Transaction management strategies ... 452

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

Spurious application server warnings with Hibernate ... 454

20.4. JDO ... 455

PersistenceManagerFactory setup ... 455

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

Transaction management ... 458

JdoDialect ... 459

20.5. JPA ... 459

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

LocalEntityManagerFactoryBean ... 459

Obtaining an EntityManagerFactory from JNDI ... 460

LocalContainerEntityManagerFactoryBean ... 460

Dealing with multiple persistence units ... 462

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

Spring-driven JPA transactions ... 465

JpaDialect and JpaVendorAdapter ... 465

Setting up JPA with JTA transaction management ... 465

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

21.1. Introduction ... 467

Ease of configuration ... 467

Consistent Interfaces ... 467

Consistent Exception Hierarchy ... 467

21.2. Marshaller and Unmarshaller ... 467

Marshaller ... 467

Unmarshaller ... 468

(16)

21.3. Using Marshaller and Unmarshaller ... 469

21.4. XML Schema-based Configuration ... 471

21.5. JAXB ... 471

Jaxb2Marshaller ... 471

XML Schema-based Configuration ... 472

21.6. Castor ... 472

CastorMarshaller ... 472

Mapping ... 473

XML Schema-based Configuration ... 473

21.7. XMLBeans ... 474

XmlBeansMarshaller ... 474

XML Schema-based Configuration ... 474

21.8. JiBX ... 474

JibxMarshaller ... 475

XML Schema-based Configuration ... 475

21.9. XStream ... 475

XStreamMarshaller ... 475

VI. The Web ... 477

22. Web MVC framework ... 478

22.1. Introduction to Spring Web MVC framework ... 478

Features of Spring Web MVC ... 478

Pluggability of other MVC implementations ... 480

22.2. The DispatcherServlet ... 480

Special Bean Types In the WebApplicationContext ... 484

Default DispatcherServlet Configuration ... 485

DispatcherServlet Processing Sequence ... 485

22.3. Implementing Controllers ... 487

Defining a controller with @Controller ... 487

Mapping Requests With @RequestMapping ... 488

Composed @RequestMapping Variants ... 489

@Controller and AOP Proxying ... 490

New Support Classes for @RequestMapping methods in Spring MVC 3.1 .. 490

URI Template Patterns ... 491

URI Template Patterns with Regular Expressions ... 492

Path Patterns ... 492

Path Pattern Comparison ... 493

Path Patterns with Placeholders ... 493

Suffix Pattern Matching ... 493

Suffix Pattern Matching and RFD ... 493

Matrix Variables ... 494

Consumable Media Types ... 496

Producible Media Types ... 496

Request Parameters and Header Values ... 497

HTTP HEAD and HTTP OPTIONS ... 497

Defining @RequestMapping handler methods ... 498

Supported method argument types ... 498

Supported method return types ... 500

Binding request parameters to method parameters with @RequestParam ... 501

Mapping the request body with the @RequestBody annotation ... 502

(17)

Creating REST Controllers with the @RestController annotation ... 504

Using HttpEntity ... 504

Using @ModelAttribute on a method ... 504

Using @ModelAttribute on a method argument ... 505

Using @SessionAttributes to store model attributes in the HTTP session between requests ... 507

Using @SessionAttribute to access pre-existing global session attributes .... 508

Using @RequestAttribute to access request attributes ... 508

Working with "application/x-www-form-urlencoded" data ... 508

Mapping cookie values with the @CookieValue annotation ... 509

Mapping request header attributes with the @RequestHeader annotation ... 509

Method Parameters And Type Conversion ... 510

Customizing WebDataBinder initialization ... 510

Advising controllers with @ControllerAdvice and @RestControllerAdvice .... 511

Jackson Serialization View Support ... 512

Jackson JSONP Support ... 513

Asynchronous Request Processing ... 514

Exception Handling for Async Requests ... 515

Intercepting Async Requests ... 516

HTTP Streaming ... 516

HTTP Streaming With Server-Sent Events ... 516

HTTP Streaming Directly To The OutputStream ... 517

Configuring Asynchronous Request Processing ... 517

Testing Controllers ... 518

22.4. Handler mappings ... 518

Intercepting requests with a HandlerInterceptor ... 519

22.5. Resolving views ... 521

Resolving views with the ViewResolver interface ... 521

Chaining ViewResolvers ... 523

Redirecting to Views ... 523

Building URIs to Controllers and methods ... 529

Working with "Forwarded" and "X-Forwarded-*" Headers ... 530

Building URIs to Controllers and methods from views ... 530

22.8. Using locales ... 531

Obtaining Time Zone Information ... 531

AcceptHeaderLocaleResolver ... 532

CookieLocaleResolver ... 532

SessionLocaleResolver ... 532

LocaleChangeInterceptor ... 532

22.9. Using themes ... 533

Overview of themes ... 533

Defining themes ... 533

Theme resolvers ... 534

(18)

Introduction ... 534

Using a MultipartResolver with Commons FileUpload ... 534

Using a MultipartResolver with Servlet 3.0 ... 535

Handling a file upload in a form ... 535

Handling a file upload request from programmatic clients ... 536

22.11. Handling exceptions ... 537

HandlerExceptionResolver ... 537

@ExceptionHandler ... 537

Handling Standard Spring MVC Exceptions ... 538

Annotating Business Exceptions With @ResponseStatus ... 539

Customizing the Default Servlet Container Error Page ... 539

22.12. Web Security ... 540

22.13. Convention over configuration support ... 540

The Controller ControllerClassNameHandlerMapping ... 540

The Model ModelMap (ModelAndView) ... 541

The View - RequestToViewNameTranslator ... 543

22.14. HTTP caching support ... 544

Cache-Control HTTP header ... 544

HTTP caching support for static resources ... 545

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

Shallow ETag support ... 546

22.15. Code-based Servlet container initialization ... 547

22.16. Configuring Spring MVC ... 549

Enabling the MVC Java Config or the MVC XML Namespace ... 549

Customizing the Provided Configuration ... 551

Conversion and Formatting ... 551

Validation ... 552

Falling Back On the "Default" Servlet To Serve Resources ... 559

Path Matching ... 560

Message Converters ... 561

Advanced Customizations with MVC Java Config ... 562

Advanced Customizations with the MVC Namespace ... 563

23. View technologies ... 564

23.1. Introduction ... 564

23.2. Thymeleaf ... 564

23.3. Groovy Markup Templates ... 564

Configuration ... 564

Example ... 565

23.4. Velocity & FreeMarker ... 565

Dependencies ... 565

Context configuration ... 565

Creating templates ... 566

Advanced configuration ... 566

(19)

FreeMarker ... 567

Bind support and form handling ... 567

The bind macros ... 567

Simple binding ... 568

Form input generation macros ... 568

HTML escaping and XHTML compliance ... 572

23.5. JSP & JSTL ... 572

View resolvers ... 573

'Plain-old' JSPs versus JSTL ... 573

Additional tags facilitating development ... 573

Using Spring’s form tag library ... 573

Configuration ... 574

HTTP Method Conversion ... 582

HTML5 Tags ... 583

23.6. Script templates ... 583

Dependencies ... 584

How to integrate script based templating ... 584

23.7. XML Marshalling View ... 586

23.8. Tiles ... 586

Dependencies ... 586

How to integrate Tiles ... 586

UrlBasedViewResolver ... 587

ResourceBundleViewResolver ... 587

SimpleSpringPreparerFactory and SpringBeanPreparerFactory ... 588

23.9. XSLT ... 588

My First Words ... 589

Bean definitions ... 589

Standard MVC controller code ... 589

Document transformation ... 590

23.10. Document views (PDF/Excel) ... 590

Introduction ... 590

Configuration and setup ... 591

Document view definitions ... 591

Controller code ... 591

Subclassing for Excel views ... 591

Subclassing for PDF views ... 593

(20)

Dependencies ... 593

Populating the ModelAndView ... 595

Working with Sub-Reports ... 596

Configuring Sub-Report Files ... 596

Configuring Sub-Report Data Sources ... 597

Configuring Exporter Parameters ... 597

23.12. Feed Views ... 598

23.13. JSON Mapping View ... 598

23.14. XML Mapping View ... 599

24. Integrating with other web frameworks ... 600

24.1. Introduction ... 600

24.2. Common configuration ... 601

24.3. JavaServer Faces 1.2 ... 602

SpringBeanFacesELResolver (JSF 1.2+) ... 602

FacesContextUtils ... 602

24.4. Apache Struts 2.x ... 602

25.3. The ViewRendererServlet ... 607

25.4. Controllers ... 608

AbstractController and PortletContentGenerator ... 609

Other simple controllers ... 610

25.6. Views and resolving them ... 614

25.7. Multipart (file upload) support ... 614

Using the PortletMultipartResolver ... 615

Handling a file upload in a form ... 615

25.8. Handling exceptions ... 619

25.9. Annotation-based controller configuration ... 619

Setting up the dispatcher for annotation support ... 619

(21)

Mapping requests with @RequestMapping ... 620

Supported handler method arguments ... 622

Binding request parameters to method parameters with @RequestParam ... 624

Providing a link to data from the model with @ModelAttribute ... 624

Specifying attributes to store in a Session with @SessionAttributes ... 625

Customizing WebDataBinder initialization ... 625

Customizing data binding with @InitBinder ... 625

Configuring a custom WebBindingInitializer ... 626

25.10. Portlet application deployment ... 626

26. WebSocket Support ... 627

26.1. Introduction ... 627

WebSocket Fallback Options ... 627

A Messaging Architecture ... 628

Sub-Protocol Support in WebSocket ... 628

Should I Use WebSocket? ... 628

26.2. WebSocket API ... 629

Create and Configure a WebSocketHandler ... 629

Customizing the WebSocket Handshake ... 630

WebSocketHandler Decoration ... 631

Deployment Considerations ... 631

Configuring the WebSocket Engine ... 632

Configuring allowed origins ... 634

26.3. SockJS Fallback Options ... 635

Overview of SockJS ... 635

Enable SockJS ... 636

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

Heartbeat Messages ... 638

Servlet 3 Async Requests ... 638

CORS Headers for SockJS ... 639

SockJS Client ... 639

26.4. STOMP Over WebSocket Messaging Architecture ... 641

Overview of STOMP ... 641

Enable STOMP over WebSocket ... 642

Flow of Messages ... 644

Annotation Message Handling ... 646

Sending Messages ... 648

Simple Broker ... 648

Full-Featured Broker ... 648

Connections To Full-Featured Broker ... 650

Using Dot as Separator in @MessageMapping Destinations ... 650

Authentication ... 651

Token-based Authentication ... 652

User Destinations ... 653

Listening To ApplicationContext Events and Intercepting Messages ... 655

STOMP Client ... 656

WebSocket Scope ... 657

Configuration and Performance ... 658

Runtime Monitoring ... 661

Testing Annotated Controller Methods ... 662

(22)

27.1. Introduction ... 663 27.2. Controller method CORS configuration ... 663 27.3. Global CORS configuration ... 664 JavaConfig ... 664 XML namespace ... 665 27.4. Advanced Customization ... 665 27.5. Filter based CORS support ... 665 VII. Integration ... 667 28. Remoting and web services using Spring ... 668 28.1. Introduction ... 668 28.2. Exposing services using RMI ... 669 Exporting the service using the RmiServiceExporter ... 669 Linking in the service at the client ... 670 28.3. Using Hessian or Burlap to remotely call services via HTTP ... 670 Wiring up the DispatcherServlet for Hessian and co. ... 670 Exposing your beans by using the HessianServiceExporter ... 671 Linking in the service on the client ... 671 Using Burlap ... 672 Applying HTTP basic authentication to a service exposed through Hessian or

(23)
(24)
(25)

34.1. Introduction ... 757 34.2. The Spring TaskExecutor abstraction ... 757 TaskExecutor types ... 757 Using a TaskExecutor ... 758 34.3. The Spring TaskScheduler abstraction ... 759 the Trigger interface ... 760 Trigger implementations ... 760 TaskScheduler implementations ... 761 34.4. Annotation Support for Scheduling and Asynchronous Execution ... 761 Enable scheduling annotations ... 761 The @Scheduled annotation ... 762 The @Async annotation ... 763 Executor qualification with @Async ... 764 Exception management with @Async ... 764 34.5. The task namespace ... 765 The 'scheduler' element ... 765 The 'executor' element ... 765 The 'scheduled-tasks' element ... 766 34.6. Using the Quartz Scheduler ... 767 Using the JobDetailFactoryBean ... 767 Using the MethodInvokingJobDetailFactoryBean ... 768 Wiring up jobs using triggers and the SchedulerFactoryBean ... 768 35. Dynamic language support ... 770 35.1. Introduction ... 770 35.2. A first example ... 770 35.3. Defining beans that are backed by dynamic languages ... 772 Common concepts ... 772 The <lang:language/> element ... 773 Refreshable beans ... 773 Inline dynamic language source files ... 775 Understanding Constructor Injection in the context of

(26)
(27)
(28)
(29)
(30)

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

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

(31)

1. Getting Started with Spring

This reference guide provides detailed information about the Spring Framework. It provides comprehensive 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 by creating 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 convention over configuration, and is designed to get you up and running as quickly as possible.

(32)

2. Introduction to the Spring Framework

The Spring Framework is a Java platform that provides comprehensive infrastructure support for developing 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 enterprise services non-invasively to POJOs. This capability applies to the Java SE programming model and to full 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 an HTTP endpoint without having to deal with the Servlet API.

• Make a local Java method a message handler without having to deal with the JMS API. • Make a local Java method a management operation without having to deal with the JMX API.

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 the means 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 integrate into 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 Framework Modules

(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.

Core Container

The Core Container consists of the spring-core, spring-beans, spring-context, spring-context-support, and spring-expression (Spring Expression Language) modules.

The spring-core and spring-beans modules provide the fundamental parts of the framework, including the IoC and Dependency Injection features. The BeanFactory is a sophisticated implementation of the factory pattern. It removes the need for programmatic singletons and allows you 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 JNDI registry. The Context module inherits its features from the Beans module and adds support for internationalization (using, for example, resource bundles), event propagation, resource loading, and the transparent creation of contexts by, for example, a Servlet container. The Context module also supports Java EE features such as EJB, JMX, and basic remoting. The ApplicationContext interface is the focal point of the Context module. spring-context-support provides support for integrating common third-party libraries into a Spring application context for caching (EhCache, Guava, JCache), mailing (JavaMail), scheduling (CommonJ, Quartz) and template engines (FreeMarker, JasperReports, Velocity).

(34)

logical and arithmetic operators, named variables, and retrieval of objects by name from Spring’s IoC container. 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 programming implementation allowing you to define, for example, method interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated. Using source-level metadata functionality, 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 classloader implementations to be used in certain application servers. The spring-instrument-tomcat module contains 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 a foundation for messaging-based applications. The module also includes a set of annotations for mapping messages 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 tedious JDBC 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 simple declarative 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 consuming messages. Since Spring Framework 4.1, it provides integration with the spring-messaging module.

Web

The Web layer consists of the web, webmvc, websocket, and spring-webmvc-portlet modules.

(35)

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

The spring-webmvc-portlet module (also known as the Web-Portlet module) provides the MVC implementation to be used in a Portlet environment and mirrors the functionality of the Servlet-based spring-webmvc module.

Test

The spring-test module supports the unit testing and integration testing of Spring components with JUnit or TestNG. It provides consistent loading of Spring ApplicationContexts and caching of those contexts. 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, from embedded applications that run on resource-constrained devices to full-fledged enterprise applications that use Spring’s transaction management functionality and web framework integration.

Figure 2.2. Typical full-fledged Spring web application

(36)

web-layer with the domain model, removing the need for ActionForms or other classes that transform HTTP parameters to values for your domain model.

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

(37)

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

(38)

Dependency Management and Naming Conventions

Dependency management and dependency injection are different things. To get those nice features of Spring into your application (like dependency injection) you need to assemble all the libraries needed (jar files) and get them onto your classpath at runtime, and possibly at compile time. These dependencies are not virtual components that are injected, but physical resources in a file system (typically). The process 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 indirect dependencies are also known as "transitive" and it is those dependencies that are hardest to identify and manage.

If you are going to use Spring you need to get a copy of the jar libraries that comprise the pieces of Spring that you need. To make this easier Spring is packaged as a set of modules that separate the dependencies as much as possible, so for example if you don’t want to write a web application you don’t need the spring-web modules. To refer to Spring library modules in this guide we use a shorthand naming 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.9.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 special configuration to use. Many of the common libraries that Spring depends on also are available from Maven Central and a large section of the Spring community uses Maven for dependency management, 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, this repository 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 other libraries deployed in Maven Central. This repository also contains a bundle distribution zip file that contains 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 the use of an automated system like Maven, Gradle or Ivy, but you can also do it manually by downloading all the jars yourself.

Below you will find the list of Spring artifacts. For a more complete description of each module, see Section 2.2, “Framework Modules”.

Table 2.1. Spring Framework Artifacts

GroupId ArtifactId Description

org.springframework spring-aop Proxy-based AOP support org.springframework spring-aspects AspectJ based aspects org.springframework spring-beans Beans support, including

Groovy

(39)

GroupId ArtifactId Description

org.springframework spring-context-support Support classes for integrating common third-party libraries into a Spring application context org.springframework spring-core Core utilities, used by many

other Spring modules org.springframework spring-expression Spring Expression Language

(SpEL)

org.springframework spring-instrument Instrumentation agent for JVM bootstrapping

org.springframework spring-instrument-tomcat Instrumentation agent for Tomcat

org.springframework spring-jdbc JDBC support package,

including DataSource setup and JDBC access support

org.springframework spring-jms JMS support package, including helper classes to send/receive JMS messages

org.springframework spring-messaging Support for messaging architectures and protocols org.springframework spring-orm Object/Relational Mapping, including JPA and Hibernate support

org.springframework spring-oxm Object/XML Mapping org.springframework spring-test Support for unit testing and

integration testing Spring components

org.springframework spring-tx Transaction infrastructure, including DAO support and JCA integration

org.springframework spring-web Foundational web support, including web client and web-based remoting

org.springframework spring-webmvc HTTP-based Model-View-Controller and REST endpoints for Servlet stacks

(40)

GroupId ArtifactId Description

org.springframework spring-websocket WebSocket and SockJS

infrastructure, including STOMP messaging 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 locate and download (even automatically) a large number of jar libraries in order to use Spring for simple use cases. For basic dependency injection there is only one mandatory external dependency, and that is for 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 with Maven and then with Gradle and finally using Ivy. In all cases, if anything is unclear, refer to the documentation of your dependency management system, or look at some sample code - Spring itself uses 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 logging dependency explicitly. For example, to create an application context and use dependency injection to configure an application, your Maven dependencies will look like this:

<dependencies>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>4.3.9.RELEASE</version>

<scope>runtime</scope>

</dependency> </dependencies>

That’s it. Note the scope can be declared as runtime if you don’t need to compile against Spring APIs, which is typically the case for basic dependency injection use cases.

The example above works with the Maven Central repository. To use the Spring Maven repository (e.g. for milestones or developer snapshots), you need to specify the repository location in your Maven configuration. For full releases:

<repositories>

<repository>

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

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

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

</repository> </repositories>

For milestones: <repositories>

<repository>

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

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

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

(41)

And for snapshots: <repositories>

<repository>

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

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

<snapshots><enabled>true</enabled></snapshots>

</repository> </repositories>

Maven "Bill Of Materials" Dependency

It is possible to accidentally mix different versions of Spring JARs when using Maven. For example, you may find that a third-party library, or another Spring project, pulls in a transitive dependency to an older release. If you forget to explicitly declare a direct dependency yourself, all sorts of unexpected issues can arise.

To overcome such problems Maven supports the concept of a "bill of materials" (BOM) dependency. You can import the spring-framework-bom in your dependencyManagement section to ensure that all spring dependencies (both direct and transitive) are at the same version.

<dependencyManagement>

An added benefit of using the BOM is that you no longer need to specify the <version> attribute when depending on Spring Framework artifacts:

<dependencies>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-web</artifactId>

</dependency>

maven { url "http://repo.spring.io/release" } }

(42)

dependencies {

compile("org.springframework:spring-context:4.3.9.RELEASE") testCompile("org.springframework:spring-test:4.3.9.RELEASE") }

Ivy Dependency Management

If you prefer to use Ivy to manage dependencies then there are similar configuration options.

To configure Ivy to point to the Spring repository add the following resolver to your ivysettings.xml: <resolvers>

<ibiblio name="io.spring.repo.maven.release"

m2compatible="true"

root="http://repo.spring.io/release/"/> </resolvers>

You can change the root URL from /release/ to /milestone/ or /snapshot/ as appropriate. Once configured, you can add dependencies in the usual way. For example (in ivy.xml):

<dependency org="org.springframework"

name="spring-core" rev="4.3.9.RELEASE" conf="compile->runtime"/>

Distribution Zip Files

Although using a build system that supports dependency management is the recommended way to obtain the Spring Framework, it is still possible to download a distribution zip file.

Distribution zips are published to the Spring Maven Repository (this is just for our convenience, you don’t need Maven or any other build system in order to download them).

To download a distribution zip open a web browser to http://repo.spring.io/release/org/springframework/ spring and select the appropriate subfolder for the version that you want. Distribution files end -dist.zip, for example spring-framework-{spring-version}-RELEASE-dist.zip. Distributions are also published for milestones and snapshots.

Logging

Logging is a very important dependency for Spring because a) it is the only mandatory external dependency, b) everyone likes to see some output from the tools they are using, and c) Spring integrates with lots of other tools all of which have also made a choice of logging dependency. One of the goals of an application developer is often to have unified logging configured in a central place for the whole application, including all external components. This is more difficult than it might have been since there are so many choices of logging framework.

The mandatory logging dependency in Spring is the Jakarta Commons Logging API (JCL). We compile against JCL and we also make JCL Log objects visible for classes that extend the Spring Framework. It’s important to users that all versions of Spring use the same logging library: migration is easy because backwards compatibility is preserved even with applications that extend Spring. The way we do this is to make one of the modules in Spring depend explicitly on commons-logging (the canonical implementation of JCL), and then make all the other modules depend on that at compile time. If you are using Maven for example, and wondering where you picked up the dependency on commons-logging, then it is from Spring and specifically from the central module called spring-core.

(43)

on the classpath and uses one that it thinks is appropriate (or you can tell it which one if you need to). If nothing else is available you get pretty nice looking logs just from the JDK (java.util.logging or JUL for short). You should find that your Spring application works and logs happily to the console out of the box in most situations, and that’s important.

Using Log4j 1.2 or 2.x

Note

Log4j 1.2 is EOL in the meantime. Also, Log4j 2.3 is the last Java 6 compatible release, with newer Log4j 2.x releases requiring Java 7+.

Many people use Log4j as a logging framework for configuration and management purposes. It is efficient and well-established, and in fact it is what we use at runtime when we build Spring. Spring also provides some utilities for configuring and initializing Log4j, so it has an optional compile-time dependency on Log4j in some modules.

To make Log4j 1.2 work with the default JCL dependency (commons-logging) all you need to do is put Log4j on the classpath, and provide it with a configuration file (log4j.properties or log4j.xml in the root of the classpath). So for Maven users this is your dependency declaration:

<dependencies>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-core</artifactId>

<version>4.3.9.RELEASE</version>

</dependency>

<dependency>

<groupId>log4j</groupId>

<artifactId>log4j</artifactId>

<version>1.2.17</version>

</dependency> </dependencies>

And here’s a sample log4j.properties for logging to the console:

log4j.rootCategory=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L - %m%n log4j.category.org.springframework.beans.factory=DEBUG

To use Log4j 2.x with JCL, all you need to do is put Log4j on the classpath and provide it with a configuration file (log4j2.xml, log4j2.properties, or other supported configuration formats). For Maven users, the minimal dependencies needed are:

<dependencies>

<dependency>

<groupId>org.apache.logging.log4j</groupId>

<artifactId>log4j-core</artifactId>

<version>2.6.2</version>

</dependency>

<dependency>

<groupId>org.apache.logging.log4j</groupId>

<artifactId>log4j-jcl</artifactId>

<version>2.6.2</version>

(44)

If you also wish to enable SLF4J to delegate to Log4j, e.g. for other libraries which use SLF4J by default, the following dependency is also needed:

<dependencies>

<dependency>

<groupId>org.apache.logging.log4j</groupId>

<artifactId>log4j-slf4j-impl</artifactId>

<version>2.6.2</version>

</dependency> </dependencies>

Here is an example log4j2.xml for logging to the console:

<?xml version="1.0" encoding="UTF-8"?>

<Configuration status="WARN">

<Appenders>

<Console name="Console" target="SYSTEM_OUT">

<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>

</Console>

</Appenders>

<Loggers>

<Logger name="org.springframework.beans.factory" level="DEBUG"/>

<Root level="error">

Unfortunately, the runtime discovery algorithm in the standard commons-logging API, while convenient for the end-user, can be problematic. If you’d like to avoid JCL’s standard lookup, there are basically two ways to switch it off:

1. Exclude the dependency from the spring-core module (as it is the only module that explicitly depends on commons-logging)

2. Depend on a special commons-logging dependency that replaces the library with an empty jar (more details can be found in the SLF4J FAQ)

To exclude commons-logging, add the following to your dependencyManagement section: <dependencies>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-core</artifactId>

<version>4.3.9.RELEASE</version> classpath, so to fix it a new one has to be provided. In the next section we show you how to provide an alternative implementation of JCL using SLF4J.

Using SLF4J with Log4j or Logback

Gambar

Figure 2.1. Overview of the Spring Framework
Figure 2.2. Typical full-fledged Spring web application
Figure 2.3. Spring middle-tier using a third-party web framework
Figure 2.5. EJBs - Wrapping existing POJOs
+7

Referensi

Dokumen terkait

Berdasarkan Berita Acara Evaluasi Dokumen Penawaran dan Kualifikasi, tanggal 24 Maret 2016 yang menghasilkan Calon Pemenang dan berdasarkan Dokumen Penawaran dan Kualifikasi

peserta lelang paket tersebut diatas bahwa terjadi PERUBAHAN PADA DAFTAR KUANTITAS DAN. HARGA / BILL OF

[r]

Suatu fungsi dapat ditentukan bentuknya jika. Suatu fungsi dapat ditentukan

Ungkapan-ungkapan seperti tingkat atau laju pertumbuhan dan yang sejenisnya dalam masalah-masalah pertanian , ekonomi dan bisnis , kehidupan , perilaku ataupun laju

Pelaksanaan Supervisi Akademis Tahun Pelajaran 2014 yang disusun berdasarkan hasil evaluasi dan analisis pelaksanaan supervisi akademis tahun sebelumnya diharapkan

Selain itu, melalui penelitian tersebut juga ditemukan bahwa ada dampak positif program pendidikan karakter SMA Kristen 1 Salatiga, antara lain: tidak adanya

Dalam hal ini, dilihat dari apakah ada pengaruh hasil belajar siswa yang signifikan, antara kelas yang menggunakan model pembelajaran kooperatif tipe make a match