300
Spring Integration Reference Manual Mark Fisher Marius Bogoevici Iwein Fuld Jonas Partner Oleg Zhurakousky Gary Russell Dave Syer Josh Long David Turanski Gunnar Hillert Artem Bilan

Spring Integration Reference

Embed Size (px)

DESCRIPTION

Spring Integration Reference

Citation preview

  • Spring Integration Reference Manual

    Mark FisherMarius Bogoevici

    Iwein FuldJonas Partner

    Oleg ZhurakouskyGary Russell

    Dave SyerJosh Long

    David TuranskiGunnar HillertArtem Bilan

  • Spring Integration Reference Manualby Mark Fisher, Marius Bogoevici, Iwein Fuld, Jonas Partner, Oleg Zhurakousky, Gary Russell, Dave Syer, JoshLong, David Turanski, Gunnar Hillert, and Artem Bilan

    2.1.1.RELEASE

    SpringSource Inc., 2012

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual iii

    Table of ContentsPreface ................................................................................................................................... xiii

    1. Code Conventions ....................................................................................................... xiiiI. What's new? ........................................................................................................................... 1

    1. What's new in Spring Integration 2.1? ............................................................................. 21.1. New Components ................................................................................................ 2

    JSR-223 Scripting Support ................................................................................. 2GemFire Support ................................................................................................ 2AMQP Support .................................................................................................. 2MongoDB Support ............................................................................................. 3Redis Support .................................................................................................... 3Support for Spring's Resource abstraction ............................................................ 3Stored Procedure Components ............................................................................ 3XPath and XML Validating Filter ....................................................................... 4Payload Enricher ................................................................................................ 4FTP and SFTP Outbound Gateways .................................................................... 4FTP Session Caching ......................................................................................... 4

    1.2. Framework Refactoring ....................................................................................... 4Standardizing Router Configuration .................................................................... 4XML Schemas updated to 2.1 ............................................................................. 5

    1.3. Source Control Management and Build Infrastructure ............................................ 6Source Code now hosted on Github .................................................................... 6Improved Source Code Visibility with Sonar ....................................................... 6

    1.4. New Samples ...................................................................................................... 6II. Overview of Spring Integration Framework ............................................................................ 7

    2. Spring Integration Overview ........................................................................................... 82.1. Background ......................................................................................................... 82.2. Goals and Principles ............................................................................................ 82.3. Main Components ............................................................................................... 9

    Message ............................................................................................................. 9Message Channel ............................................................................................. 10Message Endpoint ............................................................................................ 10

    2.4. Message Endpoints ............................................................................................ 11Transformer ..................................................................................................... 11Filter ................................................................................................................ 11Router .............................................................................................................. 11Splitter ............................................................................................................. 12Aggregator ....................................................................................................... 12Service Activator .............................................................................................. 12Channel Adapter .............................................................................................. 13

    III. Core Messaging .................................................................................................................. 143. Messaging Channels ..................................................................................................... 15

    3.1. Message Channels ............................................................................................. 15The MessageChannel Interface .......................................................................... 15

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual iv

    PollableChannel ....................................................................................... 15SubscribableChannel ................................................................................. 15

    Message Channel Implementations .................................................................... 16PublishSubscribeChannel .......................................................................... 16QueueChannel .......................................................................................... 16PriorityChannel ........................................................................................ 16RendezvousChannel .................................................................................. 16DirectChannel .......................................................................................... 17ExecutorChannel ...................................................................................... 18Scoped Channel ....................................................................................... 19

    Channel Interceptors ......................................................................................... 19MessagingTemplate .......................................................................................... 21Configuring Message Channels ......................................................................... 21

    DirectChannel Configuration ..................................................................... 22Datatype Channel Configuration ................................................................ 22QueueChannel Configuration .................................................................... 23PublishSubscribeChannel Configuration ..................................................... 24ExecutorChannel ...................................................................................... 25PriorityChannel Configuration ................................................................... 25RendezvousChannel Configuration ............................................................ 25Scoped Channel Configuration .................................................................. 26Channel Interceptor Configuration ............................................................. 26Global Channel Interceptor ....................................................................... 26Wire Tap ................................................................................................. 27Global Wire Tap Configuration ................................................................. 28

    Special Channels .............................................................................................. 293.2. Poller (Polling Consumer) .................................................................................. 293.3. Channel Adapter ................................................................................................ 30

    Configuring Inbound Channel Adapter .............................................................. 30Configuring Outbound Channel Adapter ............................................................ 31

    3.4. Messaging Bridge .............................................................................................. 32Introduction ...................................................................................................... 32Configuring Bridge ........................................................................................... 33

    4. Message Construction ................................................................................................... 344.1. Message ............................................................................................................ 34

    The Message Interface ...................................................................................... 34Message Headers .............................................................................................. 34Message Implementations ................................................................................. 35The MessageBuilder Helper Class ..................................................................... 36

    5. Message Routing .......................................................................................................... 385.1. Routers ............................................................................................................. 38

    Overview ......................................................................................................... 38Common Router Parameters ............................................................................. 40

    Inside and Outside of a Chain ................................................................... 40Top-Level (Outside of a Chain) ................................................................ 41

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual v

    Router Implementations .................................................................................... 42PayloadTypeRouter .................................................................................. 42HeaderValueRouter .................................................................................. 42RecipientListRouter .................................................................................. 43XPath Router ........................................................................................... 44Routing and Error handling ....................................................................... 44

    Configuring (Generic) Router ........................................................................... 45Configuring a Content Based Router with XML ......................................... 45Configuring a Router with Annotations ..................................................... 47

    Dynamic Routers .............................................................................................. 47Manage Router Mappings using the Control Bus ........................................ 50Manage Router Mappings using JMX ........................................................ 50

    5.2. Filter ................................................................................................................. 51Introduction ...................................................................................................... 51Configuring Filter ............................................................................................. 51

    Configuring a Filter with XML ................................................................. 51Configuring a Filter with Annotations ....................................................... 53

    5.3. Splitter .............................................................................................................. 54Introduction ...................................................................................................... 54Programming model ......................................................................................... 54Configuring Splitter .......................................................................................... 55

    Configuring a Splitter using XML ............................................................. 55Configuring a Splitter with Annotations ..................................................... 56

    5.4. Aggregator ........................................................................................................ 56Introduction ...................................................................................................... 56Functionality .................................................................................................... 56Programming model ......................................................................................... 56

    CorrelatingMessageHandler ....................................................................... 57ReleaseStrategy ........................................................................................ 58CorrelationStrategy ................................................................................... 59

    Configuring Aggregator .................................................................................... 60Configuring an Aggregator with XML ....................................................... 60Configuring an Aggregator with Annotations ............................................. 64

    Managing State in an Aggregator: MessageGroupStore ....................................... 655.5. Resequencer ...................................................................................................... 66

    Introduction ...................................................................................................... 66Functionality .................................................................................................... 67Configuring a Resequencer ............................................................................... 67

    5.6. Message Handler Chain ..................................................................................... 68Introduction ...................................................................................................... 68Configuring Chain ............................................................................................ 69

    6. Message Transformation ............................................................................................... 716.1. Transformer ....................................................................................................... 71

    Introduction ...................................................................................................... 71Configuring Transformer .................................................................................. 71

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual vi

    Configuring Transformer with XML .......................................................... 71Configuring a Transformer with Annotations ............................................. 75

    Header Filter .................................................................................................... 756.2. Content Enricher ............................................................................................... 75

    Introduction ...................................................................................................... 75Header Enricher ............................................................................................... 76Payload Enricher .............................................................................................. 77

    Configuration ........................................................................................... 78Examples ................................................................................................. 79

    6.3. Claim Check ..................................................................................................... 81Introduction ...................................................................................................... 81Incoming Claim Check Transformer .................................................................. 81Outgoing Claim Check Transformer .................................................................. 82A word on Message Store ................................................................................ 84

    7. Messaging Endpoints .................................................................................................... 857.1. Message Endpoints ............................................................................................ 85

    Message Handler .............................................................................................. 85Event Driven Consumer ................................................................................... 86Polling Consumer ............................................................................................. 86Namespace Support .......................................................................................... 88Change Polling Rate at Runtime ....................................................................... 92Payload Type Conversion ................................................................................. 93Asynchronous polling ....................................................................................... 93

    7.2. Messaging Gateways ......................................................................................... 94Enter the GatewayProxyFactoryBean ................................................................. 94Gateway XML Namespace Support ................................................................... 94Setting the Default Reply Channel .................................................................... 95Gateway Configuration with Annotations and/or XML ....................................... 95Invoking No-Argument Methods ....................................................................... 96Error Handling ................................................................................................ 97Asynchronous Gateway .................................................................................... 98Gateway behavior when no response arrives ...................................................... 99

    7.3. Service Activator ............................................................................................. 101Introduction .................................................................................................... 101Configuring Service Activator ......................................................................... 101

    7.4. Delayer ........................................................................................................... 103Introduction .................................................................................................... 103Configuring Delayer ....................................................................................... 103

    7.5. Scripting support ............................................................................................. 104Script configuration ........................................................................................ 104

    7.6. Groovy support ................................................................................................ 106Groovy configuration ...................................................................................... 106Control Bus .................................................................................................... 107

    8. System Management ................................................................................................... 1098.1. JMX Support ................................................................................................... 109

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual vii

    Notification Listening Channel Adapter ........................................................... 109Notification Publishing Channel Adapter ......................................................... 109Attribute Polling Channel Adapter ................................................................... 110Operation Invoking Channel Adapter ............................................................... 110Operation Invoking outbound Gateway ............................................................ 111MBean Exporter ............................................................................................. 111

    MBean ObjectNames .............................................................................. 112MessageChannel MBean Features ............................................................ 112

    8.2. Message History .............................................................................................. 113Message History Configuration ....................................................................... 114

    8.3. Message Store ................................................................................................. 1158.4. Control Bus ..................................................................................................... 116

    IV. Integration Adapters ......................................................................................................... 1189. AMQP Support .......................................................................................................... 119

    9.1. Introduction ..................................................................................................... 1199.2. Inbound Channel Adapter ................................................................................. 1199.3. Outbound Channel Adapter .............................................................................. 1229.4. Inbound Gateway ............................................................................................. 1229.5. Outbound Gateway .......................................................................................... 1239.6. AMQP Backed Message Channels .................................................................... 1249.7. AMQP Samples ............................................................................................... 124

    10. Spring ApplicationEvent Support ............................................................................... 12610.1. Receiving Spring ApplicationEvents ............................................................... 12610.2. Sending Spring ApplicationEvents .................................................................. 126

    11. Feed Adapter ............................................................................................................ 12811.1. Introduction ................................................................................................... 12811.2. Feed Inbound Channel Adapter ....................................................................... 128

    12. File Support ............................................................................................................. 13012.1. Introduction ................................................................................................... 13012.2. Reading Files ................................................................................................. 13012.3. Writing files .................................................................................................. 13212.4. File Transformers ........................................................................................... 133

    13. FTP/FTPS Adapters .................................................................................................. 13513.1. Introduction ................................................................................................... 13513.2. FTP Session Factory ...................................................................................... 13513.3. FTP Inbound Channel Adapter ....................................................................... 13713.4. FTP Outbound Channel Adapter ..................................................................... 13913.5. FTP Outbound Gateway ................................................................................. 14013.6. FTP Session Caching ..................................................................................... 142

    14. GemFire Support ...................................................................................................... 14314.1. Introduction ................................................................................................... 14314.2. Inbound Channel Adapter ............................................................................... 14314.3. Continuous Query Inbound Channel Adapter ................................................... 14414.4. Outbound Channel Adapter ............................................................................ 14514.5. Gemfire Message Store .................................................................................. 145

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual viii

    15. HTTP Support .......................................................................................................... 14715.1. Introduction ................................................................................................... 14715.2. Http Inbound Gateway ................................................................................... 14715.3. Http Outbound Gateway ................................................................................. 14815.4. HTTP Namespace Support ............................................................................. 14915.5. Timeout Handling .......................................................................................... 15115.6. HTTP Proxy configuration ............................................................................. 15415.7. HTTP Header Mappings ................................................................................. 15515.8. HTTP Samples .............................................................................................. 156

    Multipart HTTP request - RestTemplate (client) and Http Inbound Gateway(server) .......................................................................................................... 156

    16. TCP and UDP Support ............................................................................................. 15816.1. Introduction ................................................................................................... 15816.2. UDP Adapters ............................................................................................... 15816.3. TCP Connection Factories .............................................................................. 16016.4. TCP Connection Interceptors .......................................................................... 16316.5. TCP Adapters ................................................................................................ 16416.6. TCP Gateways ............................................................................................... 16516.7. TCP Message Correlation ............................................................................... 167

    Overview ....................................................................................................... 167Gateways ....................................................................................................... 167Collaborating Outbound and Inbound Channel Adapters ................................... 167

    16.8. A Note About NIO ........................................................................................ 16816.9. IP Configuration Attributes ............................................................................. 169

    17. JDBC Support .......................................................................................................... 17717.1. Inbound Channel Adapter ............................................................................... 177

    Polling and Transactions ................................................................................. 17817.2. Outbound Channel Adapter ............................................................................ 17817.3. Outbound Gateway ........................................................................................ 17917.4. JDBC Message Store ..................................................................................... 180

    Initializing the Database ................................................................................. 181Partitioning a Message Store ........................................................................... 181

    17.5. Stored Procedures .......................................................................................... 181Supported Databases ....................................................................................... 181Configuration ................................................................................................. 182Common Configuration Attributes ................................................................... 182Common Configuration Sub-Elements ............................................................. 183Defining Parameter Sources ............................................................................ 185Stored Procedure Inbound Channel Adapter ..................................................... 185Stored Procedure Outbound Channel Adapter ................................................... 186Stored Procedure Outbound Gateway ............................................................... 187Examples ....................................................................................................... 187

    18. JMS Support ............................................................................................................ 19018.1. Inbound Channel Adapter ............................................................................... 19018.2. Message-Driven Channel Adapter ................................................................... 191

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual ix

    18.3. Outbound Channel Adapter ............................................................................ 19218.4. Inbound Gateway ........................................................................................... 19218.5. Outbound Gateway ........................................................................................ 19318.6. Mapping Message Headers to/from JMS Message ............................................ 19418.7. Message Conversion, Marshalling and Unmarshalling ...................................... 19418.8. JMS Backed Message Channels ...................................................................... 19418.9. JMS Samples ................................................................................................. 196

    19. Mail Support ............................................................................................................ 19719.1. Mail-Sending Channel Adapter ....................................................................... 19719.2. Mail-Receiving Channel Adapter .................................................................... 19719.3. Mail Namespace Support ................................................................................ 19819.4. Email Message Filtering ................................................................................. 201

    20. MongoDb Support .................................................................................................... 20220.1. Introduction ................................................................................................... 20220.2. Connecting to MongoDb ................................................................................ 20220.3. MongoDB Message Store ............................................................................... 203

    21. Redis Support ........................................................................................................... 20421.1. Introduction ................................................................................................... 20421.2. Connecting to Redis ....................................................................................... 20421.3. Messaging with Redis .................................................................................... 205

    Redis Publish/Subscribe channel ..................................................................... 205Redis Inbound Channel Adapter ...................................................................... 206Redis Outbound Channel Adapter .................................................................... 206

    21.4. Redis Message Store ...................................................................................... 20722. Resource Support ...................................................................................................... 208

    22.1. Introduction ................................................................................................... 20822.2. Resource Inbound Channel Adapter ................................................................ 208

    23. RMI Support ............................................................................................................ 21023.1. Introduction ................................................................................................... 21023.2. Outbound RMI .............................................................................................. 21023.3. Inbound RMI ................................................................................................. 21023.4. RMI namespace support ................................................................................. 210

    24. SFTP Adapters ......................................................................................................... 21224.1. Introduction ................................................................................................... 21224.2. SFTP Session Factory .................................................................................... 21224.3. SFTP Inbound Channel Adapter ...................................................................... 21324.4. SFTP Outbound Channel Adapter ................................................................... 21424.5. SFTP Outbound Gateway ............................................................................... 21524.6. SFTP/JSCH Logging ...................................................................................... 21624.7. SFTP Session Caching ................................................................................... 217

    25. Stream Support ......................................................................................................... 21825.1. Introduction ................................................................................................... 21825.2. Reading from streams .................................................................................... 21825.3. Writing to streams ......................................................................................... 21825.4. Stream namespace support .............................................................................. 219

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual x

    26. Twitter Adapter ........................................................................................................ 22026.1. Introduction ................................................................................................... 22026.2. Twitter OAuth Configuration .......................................................................... 22026.3. Twitter Template ........................................................................................... 22126.4. Twitter Inbound Adapters ............................................................................... 221

    Inbound Message Channel Adapter .................................................................. 222Direct Inbound Message Channel Adapter ....................................................... 223Mentions Inbound Message Channel Adapter ................................................... 223Search Inbound Message Channel Adapter ....................................................... 223

    26.5. Twitter Outbound Adapter .............................................................................. 223Twitter Outbound Update Channel Adapter ...................................................... 224Twitter Outbound Direct Message Channel Adapter ......................................... 224

    27. Web Services Support ............................................................................................... 22627.1. Outbound Web Service Gateways ................................................................... 22627.2. Inbound Web Service Gateways ...................................................................... 22627.3. Web Service Namespace Support .................................................................... 227

    28. XML Support - Dealing with XML Payloads ............................................................. 22928.1. Introduction ................................................................................................... 22928.2. Namespace Support ........................................................................................ 229

    XPath Expressions .......................................................................................... 230Providing Namespaces (Optional) to XPath Expressions ........................... 230

    28.3. Transforming XML Payloads .......................................................................... 231Configuring Transformers as Beans ................................................................. 231Namespace Support for XML Transformers ..................................................... 233

    28.4. Transforming XML Messages Using XPath ..................................................... 23528.5. Splitting XML Messages ................................................................................ 23628.6. Routing XML Messages Using XPath ............................................................. 237

    XML Payload Converter ................................................................................. 23928.7. XPath Header Enricher ................................................................................... 23928.8. Using the XPath Filter ................................................................................... 24028.9. XML Validating Filter ................................................................................... 241

    29. XMPP Support ......................................................................................................... 24329.1. Introduction ................................................................................................... 24329.2. XMPP Connection ......................................................................................... 24329.3. XMPP Messages ............................................................................................ 244

    Inbound Message Channel Adapter .................................................................. 244Outbound Message Channel Adapter ............................................................... 244

    29.4. XMPP Presence ............................................................................................. 245Inbound Presence Message Channel Adapter .................................................... 245Outbound Presence Message Channel Adapter ................................................. 245

    29.5. Appendices .................................................................................................... 246V. Appendices ........................................................................................................................ 248

    30. Message Publishing .................................................................................................. 24930.1. Message Publishing Configuration .................................................................. 249

    Annotation-driven approach via @Publisher annotation .................................... 249

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual xi

    XML-based approach via the element ......................... 251Producing and publishing messages based on a scheduled trigger ....................... 253

    31. Transaction Support .................................................................................................. 25531.1. Understanding Transactions in Message flows ................................................. 255

    Poller Transaction Support .............................................................................. 25631.2. Transaction Boundaries .................................................................................. 257

    32. Security in Spring Integration .................................................................................... 25932.1. Introduction ................................................................................................... 25932.2. Securing channels .......................................................................................... 259

    A. Spring Integration Samples ........................................................................................ 260A.1. Introduction .................................................................................................... 260A.2. Where to get Samples ..................................................................................... 260A.3. Submitting Samples or Sample Requests .......................................................... 261A.4. Samples Structure ........................................................................................... 261A.5. Samples .......................................................................................................... 263

    Loan Broker ................................................................................................... 263The Cafe Sample ............................................................................................ 268The XML Messaging Sample .......................................................................... 272

    B. Configuration ............................................................................................................. 273B.1. Introduction .................................................................................................... 273B.2. Namespace Support ......................................................................................... 273B.3. Configuring the Task Scheduler ....................................................................... 274B.4. Error Handling ................................................................................................ 275B.5. Annotation Support ......................................................................................... 276B.6. Message Mapping rules and conventions .......................................................... 279

    Simple Scenarios ............................................................................................ 279Complex Scenarios ......................................................................................... 281

    C. Additional Resources ................................................................................................. 283C.1. Spring Integration Home ................................................................................. 283

    D. Change History .......................................................................................................... 284D.1. Changes between 1.0 and 2.0 ........................................................................... 284

    Spring 3 support ............................................................................................. 284Support for the Spring Expression Language (SpEL) ................................ 284ConversionService and Converter ............................................................ 284TaskScheduler and Trigger ...................................................................... 284RestTemplate and HttpMessageConverter ................................................ 284

    Enterprise Integration Pattern Additions ........................................................... 284Message History ..................................................................................... 285Message Store ........................................................................................ 285Claim Check .......................................................................................... 285Control Bus ............................................................................................ 285

    New Channel Adapters and Gateways ............................................................. 285TCP/UDP Adapters ................................................................................ 285Twitter Adapters ..................................................................................... 285XMPP Adapters ..................................................................................... 285

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual xii

    FTP/FTPS Adapters ................................................................................ 286SFTP Adapters ....................................................................................... 286Feed Adapters ........................................................................................ 286

    Other Additions .............................................................................................. 286Groovy Support ...................................................................................... 286Map Transformers .................................................................................. 286JSON Transformers ................................................................................ 286Serialization Transformers ....................................................................... 286

    Framework Refactoring ................................................................................... 286New Source Control Management and Build Infrastructure ............................... 287New Spring Integration Samples ..................................................................... 287SpringSource Tool Suite Visual Editor for Spring Integration ............................ 287

    D.2. Changes between 2.0 and 2.1 ........................................................................... 287

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual xiii

    Preface1 Code ConventionsThe Spring Framework 2.0 introduced support for namespaces, which simplifies the Xml configurationof the application context, and consequently Spring Integration provides broad namespace support. Thisreference guide applies the following conventions for all code examples that use namespace support:

    The int namespace prefix will be used for Spring Integration's core namespace support. Each SpringIntegration adapter type (module) will provide its own namespace, which is configured using thefollowing convention:

    int- followed by the name of the module, e.g. int-twitter, int-stream,

    For a detailed explanation regarding Spring Integration's namespace support see Section B.2,Namespace Support.

    NotePlease note that the namespace prefix can be freely chosen. You may even choose not touse any namespace prefixes at all. Therefore, apply the convention that suits your applicationneeds best. Be aware, though, that SpringSource Tool Suite (STS) uses the same namespaceconventions for Spring Integration as used in this reference guide.

  • Part I. What's new?For those who are already familiar with Spring Integration, this chapter provides a brief overview of thenew features of version 2.1. If you are interested in the changes and features, that were introduced inearlier versions, please take a look at chapter: Appendix D, Change History

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 2

    1. What's new in Spring Integration 2.1?This chapter provides an overview of the new features and improvements that have been introduced withSpring Integration 2.1 If you are interested in even more detail, please take a look at the Issue Trackertickets that were resolved as part of the 2.1 development process:

    Release Notes for Spring Integration 2.1 M1

    Release Notes for Spring Integration 2.1 M2

    Release Notes for Spring Integration 2.1 M3

    1.1 New Components

    JSR-223 Scripting Support

    In Spring Integration 2.0, support for Groovy was added. With Spring Integration 2.1 we expandedsupport for additional languages substantially by implementing support for JSR-223 (Scripting forthe Java Platform). Now you have the ability to use any scripting language that supports JSR-223including:

    Javascript

    Ruby/JRuby

    Python/Jython

    Groovy

    For further details please see Section 7.5, Scripting support.

    GemFire Support

    Spring Integration provides support for GemFire by providing inbound adapters for entry andcontinuous query events, an outbound adapter to write entries to the cache, and MessageStore andMessageGroupStore implementations. Spring integration leverages the Spring Gemfire project,providing a thin wrapper over its components.

    For further details please see Chapter 14, GemFire Support.

    AMQP Support

    Spring Integration 2.1 adds several Channel Adapters for receiving and sending messages using theAdvanced Message Queuing Protocol (AMQP). Furthermore, Spring Integration also provides a point-to-point Message Channel, as well as a publish/subscribe Message Channel that are backed by AMQPExchanges and Queues.

    For further details please see Chapter 9, AMQP Support.

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 3

    MongoDB SupportAs of version 2.1 Spring Integration provides support for MongoDB by providing a MongoDB-basedMessageStore.

    For further details please see Chapter 20, MongoDb Support.

    Redis SupportAs of version 2.1 Spring Integration supports Redis, an advanced key-value store, by providing a Redis-based MessageStore as well as Publish-Subscribe Messaging adapters.

    For further details please see Chapter 21, Redis Support.

    Support for Spring's Resource abstractionAs of version 2.1, we've introduced a new Resource Inbound Channel Adapter that builds uponSpring's Resource abstraction to support greater flexibility across a variety of actual types of underlyingresources, such as a file, a URL, or a class path resource. Therefore, it's similar to but more generic thanthe File Inbound Channel Adapter.

    For further details please see Section 22.2, Resource Inbound Channel Adapter.

    Stored Procedure ComponentsWith Spring Integration 2.1, the JDBC Module also provides Stored Procedure support by addingseveral new components, including inbound/outbound channel adapters and an Outbound Gateway.The Stored Procedure support leverages Spring's SimpleJdbcCall class and consequently supportsstored procedures for:

    Apache Derby

    DB2

    MySQL

    Microsoft SQL Server

    Oracle

    PostgreSQL

    Sybase

    The Stored Procedure components also support Sql Functions for the following databases:

    MySQL

    Microsoft SQL Server

    Oracle

    PostgreSQL

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 4

    For further details please see Section 17.5, Stored Procedures.

    XPath and XML Validating Filter

    Spring Integration 2.1 provides a new XPath-based Message Filter, that is part of the XML module.The XPath Filter allows you to filter messages using provided XPath Expressions. Furthermore,documentation was added for the XML Validating Filter.

    For more details please see Section 28.8, Using the XPath Filter and Section 28.9, XML ValidatingFilter.

    Payload Enricher

    Since Spring Integration 2.1, the Payload Enricher is provided. A Payload Enricher defines an endpointthat typically passes a Message to the exposed request channel and then expects a reply message. Thereply message then becomes the root object for evaluation of expressions to enrich the target payload.

    For further details please see the section called Payload Enricher.

    FTP and SFTP Outbound Gateways

    Spring Integration 2.1 provides two new Outbound Gateways in order to interact with remote FileTransfer Protocol (FTP) or Secure File Transfer Protocol (SFT) servers. These two gateways allow youto directly execute a limited set of remote commands.

    For instance, you can use these Outbound Gateways to list, retrieve and delete remote files and have theSpring Integration message flow continue with the remote server's response.

    For further details please see Section 13.5, FTP Outbound Gateway and Section 24.5, SFTPOutbound Gateway.

    FTP Session Caching

    As of version 2.1, we have exposed more flexibility with regards to session management for remote fileadapters (e.g., FTP, SFTP etc).

    Specifically, the cache-sessions attribute, which is available via the XML namespace support, isnow deprecated. Alternatively, we added the sessionCacheSize and sessionWaitTimeoutattributes on the CachingSessionFactory.

    For further details please see Section 13.6, FTP Session Caching and Section 24.7, SFTP SessionCaching.

    1.2 Framework RefactoringStandardizing Router Configuration

    Router parameters have been standardized across all router implementations with Spring Integration 2.1providing a more consistent user experience.

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 5

    With Spring Integration 2.1 the ignore-channel-name-resolution-failures attribute hasbeen removed in favor of consolidating its behavior with the resolution-required attribute.Also, the resolution-required attribute now defaults to true.

    Starting with Spring Integration 2.1, routers will no longer silently drop any messages, if nodefault output channel was defined. This means, that by default routers now require at least oneresolved channel (if no default-output-channel was set) and by default will throw aMessageDeliveryException if no channel was determined (or an attempt to send was notsuccessful).

    If, however, you do desire to drop messages silently, simply set default-output-channel="nullChannel".

    ImportantWith the standardization of Router parameters and the consolidation of the parametersdescribed above, there is the possibility of breaking older Spring Integration basedapplications.

    For further details please see Section 5.1, Routers

    XML Schemas updated to 2.1

    Spring Integration 2.1 ships with an updated XML Schema (version 2.1), providing many improvements,e.g. the Router standardizations discussed above.

    From now on, users must always declare the latest XML schema (currently version 2.1). Alternatively,they can use the version-less schema. Generally, the best option is to use version-less namespaces, asthese will automatically use the latest available version of Spring Integration.

    Declaring a version-less Spring Integration namespace:

    ...

    Declaring a Spring Integration namespace using an explicit version:

    ...

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 6

    The old 1.0 and 2.0 schemas are still there, but if an Application Context still references one of thosedeprecated schemas, the validator will fail on initialization.

    1.3 Source Control Management and Build InfrastructureSource Code now hosted on Github

    Since version 2.0, the Spring Integration project uses Git for version control. In order to increasecommunity visibility even further, the project was moved from SpringSource hosted Git repositoriesto Github. The Spring Integration Git repository is located at: https://github.com/SpringSource/spring-integration/

    For the project we also improved the process of providing code contributions and we ensure that everycommit is peer-reviewed. In fact, core committers now follow the same process as contributors. Formore details please see:

    https://github.com/SpringSource/spring-integration/wiki/Contributor-Guidelines

    Improved Source Code Visibility with Sonar

    In an effort to provide better source code visibility and consequently to monitor the quality of SpringIntegration's source code, an instance of Sonar was setup and metrics are gathered nightly and madeavaiblable at:

    https://sonar.springsource.org/

    1.4 New SamplesFor the 2.1 release of Spring Integration we also expanded the Spring Integration Samples project andadded many new samples, e.g. sampples covering AMQP support, the new payload enricher, a sampleillustrating techniques for testing Spring Integration flow fragments, as well as an example for executingStored Procedures against Oracle. For details please visit:

    https://github.com/SpringSource/spring-integration-samples

  • Part II. Overview of SpringIntegration Framework

    Spring Integration provides an extension of the Spring programming model to support the well-knownEnterprise Integration Patterns. It enables lightweight messaging within Spring-based applications andsupports integration with external systems via declarative adapters. Those adapters provide a higher-level of abstraction over Spring's support for remoting, messaging, and scheduling. Spring Integration'sprimary goal is to provide a simple model for building enterprise integration solutions while maintainingthe separation of concerns that is essential for producing maintainable, testable code.

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 8

    2. Spring Integration Overview2.1 BackgroundOne of the key themes of the Spring Framework is inversion of control. In its broadest sense, this meansthat the framework handles responsibilities on behalf of the components that are managed within itscontext. The components themselves are simplified since they are relieved of those responsibilities. Forexample, dependency injection relieves the components of the responsibility of locating or creating theirdependencies. Likewise, aspect-oriented programming relieves business components of generic cross-cutting concerns by modularizing them into reusable aspects. In each case, the end result is a systemthat is easier to test, understand, maintain, and extend.

    Furthermore, the Spring framework and portfolio provide a comprehensive programming model forbuilding enterprise applications. Developers benefit from the consistency of this model and especiallythe fact that it is based upon well-established best practices such as programming to interfaces andfavoring composition over inheritance. Spring's simplified abstractions and powerful support librariesboost developer productivity while simultaneously increasing the level of testability and portability.

    Spring Integration is motivated by these same goals and principles. It extends the Spring programmingmodel into the messaging domain and builds upon Spring's existing enterprise integration support toprovide an even higher level of abstraction. It supports message-driven architectures where inversion ofcontrol applies to runtime concerns, such as when certain business logic should execute and where theresponse should be sent. It supports routing and transformation of messages so that different transportsand different data formats can be integrated without impacting testability. In other words, the messagingand integration concerns are handled by the framework, so business components are further isolatedfrom the infrastructure and developers are relieved of complex integration responsibilities.

    As an extension of the Spring programming model, Spring Integration provides a wide variety ofconfiguration options including annotations, XML with namespace support, XML with generic "bean"elements, and of course direct usage of the underlying API. That API is based upon well-definedstrategy interfaces and non-invasive, delegating adapters. Spring Integration's design is inspired by therecognition of a strong affinity between common patterns within Spring and the well-known EnterpriseIntegration Patterns as described in the book of the same name by Gregor Hohpe and Bobby Woolf(Addison Wesley, 2004). Developers who have read that book should be immediately comfortable withthe Spring Integration concepts and terminology.

    2.2 Goals and PrinciplesSpring Integration is motivated by the following goals:

    Provide a simple model for implementing complex enterprise integration solutions.

    Facilitate asynchronous, message-driven behavior within a Spring-based application.

    Promote intuitive, incremental adoption for existing Spring users.

    Spring Integration is guided by the following principles:

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 9

    Components should be loosely coupled for modularity and testability.

    The framework should enforce separation of concerns between business logic and integration logic.

    Extension points should be abstract in nature but within well-defined boundaries to promote reuseand portability.

    2.3 Main ComponentsFrom the vertical perspective, a layered architecture facilitates separation of concerns, and interface-based contracts between layers promote loose coupling. Spring-based applications are typically designedthis way, and the Spring framework and portfolio provide a strong foundation for following this bestpractice for the full-stack of an enterprise application. Message-driven architectures add a horizontalperspective, yet these same goals are still relevant. Just as "layered architecture" is an extremely genericand abstract paradigm, messaging systems typically follow the similarly abstract "pipes-and-filters"model. The "filters" represent any component that is capable of producing and/or consuming messages,and the "pipes" transport the messages between filters so that the components themselves remainloosely-coupled. It is important to note that these two high-level paradigms are not mutually exclusive.The underlying messaging infrastructure that supports the "pipes" should still be encapsulated in a layerwhose contracts are defined as interfaces. Likewise, the "filters" themselves would typically be managedwithin a layer that is logically above the application's service layer, interacting with those servicesthrough interfaces much in the same way that a web-tier would.

    Message

    In Spring Integration, a Message is a generic wrapper for any Java object combined with metadata usedby the framework while handling that object. It consists of a payload and headers. The payload canbe of any type and the headers hold commonly required information such as id, timestamp, correlationid, and return address. Headers are also used for passing values to and from connected transports. Forexample, when creating a Message from a received File, the file name may be stored in a header to beaccessed by downstream components. Likewise, if a Message's content is ultimately going to be sentby an outbound Mail adapter, the various properties (to, from, cc, subject, etc.) may be configured asMessage header values by an upstream component. Developers can also store any arbitrary key-valuepairs in the headers.

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 10

    Message Channel

    A Message Channel represents the "pipe" of a pipes-and-filters architecture. Producers send Messages toa channel, and consumers receive Messages from a channel. The Message Channel therefore decouplesthe messaging components, and also provides a convenient point for interception and monitoring ofMessages.

    A Message Channel may follow either Point-to-Point or Publish/Subscribe semantics. With a Point-to-Point channel, at most one consumer can receive each Message sent to the channel. Publish/Subscribechannels, on the other hand, will attempt to broadcast each Message to all of its subscribers. SpringIntegration supports both of these.

    Whereas "Point-to-Point" and "Publish/Subscribe" define the two options for how many consumerswill ultimately receive each Message, there is another important consideration: should the channelbuffer messages? In Spring Integration, Pollable Channels are capable of buffering Messages withina queue. The advantage of buffering is that it allows for throttling the inbound Messages and therebyprevents overloading a consumer. However, as the name suggests, this also adds some complexity,since a consumer can only receive the Messages from such a channel if a poller is configured. On theother hand, a consumer connected to a Subscribable Channel is simply Message-driven. The variety ofchannel implementations available in Spring Integration will be discussed in detail in the section calledMessage Channel Implementations.

    Message Endpoint

    One of the primary goals of Spring Integration is to simplify the development of enterprise integrationsolutions through inversion of control. This means that you should not have to implement consumersand producers directly, and you should not even have to build Messages and invoke send or receiveoperations on a Message Channel. Instead, you should be able to focus on your specific domain modelwith an implementation based on plain Objects. Then, by providing declarative configuration, you can"connect" your domain-specific code to the messaging infrastructure provided by Spring Integration.The components responsible for these connections are Message Endpoints. This does not mean that youwill necessarily connect your existing application code directly. Any real-world enterprise integrationsolution will require some amount of code focused upon integration concerns such as routing andtransformation. The important thing is to achieve separation of concerns between such integration logicand business logic. In other words, as with the Model-View-Controller paradigm for web applications,the goal should be to provide a thin but dedicated layer that translates inbound requests into service layerinvocations, and then translates service layer return values into outbound replies. The next section willprovide an overview of the Message Endpoint types that handle these responsibilities, and in upcomingchapters, you will see how Spring Integration's declarative configuration options provide a non-invasiveway to use each of these.

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 11

    2.4 Message EndpointsA Message Endpoint represents the "filter" of a pipes-and-filters architecture. As mentioned above, theendpoint's primary role is to connect application code to the messaging framework and to do so in a non-invasive manner. In other words, the application code should ideally have no awareness of the Messageobjects or the Message Channels. This is similar to the role of a Controller in the MVC paradigm. Justas a Controller handles HTTP requests, the Message Endpoint handles Messages. Just as Controllers aremapped to URL patterns, Message Endpoints are mapped to Message Channels. The goal is the samein both cases: isolate application code from the infrastructure. These concepts are discussed at lengthalong with all of the patterns that follow in the Enterprise Integration Patterns book. Here, we provideonly a high-level description of the main endpoint types supported by Spring Integration and their roles.The chapters that follow will elaborate and provide sample code as well as configuration examples.

    Transformer

    A Message Transformer is responsible for converting a Message's content or structure and returning themodified Message. Probably the most common type of transformer is one that converts the payload ofthe Message from one format to another (e.g. from XML Document to java.lang.String). Similarly, atransformer may be used to add, remove, or modify the Message's header values.

    Filter

    A Message Filter determines whether a Message should be passed to an output channel at all. Thissimply requires a boolean test method that may check for a particular payload content type, a propertyvalue, the presence of a header, etc. If the Message is accepted, it is sent to the output channel, but ifnot it will be dropped (or for a more severe implementation, an Exception could be thrown). MessageFilters are often used in conjunction with a Publish Subscribe channel, where multiple consumers mayreceive the same Message and use the filter to narrow down the set of Messages to be processed basedon some criteria.

    NoteBe careful not to confuse the generic use of "filter" within the Pipes-and-Filters architecturalpattern with this specific endpoint type that selectively narrows down the Messages flowingbetween two channels. The Pipes-and-Filters concept of "filter" matches more closely withSpring Integration's Message Endpoint: any component that can be connected to MessageChannel(s) in order to send and/or receive Messages.

    Router

    A Message Router is responsible for deciding what channel or channels should receive the Messagenext (if any). Typically the decision is based upon the Message's content and/or metadata available inthe Message Headers. A Message Router is often used as a dynamic alternative to a statically configuredoutput channel on a Service Activator or other endpoint capable of sending reply Messages. Likewise,a Message Router provides a proactive alternative to the reactive Message Filters used by multiplesubscribers as described above.

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 12

    Splitter

    A Splitter is another type of Message Endpoint whose responsibility is to accept a Message from its inputchannel, split that Message into multiple Messages, and then send each of those to its output channel.This is typically used for dividing a "composite" payload object into a group of Messages containingthe sub-divided payloads.

    Aggregator

    Basically a mirror-image of the Splitter, the Aggregator is a type of Message Endpoint that receivesmultiple Messages and combines them into a single Message. In fact, Aggregators are often downstreamconsumers in a pipeline that includes a Splitter. Technically, the Aggregator is more complex than aSplitter, because it is required to maintain state (the Messages to-be-aggregated), to decide when thecomplete group of Messages is available, and to timeout if necessary. Furthermore, in case of a timeout,the Aggregator needs to know whether to send the partial results or to discard them to a separate channel.Spring Integration provides a CompletionStrategy as well as configurable settings for timeout,whether to send partial results upon timeout, and the discard channel.

    Service Activator

    A Service Activator is a generic endpoint for connecting a service instance to the messaging system.The input Message Channel must be configured, and if the service method to be invoked is capable ofreturning a value, an output Message Channel may also be provided.

    NoteThe output channel is optional, since each Message may also provide its own 'Return Address'header. This same rule applies for all consumer endpoints.

    The Service Activator invokes an operation on some service object to process the request Message,extracting the request Message's payload and converting if necessary (if the method does not expect aMessage-typed parameter). Whenever the service object's method returns a value, that return value willlikewise be converted to a reply Message if necessary (if it's not already a Message). That reply Messageis sent to the output channel. If no output channel has been configured, then the reply will be sent to thechannel specified in the Message's "return address" if available.

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 13

    A request-reply "Service Activator" endpoint connects atarget object's method to input and output Message Channels.

    Channel Adapter

    A Channel Adapter is an endpoint that connects a Message Channel to some other system or transport.Channel Adapters may be either inbound or outbound. Typically, the Channel Adapter will do somemapping between the Message and whatever object or resource is received-from or sent-to the othersystem (File, HTTP Request, JMS Message, etc). Depending on the transport, the Channel Adaptermay also populate or extract Message header values. Spring Integration provides a number of ChannelAdapters, and they will be described in upcoming chapters.

    An inbound "Channel Adapter" endpoint connects a source system to a MessageChannel.

    An outbound "Channel Adapter" endpoint connects a MessageChannel to a target system.

  • Part III. Core MessagingThis section covers all aspects of the core messaging API in Spring Integration. Here you will learn aboutMessages, Message Channels, and Message Endpoints. Many of the Enterprise Integration Patternsare covered here as well, such as Filters, Routers, Transformers, Service-Activators, Splitters, andAggregators. The section also contains material about System Management, including the Control Busand Message History support.

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 15

    3. Messaging Channels3.1 Message ChannelsWhile the Message plays the crucial role of encapsulating data, it is the MessageChannel thatdecouples message producers from message consumers.

    The MessageChannel Interface

    Spring Integration's top-level MessageChannel interface is defined as follows.

    public interface MessageChannel {

    boolean send(Message message);

    boolean send(Message message, long timeout);}

    When sending a message, the return value will be true if the message is sent successfully. If the sendcall times out or is interrupted, then it will return false.

    PollableChannel

    Since Message Channels may or may not buffer Messages (as discussed in the overview), there aretwo sub-interfaces defining the buffering (pollable) and non-buffering (subscribable) channel behavior.Here is the definition of PollableChannel.

    public interface PollableChannel extends MessageChannel {

    Message receive();

    Message receive(long timeout);

    }

    Similar to the send methods, when receiving a message, the return value will be null in the case of atimeout or interrupt.

    SubscribableChannel

    The SubscribableChannel base interface is implemented by channels that send Messages directlyto their subscribed MessageHandlers. Therefore, they do not provide receive methods for polling,but instead define methods for managing those subscribers:

    public interface SubscribableChannel extends MessageChannel {

    boolean subscribe(MessageHandler handler);

    boolean unsubscribe(MessageHandler handler);

    }

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 16

    Message Channel Implementations

    Spring Integration provides several different Message Channel implementations. Each is brieflydescribed in the sections below.

    PublishSubscribeChannel

    The PublishSubscribeChannel implementation broadcasts any Message sent to it to all ofits subscribed handlers. This is most often used for sending Event Messages whose primary roleis notification as opposed to Document Messages which are generally intended to be processedby a single handler. Note that the PublishSubscribeChannel is intended for sending only.Since it broadcasts to its subscribers directly when its send(Message) method is invoked,consumers cannot poll for Messages (it does not implement PollableChannel and therefore has noreceive() method). Instead, any subscriber must be a MessageHandler itself, and the subscriber'shandleMessage(Message) method will be invoked in turn.

    QueueChannel

    The QueueChannel implementation wraps a queue. Unlike the PublishSubscribeChannel,the QueueChannel has point-to-point semantics. In other words, even if the channel has multipleconsumers, only one of them should receive any Message sent to that channel. It provides a defaultno-argument constructor (providing an essentially unbounded capacity of Integer.MAX_VALUE) aswell as a constructor that accepts the queue capacity:

    public QueueChannel(int capacity)

    A channel that has not reached its capacity limit will store messages in its internal queue, and thesend() method will return immediately even if no receiver is ready to handle the message. If thequeue has reached capacity, then the sender will block until room is available. Or, if using the sendcall that accepts a timeout, it will block until either room is available or the timeout period elapses,whichever occurs first. Likewise, a receive call will return immediately if a message is available on thequeue, but if the queue is empty, then a receive call may block until either a message is available orthe timeout elapses. In either case, it is possible to force an immediate return regardless of the queue'sstate by passing a timeout value of 0. Note however, that calls to the no-arg versions of send() andreceive() will block indefinitely.

    PriorityChannel

    Whereas the QueueChannel enforces first-in/first-out (FIFO) ordering, the PriorityChannel isan alternative implementation that allows for messages to be ordered within the channel based upon apriority. By default the priority is determined by the 'priority' header within each message. However,for custom priority determination logic, a comparator of type Comparator

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 17

    implementation of BlockingQueue). This works well in situations where the sender and receiverare operating in different threads but simply dropping the message in a queue asynchronously is notappropriate. In other words, with a RendezvousChannel at least the sender knows that some receiverhas accepted the message, whereas with a QueueChannel, the message would have been stored tothe internal queue and potentially never received.

    Tip

    Keep in mind that all of these queue-based channels are storing messages in-memory only bydefault. When persistence is required, you can either provide a 'message-store' attribute withinthe 'queue' element to reference a persistent MessageStore implementation, or you can replacethe local channel with one that is backed by a persistent broker, such as a JMS-backed channelor Channel Adapter. The latter option allows you to take advantage of any JMS provider'simplementation for message persistence, and it will be discussed in Chapter 18, JMS Support.However, when buffering in a queue is not necessary, the simplest approach is to rely uponthe DirectChannel discussed next.

    The RendezvousChannel is also useful for implementing request-reply operations. The sendercan create a temporary, anonymous instance of RendezvousChannel which it then sets as the'replyChannel' header when building a Message. After sending that Message, the sender can immediatelycall receive (optionally providing a timeout value) in order to block while waiting for a reply Message.This is very similar to the implementation used internally by many of Spring Integration's request-replycomponents.

    DirectChannel

    The DirectChannel has point-to-point semantics but otherwise is more similar to thePublishSubscribeChannel than any of the queue-based channel implementations describedabove. It implements the SubscribableChannel interface instead of the PollableChannelinterface, so it dispatches Messages directly to a subscriber. As a point-to-point channel, however, itdiffers from the PublishSubscribeChannel in that it will only send each Message to a singlesubscribed MessageHandler.

    In addition to being the simplest point-to-point channel option, one of its most important features isthat it enables a single thread to perform the operations on "both sides" of the channel. For example,if a handler is subscribed to a DirectChannel, then sending a Message to that channel will triggerinvocation of that handler's handleMessage(Message) method directly in the sender's thread,before the send() method invocation can return.

    The key motivation for providing a channel implementation with this behavior is to support transactionsthat must span across the channel while still benefiting from the abstraction and loose coupling that thechannel provides. If the send call is invoked within the scope of a transaction, then the outcome of thehandler's invocation (e.g. updating a database record) will play a role in determining the ultimate resultof that transaction (commit or rollback).

    NoteSince the DirectChannel is the simplest option and does not add any additional overheadthat would be required for scheduling and managing the threads of a poller, it is the default

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 18

    channel type within Spring Integration. The general idea is to define the channels for anapplication and then to consider which of those need to provide buffering or to throttleinput, and then modify those to be queue-based PollableChannels. Likewise, if achannel needs to broadcast messages, it should not be a DirectChannel but rather aPublishSubscribeChannel. Below you will see how each of these can be configured.

    The DirectChannel internally delegates to a Message Dispatcher to invoke its subscribed MessageHandlers, and that dispatcher can have a load-balancing strategy. The load-balancer determines howinvocations will be ordered in the case that there are multiple handlers subscribed to the same channel.When using the namespace support described below, the default strategy is "round-robin" whichessentially load-balances across the handlers in rotation.

    NoteThe "round-robin" strategy is currently the only implementation available out-of-the-box inSpring Integration. Other strategy implementations may be added in future versions.

    The load-balancer also works in combination with a boolean failover property. If the "failover" valueis true (the default), then the dispatcher will fall back to any subsequent handlers as necessary whenpreceding handlers throw Exceptions. The order is determined by an optional order value defined onthe handlers themselves or, if no such value exists, the order in which the handlers are subscribed.

    If a certain situation requires that the dispatcher always try to invoke the first handler, then fallback in thesame fixed order sequence every time an error occurs, no load-balancing strategy should be provided.In other words, the dispatcher still supports the failover boolean property even when no load-balancingis enabled. Without load-balancing, however, the invocation of handlers will always begin with thefirst according to their order. For example, this approach works well when there is a clear definitionof primary, secondary, tertiary, and so on. When using the namespace support, the "order" attribute onany endpoint will determine that order.

    NoteKeep in mind that load-balancing and failover only apply when a channel has more than onesubscribed Message Handler. When using the namespace support, this means that more thanone endpoint shares the same channel reference in the "input-channel" attribute.

    ExecutorChannel

    The ExecutorChannel is a point-to-point channel that supports the same dispatcher configurationas DirectChannel (load-balancing strategy and the failover boolean property). The key differencebetween these two dispatching channel types is that the ExecutorChannel delegates to an instanceof TaskExecutor to perform the dispatch. This means that the send method typically will not block,but it also means that the handler invocation may not occur in the sender's thread. It therefore does notsupport transactions spanning the sender and receiving handler.

    TipNote that there are occasions where the sender may block. For example, when usinga TaskExecutor with a rejection-policy that throttles back on the client (such as the

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 19

    ThreadPoolExecutor.CallerRunsPolicy), the sender's thread will execute themethod directly anytime the thread pool is at its maximum capacity and the executor's workqueue is full. Since that situation would only occur in a non-predictable way, that obviouslycannot be relied upon for transactions.

    Scoped Channel

    Spring Integration 1.0 provided a ThreadLocalChannel implementation, but that has been removedas of 2.0. Now, there is a more general way for handling the same requirement by simply adding a"scope" attribute to a channel. The value of the attribute can be any name of a Scope that is availablewithin the context. For example, in a web environment, certain Scopes are available, and any customScope implementations can be registered with the context. Here's an example of a ThreadLocal-basedscope being applied to a channel, including the registration of the Scope itself.

    The channel above also delegates to a queue internally, but the channel is bound to the current thread,so the contents of the queue are as well. That way the thread that sends to the channel will later be ableto receive those same Messages, but no other thread would be able to access them. While thread-scopedchannels are rarely needed, they can be useful in situations where DirectChannels are being usedto enforce a single thread of operation but any reply Messages should be sent to a "terminal" channel.If that terminal channel is thread-scoped, the original sending thread can collect its replies from it.

    Now, since any channel can be scoped, you can define your own scopes in addition to Thread Local.

    Channel Interceptors

    One of the advantages of a messaging architecture is the ability to provide common behavior and capturemeaningful information about the messages passing through the system in a non-invasive way. Sincethe Messages are being sent to and received from MessageChannels, those channels provide anopportunity for intercepting the send and receive operations. The ChannelInterceptor strategyinterface provides methods for each of those operations:

    public interface ChannelInterceptor {

    Message preSend(Message message, MessageChannel channel);

    void postSend(Message message, MessageChannel channel, boolean sent);

    boolean preReceive(MessageChannel channel);

    Message postReceive(Message message, MessageChannel channel);

  • Spring Integration

    2.1.1.RELEASESpring IntegrationReference Manual 20

    }

    After implementing the interface, registering the interceptor with a channel is just a matter of calling:channel.addInterceptor(someChannelInterceptor);

    The methods that return a Message instance