Spring Integration Reference Manual V5.1.1.RELEASE Mark Fisher

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 712

DownloadSpring Integration Reference Manual V5.1.1.RELEASE - Mark Fisher
Open PDF In BrowserView PDF
Spring Integration Reference Manual
5.1.1.RELEASE

Mark Fisher , Marius Bogoevici , Iwein Fuld , Jonas Partner , Oleg Zhurakousky , Gary Russell ,
Dave Syer , Josh Long , David Turanski , Gunnar Hillert , Artem Bilan , Amol Nayak , Jay Bryant

Copyright © 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 Pivotal Software, Inc. All Rights Reserved.
Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee
for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.

Spring Integration Reference Manual

Table of Contents
............................................................................................................................................. xxvii
I. Preface ................................................................................................................................... 1
1. Requirements ................................................................................................................. 2
1.1. Compatible Java Versions .................................................................................... 2
1.2. Compatible Versions of the Spring Framework ...................................................... 2
2. Code Conventions .......................................................................................................... 3
3. Conventions in This Guide .............................................................................................. 4
II. What’s New? ......................................................................................................................... 5
4. What’s New in Spring Integration 5.1? ............................................................................ 6
4.1. New Components ................................................................................................ 6
AmqpDedicatedChannelAdvice ...................................................................... 6
Improved Function Support ................................................................................. 6
@LongRunningTest .......................................................................................... 6
4.2. General Changes ................................................................................................ 6
Java DSL ........................................................................................................... 7
Dispatcher Exceptions ........................................................................................ 7
Global Channel Interceptors ............................................................................... 7
Channel Interceptors .......................................................................................... 7
ObjectToJsonTransformer ............................................................................ 8
Integration Flows: Generated Bean Names .......................................................... 8
Aggregator Changes .......................................................................................... 8
@Publisher annotation changes .......................................................................... 8
4.3. Files Changes ..................................................................................................... 8
4.4. AMQP Changes .................................................................................................. 8
4.5. JDBC Changes ................................................................................................... 9
4.6. FTP and SFTP Changes ..................................................................................... 9
4.7. TCP Support ....................................................................................................... 9
4.8. Twitter Support .................................................................................................... 9
4.9. JMS Support ..................................................................................................... 10
4.10. HTTP/WebFlux Support ................................................................................... 10
4.11. JMX Changes .................................................................................................. 10
4.12. Micrometer Support Changes ........................................................................... 10
4.13. Integration Graph Customization ....................................................................... 10
4.14. Integration Global Properties ............................................................................ 10
4.15. The receiveTimeout for @Poller ................................................................ 10
III. Overview of Spring Integration Framework ............................................................................ 11
5. Spring Integration Overview .......................................................................................... 12
5.1. Background ....................................................................................................... 12
5.2. Goals and Principles .......................................................................................... 12
5.3. Main Components ............................................................................................. 13
Message .......................................................................................................... 13
Message Channel ............................................................................................ 13
Message Endpoint ............................................................................................ 14
5.4. Message Endpoints ........................................................................................... 14
Message Transformer ....................................................................................... 15
Message Filter ................................................................................................. 15
Message Router ............................................................................................... 15

5.1.1.RELEASE

Spring Integration

iii

Spring Integration Reference Manual

Splitter .............................................................................................................
Aggregator .......................................................................................................
Service Activator ..............................................................................................
Channel Adapter ..............................................................................................
Endpoint Bean Names ......................................................................................
5.5. Configuration and @EnableIntegration ..........................................................
5.6. Programming Considerations ..............................................................................
Considerations When Using Packaged (for example, Shaded) Jars ......................
5.7. Programming Tips and Tricks .............................................................................
XML Schemas ..................................................................................................
Finding Class Names for Java and DSL Configuration ........................................
5.8. POJO Method invocation ...................................................................................
IV. Core Messaging ..................................................................................................................
6. Messaging Channels ....................................................................................................
6.1. Message Channels ............................................................................................
The MessageChannel Interface .........................................................................
PollableChannel ..................................................................................
SubscribableChannel ..........................................................................
Message Channel Implementations ...................................................................
PublishSubscribeChannel ..................................................................
QueueChannel ........................................................................................
PriorityChannel ..................................................................................
RendezvousChannel ..............................................................................
DirectChannel ......................................................................................
ExecutorChannel ..................................................................................
Scoped Channel .......................................................................................
Channel Interceptors ........................................................................................
MessagingTemplate ......................................................................................
Configuring Message Channels .........................................................................
DirectChannel Configuration .................................................................
Datatype Channel Configuration ................................................................
QueueChannel Configuration ...................................................................
PublishSubscribeChannel Configuration .............................................
ExecutorChannel ..................................................................................
PriorityChannel Configuration .............................................................
RendezvousChannel Configuration .........................................................
Scoped Channel Configuration ..................................................................
Channel Interceptor Configuration .............................................................
Global Channel Interceptor Configuration ...................................................
Wire Tap ..................................................................................................
Conditional Wire Taps ..............................................................................
Global Wire Tap Configuration ..................................................................
Special Channels .............................................................................................
6.2. Poller ................................................................................................................
Polling Consumer .............................................................................................
Pollable Message Source .................................................................................
Deferred Acknowledgment Pollable Message Source .........................................
Conditional Pollers for Message Sources ...........................................................
Background ..............................................................................................
"Smart" Polling ........................................................................................

5.1.1.RELEASE

Spring Integration

15
16
16
17
17
20
21
21
23
23
24
26
28
29
29
29
29
29
29
30
30
30
31
31
33
33
33
35
35
36
36
38
40
40
41
41
41
42
42
43
45
45
45
45
46
46
47
48
48
48

iv

Spring Integration Reference Manual

SimpleActiveIdleMessageSourceAdvice ..........................................
CompoundTriggerAdvice ......................................................................
6.3. Channel Adapter ...............................................................................................
Configuring An Inbound Channel Adapter ..........................................................
Configuring An Outbound Channel Adapter ........................................................
Channel Adapter Expressions and Scripts .........................................................
6.4. Messaging Bridge ..............................................................................................
Configuring a Bridge with XML ..........................................................................
Configuring a Bridge with Java Configuration .....................................................
Configuring a Bridge with the Java DSL ............................................................
7. Message ......................................................................................................................
7.1. The Message Interface ......................................................................................
7.2. Message Headers .............................................................................................
MessageHeaderAccessor API .......................................................................
Message ID Generation ....................................................................................
Read-only Headers ...........................................................................................
Header Propagation .........................................................................................
7.3. Message Implementations ..................................................................................
7.4. The MessageBuilder Helper Class ..................................................................
8. Message Routing .........................................................................................................
8.1. Routers .............................................................................................................
Overview ..........................................................................................................
Common Router Parameters .............................................................................
Inside and Outside of a Chain ...................................................................
Top-Level (Outside of a Chain) .................................................................
Router Implementations ....................................................................................
PayloadTypeRouter ..............................................................................
HeaderValueRouter ..............................................................................
RecipientListRouter ..........................................................................
RecipientListRouterManagement ......................................................
XPath Router ...........................................................................................
Routing and Error Handling .......................................................................
Configuring a Generic Router ............................................................................
Configuring a Content-based Router with XML ...........................................
Routers and the Spring Expression Language (SpEL) ........................................
Configuring a Router with Annotations .......................................................
Dynamic Routers ..............................................................................................
Manage Router Mappings using the Control Bus ........................................
Manage Router Mappings by Using JMX ...................................................
Routing Slip .............................................................................................
Process Manager Enterprise Integration Pattern .........................................
8.2. Filter .................................................................................................................
Configuring a Filter with XML ............................................................................
Configuring a Filter with Annotations .................................................................
8.3. Splitter ..............................................................................................................
Programming Model .........................................................................................
Iterators ...................................................................................................
Stream and Flux ......................................................................................
Configuring a Splitter with XML .........................................................................
Configuring a Splitter with Annotations ..............................................................

5.1.1.RELEASE

Spring Integration

49
49
50
50
51
52
53
53
54
54
56
56
56
57
59
59
60
60
61
63
63
63
65
65
67
67
67
68
70
71
72
72
72
72
74
75
76
78
79
79
81
82
82
85
85
85
86
86
86
87

v

Spring Integration Reference Manual

8.4. Aggregator ........................................................................................................ 88
Functionality ..................................................................................................... 88
Programming Model ......................................................................................... 88
AggregatingMessageHandler .............................................................. 89
ReleaseStrategy .................................................................................. 91
Aggregating Large Groups ........................................................................ 93
Correlation Strategy .................................................................................. 93
Lock Registry ........................................................................................... 94
Avoiding Deadlocks .................................................................................. 94
Configuring an Aggregator in Java DSL ............................................................. 94
Configuring an Aggregator with XML ......................................................... 95
Configuring an Aggregator with Annotations ............................................. 101
Managing State in an Aggregator: MessageGroupStore ................................. 102
8.5. Resequencer ................................................................................................... 104
Functionality ................................................................................................... 104
Configuring a Resequencer ............................................................................. 105
8.6. Message Handler Chain ................................................................................... 107
Configuring a Chain ........................................................................................ 107
Using the id Attribute ...................................................................................... 108
Calling a Chain from within a Chain ................................................................ 109
8.7. Scatter-Gather ................................................................................................. 110
Functionality ................................................................................................... 110
Auction ................................................................................................... 110
Distribution ............................................................................................. 110
Configuring a Scatter-Gather Endpoint ............................................................. 111
8.8. Thread Barrier ................................................................................................. 112
9. Message Transformation ............................................................................................. 115
9.1. Transformer ..................................................................................................... 115
Configuring a Transformer with XML ................................................................ 115
Transformers and Spring Expression Language (SpEL) .................................... 116
Common Transformers ................................................................................... 116
Object-to-String Transformer ................................................................... 116
Object-to-Map and Map-to-Object Transformers .................................... 117
Stream Transformer ................................................................................ 119
JSON Transformers ................................................................................ 119
Configuring a Transformer with Annotations ..................................................... 122
Header Filter .................................................................................................. 122
Codec-Based Transformers ............................................................................. 122
9.2. Content Enricher .............................................................................................. 123
Header Enricher ............................................................................................. 123
POJO Support ........................................................................................ 124
SpEL Support ......................................................................................... 124
Configuring a Header Enricher with Java Configuration ............................. 124
Configuring a Header Enricher with the Java DSL .................................... 125
Header Channel Registry ........................................................................ 125
Payload Enricher ............................................................................................ 126
Configuration .......................................................................................... 127
Examples ............................................................................................... 128
How Do I Pass Only a Subset of Data to the Request Channel? ................ 129

5.1.1.RELEASE

Spring Integration

vi

Spring Integration Reference Manual

How Can I Enrich Payloads with Static Information without Using a
Request Channel? ..................................................................................
9.3. Claim Check ....................................................................................................
Incoming Claim Check Transformer .................................................................
Outgoing Claim Check Transformer .................................................................
Claim Once ....................................................................................................
A Word on Message Store ..............................................................................
9.4. Codec .............................................................................................................
EncodingPayloadTransformer ..................................................................
DecodingTransformer ................................................................................
CodecMessageConverter ............................................................................
Kryo ...............................................................................................................
Customizing Kryo ...................................................................................
10. Messaging Endpoints ................................................................................................
10.1. Message Endpoints ........................................................................................
Message Handler ...........................................................................................
Event-driven Consumer ...................................................................................
Polling Consumer ...........................................................................................
Endpoint Namespace Support .........................................................................
Examples ...............................................................................................
AOP Advice chains .................................................................................
Changing Polling Rate at Runtime ...................................................................
Payload Type Conversion ...............................................................................
Content Type Conversion ...............................................................................
Asynchronous Polling .....................................................................................
Endpoint Inner Beans .....................................................................................
10.2. Endpoint Roles ..............................................................................................
10.3. Leadership Event Handling .............................................................................
10.4. Messaging Gateways .....................................................................................
Enter the GatewayProxyFactoryBean .........................................................
Gateway XML Namespace Support .................................................................
Setting the Default Reply Channel ...................................................................
Gateway Configuration with Annotations and XML ............................................
Expressions and "Global" Headers ........................................................
Mapping Method Arguments to a Message ......................................................
Mapping Method Arguments ....................................................................
@MessagingGateway Annotation ...................................................................
Invoking No-Argument Methods .......................................................................
Error Handling ................................................................................................
Gateway Timeouts ..........................................................................................
Asynchronous Gateway ..................................................................................
ListenableFuture ..............................................................................
AsyncTaskExecutor ............................................................................
CompletableFuture ............................................................................
Reactor Mono .........................................................................................
Downstream Flows Returning an Asynchronous Type ...............................
void Return Type ..................................................................................
Gateway Behavior When No response Arrives .................................................
Long-running Process Downstream .........................................................
Downstream Component Returns null ......................................................

5.1.1.RELEASE

Spring Integration

129
130
130
131
132
133
133
133
133
133
133
134
136
136
136
136
137
139
140
141
143
143
145
146
146
147
148
149
149
150
150
151
152
152
153
154
154
155
157
158
159
159
160
161
162
162
162
162
163

vii

Spring Integration Reference Manual

Downstream Component Return Signature is void While Gateway Method
Signature Is Non-void .............................................................................
Downstream Component Results in Runtime Exception ............................
10.5. Service Activator ............................................................................................
Configuring Service Activator ..........................................................................
Service Activators and the Spring Expression Language (SpEL) ................
Asynchronous Service Activator ......................................................................
Service Activator and Method Return Type ......................................................
10.6. Delayer ..........................................................................................................
Configuring a Delayer .....................................................................................
Delayer and a Message Store .........................................................................
Release Failures ............................................................................................
10.7. Scripting Support ...........................................................................................
Script Configuration ........................................................................................
Script Variable Bindings ..........................................................................
10.8. Groovy support ..............................................................................................
Groovy Configuration ......................................................................................
Groovy Object Customization ..........................................................................
Groovy Script Compiler Customization .............................................................
Control Bus ....................................................................................................
10.9. Adding Behavior to Endpoints .........................................................................
Provided Advice Classes ................................................................................
Retry Advice ..........................................................................................
Circuit Breaker Advice ............................................................................
Expression Evaluating Advice ..................................................................
Custom Advice Classes ..................................................................................
Other Advice Chain Elements .........................................................................
Handling Message Advice ...............................................................................
Transaction Support .......................................................................................
Advising Filters ...............................................................................................
Advising Endpoints Using Annotations .............................................................
Ordering Advices within an Advice Chain .........................................................
Advised Handler Properties .............................................................................
Idempotent Receiver Enterprise Integration Pattern ..........................................
10.10. Logging Channel Adapter .............................................................................
Using Java Configuration ................................................................................
Configuring with the Java DSL ........................................................................
10.11. java.util.function Interfaces Support ...................................................
Kotlin Lambdas ..............................................................................................
11. Java DSL .................................................................................................................
11.1. DSL Basics ...................................................................................................
11.2. Message Channels ........................................................................................
11.3. Pollers ...........................................................................................................
11.4. DSL and Endpoint Configuration .....................................................................
11.5. Transformers .................................................................................................
11.6. Inbound Channel Adapters .............................................................................
11.7. Message Routers ...........................................................................................
11.8. Splitters .........................................................................................................
11.9. Aggregators and Resequencers ......................................................................
11.10. Service Activators and the .handle() method .............................................

5.1.1.RELEASE

Spring Integration

163
163
164
164
166
167
167
167
168
170
171
171
172
173
174
175
175
176
177
177
178
178
184
185
186
187
188
188
190
190
190
190
191
193
194
194
195
196
198
199
200
202
202
203
203
204
205
205
206

viii

Spring Integration Reference Manual

11.11. Operator log() ..............................................................................................
11.12. MessageChannelSpec.wireTap() ............................................................
11.13. Working With Message Flows .......................................................................
11.14. FunctionExpression ...............................................................................
11.15. Sub-flows support ........................................................................................
11.16. Using Protocol Adapters ...............................................................................
11.17. IntegrationFlowAdapter ........................................................................
11.18. Dynamic and Runtime Integration Flows ........................................................
11.19. IntegrationFlow as Gateway ...................................................................
12. System Management ................................................................................................
12.1. Metrics and Management ...............................................................................
Configuring Metrics Capture ............................................................................
Micrometer Integration ....................................................................................
MessageChannel Metric Features .................................................................
MessageHandler Metric Features ....................................................................
Time-Based Average Estimates .......................................................................
Metrics Factory ...............................................................................................
Customizing the Default Channel and Handler Statistics ............................
Advanced Customization .........................................................................
Performance Improvement ......................................................................
12.2. JMX Support .................................................................................................
Notification-listening Channel Adapter ..............................................................
Notification-publishing Channel Adapter ...........................................................
Attribute-polling Channel Adapter ....................................................................
Tree-polling Channel Adapter ..........................................................................
Operation-invoking Channel Adapter ................................................................
Operation-invoking Outbound Gateway ............................................................
MBean Exporter .............................................................................................
MBean Object Names .............................................................................
JMX Improvements .................................................................................
Orderly Shutdown Managed Operation ....................................................
12.3. Message History ............................................................................................
Message History Configuration ........................................................................
12.4. Message Store ..............................................................................................
Using MessageGroupFactory ......................................................................
Persistent MessageGroupStore and Lazy-load ..............................................
12.5. Metadata Store ..............................................................................................
Idempotent Receiver and Metadata Store ........................................................
MetadataStoreListener ............................................................................
12.6. Control Bus ...................................................................................................
12.7. Orderly Shutdown ..........................................................................................
12.8. Integration Graph ...........................................................................................
Graph Runtime Model .....................................................................................
12.9. Integration Graph Controller ...........................................................................
V. Integration Endpoints ..........................................................................................................
13. Endpoint Quick Reference Table ...............................................................................
14. AMQP Support .........................................................................................................
14.1. Inbound Channel Adapter ...............................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................

5.1.1.RELEASE

Spring Integration

207
207
208
209
209
211
212
213
215
217
217
217
218
220
221
221
222
222
223
223
223
223
224
225
225
226
226
226
227
228
231
231
231
232
235
235
235
236
237
237
238
239
242
243
245
246
250
250
253
254

ix

Spring Integration Reference Manual

14.2. Polled Inbound Channel Adapter .....................................................................
14.3. Inbound Gateway ...........................................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
14.4. Inbound Endpoint Acknowledge Mode .............................................................
14.5. Outbound Channel Adapter ............................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
14.6. Outbound Gateway ........................................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
14.7. Asynchronous Outbound Gateway ..................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
14.8. Outbound Message Conversion ......................................................................
14.9. Outbound User ID ..........................................................................................
14.10. Delayed Message Exchange .........................................................................
14.11. AMQP-backed Message Channels ................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
14.12. AMQP Message Headers .............................................................................
Overview ........................................................................................................
contentType Header .......................................................................................
14.13. Strict Message Ordering ...............................................................................
Inbound ..........................................................................................................
Outbound .......................................................................................................
14.14. AMQP Samples ...........................................................................................
15. Spring ApplicationEvent Support .........................................................................
15.1. Receiving Spring Application Events ...............................................................
15.2. Sending Spring Application Events ..................................................................
16. Feed Adapter ...........................................................................................................
16.1. Feed Inbound Channel Adapter ......................................................................
16.2. Duplicate Entries ............................................................................................
16.3. Other Options ................................................................................................
16.4. Java DSL Configuration .................................................................................
17. File Support .............................................................................................................
17.1. Reading Files ................................................................................................
Message Headers ..........................................................................................
Directory Scanning and Polling ........................................................................
Namespace Support .......................................................................................
WatchServiceDirectoryScanner ..............................................................
Limiting Memory Consumption ........................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
'tail’ing Files ...................................................................................................
Dealing With Incomplete Data .........................................................................
17.2. Writing files ...................................................................................................
Generating File Names ...................................................................................
Specifying the Output Directory .......................................................................
Using the directory Attribute ...............................................................

5.1.1.RELEASE

Spring Integration

255
255
256
257
258
258
260
261
262
264
265
266
268
269
269
270
271
271
272
273
273
273
275
276
276
276
277
278
278
279
280
280
281
281
281
283
283
286
286
286
288
289
290
290
291
293
293
294
295
295

x

Spring Integration Reference Manual

Using the directory-expression Attribute .........................................
Using the auto-create-directory Attribute .......................................
Dealing with Existing Destination Files .............................................................
Flushing Files When Using APPEND_NO_FLUSH ...............................................
File Timestamps .............................................................................................
File Permissions .............................................................................................
File Outbound Channel Adapter ......................................................................
Outbound Gateway .........................................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
17.3. File Transformers ...........................................................................................
17.4. File Splitter ....................................................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
18. FTP/FTPS Adapters ..................................................................................................
18.1. FTP Session Factory .....................................................................................
Default Factories ............................................................................................
18.2. Advanced Configuration .................................................................................
FTPS and Shared SSLSession .......................................................................
18.3. Delegating Session Factory ............................................................................
18.4. FTP Inbound Channel Adapter .......................................................................
More on File Filtering and Incomplete Files ......................................................
Poller Configuration Notes for the Inbound FTP Adapter ...................................
Recovering from Failures ................................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
Dealing With Incomplete Data .........................................................................
18.5. FTP Streaming Inbound Channel Adapter .......................................................
Configuring with Java Configuration .................................................................
18.6. Inbound Channel Adapters: Polling Multiple Servers and Directories ..................
18.7. Inbound Channel Adapters: Controlling Remote File Fetching ...........................
18.8. FTP Outbound Channel Adapter .....................................................................
Avoiding Partially Written Files ........................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
18.9. FTP Outbound Gateway .................................................................................
Using the ls Command ..................................................................................
Using the nlst Command ..............................................................................
Using the get Command ................................................................................
Using the mget Command ..............................................................................
Using the put Command ................................................................................
Using the rm Command ..................................................................................
Using the mv Command ..................................................................................
Additional Information about FTP Outbound Gateway Commands ......................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
Outbound Gateway Partial Success (mget and mput) ......................................
18.10. FTP Session Caching ...................................................................................
18.11. Using RemoteFileTemplate ......................................................................
18.12. Using MessageSessionCallback ..............................................................

5.1.1.RELEASE

Spring Integration

295
295
295
296
297
297
297
298
298
299
299
300
302
302
303
303
303
304
305
306
307
309
310
310
311
312
313
313
314
315
317
318
319
319
320
321
322
322
323
324
325
325
326
326
327
327
328
329
329
330

xi

Spring Integration Reference Manual

19. Pivotal GemFire and Apache Geode Support .............................................................
19.1. Inbound Channel Adapter ...............................................................................
19.2. Continuous Query Inbound Channel Adapter ...................................................
19.3. Outbound Channel Adapter ............................................................................
19.4. Gemfire Message Store .................................................................................
19.5. Gemfire Lock Registry ....................................................................................
19.6. Gemfire Metadata Store .................................................................................
20. HTTP Support ..........................................................................................................
20.1. Http Inbound Components ..............................................................................
20.2. HTTP Outbound Components .........................................................................
Using HttpRequestExecutingMessageHandler .........................................
Using Cookies ................................................................................................
20.3. HTTP Namespace Support .............................................................................
Inbound ..........................................................................................................
Request Mapping Support ...............................................................................
Cross-origin Resource Sharing (CORS) Support ...............................................
Response Status Code ...................................................................................
URI Template Variables and Expressions ........................................................
Outbound .......................................................................................................
Mapping URI Variables ...................................................................................
Controlling URI Encoding ................................................................................
20.4. Configuring HTTP Endpoints with Java ...........................................................
20.5. Timeout Handling ...........................................................................................
HTTP Inbound Gateway .................................................................................
20.6. HTTP Proxy configuration ...............................................................................
Standard Java Proxy configuration ..................................................................
Spring’s SimpleClientHttpRequestFactory .............................................
20.7. HTTP Header Mappings .................................................................................
20.8. Integration Graph Controller ...........................................................................
20.9. HTTP Samples ..............................................................................................
Multipart HTTP Request — RestTemplate (Client) and Http Inbound Gateway
(Server) ..........................................................................................................
21. JDBC Support ..........................................................................................................
21.1. Inbound Channel Adapter ...............................................................................
Polling and Transactions .................................................................................
max-rows Versus max-messages-per-poll ................................................
21.2. Outbound Channel Adapter ............................................................................
Passing Parameters by Using SpEL Expressions .............................................
Using the PreparedStatement Callback .......................................................
Batch Update .................................................................................................
21.3. Outbound Gateway ........................................................................................
21.4. JDBC Message Store .....................................................................................
Initializing the Database ..................................................................................
The Generic JDBC Message Store ..................................................................
Backing Message Channels ............................................................................
Supported Databases .............................................................................
Custom Message Insertion ......................................................................
Concurrent Polling ..................................................................................
Priority Channel ......................................................................................
Partitioning a Message Store ..........................................................................

5.1.1.RELEASE

Spring Integration

332
332
333
334
335
336
336
338
338
340
340
341
341
342
342
343
344
345
346
348
349
350
351
353
353
353
354
354
355
355
355
357
357
359
359
360
360
361
362
362
363
363
364
364
364
365
365
366
367

xii

Spring Integration Reference Manual

21.5. Stored Procedures .........................................................................................
Supported Databases .....................................................................................
Configuration ..................................................................................................
Common Configuration Attributes ....................................................................
Common Configuration Sub-Elements .............................................................
Defining Parameter Sources ...........................................................................
Stored Procedure Inbound Channel Adapter ....................................................
Stored Procedure Outbound Channel Adapter ..................................................
Stored Procedure Outbound Gateway ..............................................................
Examples .......................................................................................................
21.6. JDBC Lock Registry .......................................................................................
21.7. JDBC Metadata Store ....................................................................................
22. JPA Support .............................................................................................................
22.1. Functionality ..................................................................................................
22.2. Supported Persistence Providers ....................................................................
22.3. Java Implementation ......................................................................................
22.4. Namespace Support .......................................................................................
Common XML Namespace Configuration Attributes ..........................................
Providing JPA Query Parameters ....................................................................
Transaction Handling ......................................................................................
22.5. Inbound Channel Adapter ...............................................................................
Configuration Parameter Reference .................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
22.6. Outbound Channel Adapter ............................................................................
Using an Entity Class .....................................................................................
Using JPA Query Language (JPA QL) .............................................................
Using Native Queries ......................................................................................
Using Named Queries ....................................................................................
Configuration Parameter Reference .................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
22.7. Outbound Gateways .......................................................................................
Common Configuration Parameters .................................................................
Updating Outbound Gateway ..........................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
Retrieving Outbound Gateway .........................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
JPA Outbound Gateway Samples ....................................................................
Update by Using an Entity Class .............................................................
Update using JPQL ................................................................................
Retrieving an Entity using JPQL ..............................................................
Retrieving an Entity by Using id-expression ........................................
Update using a Named Query .................................................................
23. JMS Support ............................................................................................................
23.1. Inbound Channel Adapter ...............................................................................
Transactions ...................................................................................................
23.2. Message-driven Channel Adapter ...................................................................

5.1.1.RELEASE

Spring Integration

367
367
368
368
369
371
371
372
372
373
374
375
377
377
378
378
379
379
380
380
381
382
384
384
385
385
386
387
387
388
389
390
391
392
392
393
393
394
395
395
396
396
397
397
397
397
399
399
400
401

xiii

Spring Integration Reference Manual

24.

25.

26.

27.

Inbound Conversion Errors .............................................................................
23.3. Outbound Channel Adapter ............................................................................
Transactions ...................................................................................................
23.4. Inbound Gateway ...........................................................................................
23.5. Outbound Gateway ........................................................................................
Using a  .......................................................................
Idle Reply Listeners ........................................................................................
Gateway Reply Correlation .............................................................................
Async Gateway ..............................................................................................
Attribute Reference .........................................................................................
23.6. Mapping Message Headers to and from JMS Message ....................................
23.7. Message Conversion, Marshalling, and Unmarshalling .....................................
23.8. JMS-backed Message Channels .....................................................................
23.9. Using JMS Message Selectors .......................................................................
23.10. JMS Samples ..............................................................................................
Mail Support .............................................................................................................
24.1. Mail-sending Channel Adapter ........................................................................
24.2. Mail-receiving Channel Adapter ......................................................................
24.3. Inbound Mail Message Mapping .....................................................................
24.4. Mail Namespace Support ...............................................................................
IMAP idle and Lost Connections ...................................................................
24.5. Marking IMAP Messages When \Recent Is Not Supported ..............................
24.6. Email Message Filtering .................................................................................
24.7. Transaction Synchronization ...........................................................................
MongoDb Support .....................................................................................................
25.1. Connecting to MongoDb .................................................................................
Using MongoDbFactory ................................................................................
25.2. MongoDB Message Store ...............................................................................
MongoDB Channel Message Store ..................................................................
MongoDB Metadata Store ...............................................................................
25.3. MongoDB Inbound Channel Adapter ...............................................................
25.4. MongoDB Outbound Channel Adapter .............................................................
25.5. MongoDB Outbound Gateway ........................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
MQTT Support .........................................................................................................
26.1. Inbound (Message-driven) Channel Adapter ....................................................
Adding and Removing Topics at Runtime ........................................................
Configuring with Java Configuration .................................................................
26.2. Outbound Channel Adapter ............................................................................
Configuring with Java Configuration .................................................................
Redis Support ..........................................................................................................
27.1. Connecting to Redis .......................................................................................
Using RedisConnectionFactory ................................................................
Using RedisTemplate ..................................................................................
27.2. Messaging with Redis ....................................................................................
Redis Publish/Subscribe channel .....................................................................
Redis Inbound Channel Adapter ......................................................................
Redis Outbound Channel Adapter ...................................................................
Redis Queue Inbound Channel Adapter ...........................................................

5.1.1.RELEASE

Spring Integration

402
402
403
403
404
405
406
406
408
408
411
412
412
413
414
415
415
416
416
418
420
422
422
423
425
425
425
426
427
427
428
430
430
431
432
434
434
436
436
437
438
440
440
440
441
441
441
442
442
443

xiv

Spring Integration Reference Manual

Redis Queue Outbound Channel Adapter ........................................................
Redis Application Events ................................................................................
27.3. Redis Message Store .....................................................................................
Redis Channel Message Stores ......................................................................
27.4. Redis Metadata Store ....................................................................................
27.5. Redis Store Inbound Channel Adapter ............................................................
27.6. RedisStore Outbound Channel Adapter ...........................................................
27.7. Redis Outbound Command Gateway ..............................................................
27.8. Redis Queue Outbound Gateway ....................................................................
27.9. Redis Queue Inbound Gateway ......................................................................
27.10. Redis Lock Registry .....................................................................................
28. Resource Support .....................................................................................................
28.1. Resource Inbound Channel Adapter ................................................................
29. RMI Support .............................................................................................................
29.1. Outbound RMI ...............................................................................................
29.2. Inbound RMI ..................................................................................................
29.3. RMI namespace support ................................................................................
29.4. Configuring with Java Configuration ................................................................
30. SFTP Adapters .........................................................................................................
30.1. SFTP Session Factory ...................................................................................
Configuration Properties ..................................................................................
30.2. Proxy Factory Bean .......................................................................................
30.3. Delegating Session Factory ............................................................................
30.4. SFTP Session Caching ..................................................................................
30.5. Using RemoteFileTemplate ........................................................................
30.6. SFTP Inbound Channel Adapter .....................................................................
More on File Filtering and Large Files .............................................................
Recovering from Failures ................................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
Dealing With Incomplete Data .........................................................................
30.7. SFTP Streaming Inbound Channel Adapter .....................................................
Configuring with Java Configuration .................................................................
30.8. Inbound Channel Adapters: Polling Multiple Servers and Directories ..................
30.9. Inbound Channel Adapters: Controlling Remote File Fetching ...........................
30.10. SFTP Outbound Channel Adapter .................................................................
SpEL and the SFTP Outbound Adapter ...........................................................
Avoiding Partially Written Files ........................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
30.11. SFTP Outbound Gateway .............................................................................
Using the ls Command ..................................................................................
Using the get Command ................................................................................
Using the mget Command ..............................................................................
Using the put Command ................................................................................
Using the mput Command ..............................................................................
Using the mv Command ..................................................................................
Additional Command Information .....................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................

5.1.1.RELEASE

Spring Integration

444
445
445
446
446
447
449
450
451
452
453
454
454
456
456
456
456
457
458
458
459
460
461
461
462
463
465
465
466
467
468
468
469
470
472
473
473
473
474
475
476
476
477
478
479
479
480
480
481
481

xv

Spring Integration Reference Manual

31.

32.

33.

34.

Outbound Gateway Partial Success (mget and mput) ......................................
30.12. SFTP/JSCH Logging ....................................................................................
30.13. MessageSessionCallback .............................................................................
STOMP Support .......................................................................................................
31.1. Overview .......................................................................................................
31.2. STOMP Inbound Channel Adapter ..................................................................
31.3. STOMP Outbound Channel Adapter ...............................................................
31.4. STOMP Headers Mapping ..............................................................................
31.5. STOMP Integration Events .............................................................................
31.6. STOMP Adapters Java Configuration ..............................................................
31.7. STOMP Namespace Support ..........................................................................
Understanding the  Element .....
Understanding the  Element .......
Stream Support ........................................................................................................
32.1. Reading from Streams ...................................................................................
32.2. Writing to Streams .........................................................................................
32.3. Stream Namespace Support ...........................................................................
Syslog Support .........................................................................................................
33.1. Syslog Inbound Channel Adapter ....................................................................
Example Configuration ....................................................................................
TCP and UDP Support .............................................................................................
34.1. Introduction ....................................................................................................
34.2. UDP Adapters ...............................................................................................
Outbound UDP Adapters (XML Configuration) ..................................................
Outbound UDP Adapters (Java Configuration) ..................................................
Outbound UDP Adapters (Java DSL Configuration) ..........................................
Inbound UDP Adapters (XML Configuration) ....................................................
Inbound UDP Adapters (Java Configuration) ....................................................
Inbound UDP Adapters (Java DSL Configuration) .............................................
Server Listening Events ..................................................................................
Advanced Outbound Configuration ..................................................................
34.3. TCP Connection Factories ..............................................................................
TCP Caching Client Connection Factory ..........................................................
TCP Failover Client Connection Factory ..........................................................
TCP Thread Affinity Connection Factory ..........................................................
34.4. TCP Connection Interceptors ..........................................................................
34.5. TCP Connection Events .................................................................................
34.6. TCP Adapters ................................................................................................
34.7. TCP Gateways ..............................................................................................
34.8. TCP Message Correlation ..............................................................................
Gateways .......................................................................................................
Collaborating Outbound and Inbound Channel Adapters ...................................
Transferring Headers ......................................................................................
34.9. About Non-blocking I/O (NIO) .........................................................................
Pool Size .......................................................................................................
Thread Pool Task Executor with CALLER_RUNS Policy .....................................
34.10. SSL/TLS Support .........................................................................................
Getting Started ...............................................................................................
Host Verification .............................................................................................
34.11. Advanced Techniques ..................................................................................

5.1.1.RELEASE

Spring Integration

482
483
483
484
484
484
485
485
485
486
487
488
489
490
490
491
491
493
493
494
496
496
497
497
498
498
498
499
499
499
499
500
504
504
505
505
506
507
509
510
510
510
511
513
513
513
515
515
516
517

xvi

Spring Integration Reference Manual

35.

36.

37.

38.

Strategy Interfaces .........................................................................................
The TcpSSLContextSupport Strategy Interface ....................................
The TcpSocketFactorySupport Strategy Interface ..............................
The TcpSocketSupport Strategy Interface ............................................
The TcpNetConnectionSupport Strategy Interface ..............................
The TcpNioConnectionSupport Strategy Interface ..............................
Example: Enabling SSL Client Authentication ...................................................
34.12. IP Configuration Attributes ............................................................................
34.13. IP Message Headers ....................................................................................
34.14. Annotation-Based Configuration ....................................................................
WebFlux Support ......................................................................................................
35.1. WebFlux Inbound Components .......................................................................
35.2. WebFlux Outbound Components ....................................................................
35.3. WebFlux Namespace Support ........................................................................
Inbound ..........................................................................................................
Outbound .......................................................................................................
35.4. Configuring WebFlux Endpoints with Java .......................................................
35.5. WebFlux Header Mappings ............................................................................
WebSockets Support ................................................................................................
36.1. Overview .......................................................................................................
36.2. WebSocket Inbound Channel Adapter .............................................................
36.3. WebSocket Outbound Channel Adapter ..........................................................
36.4. WebSockets Namespace Support ...................................................................
 Attributes .......................................
 Attributes .......................................
 Attributes .......................
 Attributes .........................
36.5. Using ClientStompEncoder ........................................................................
Web Services Support ..............................................................................................
37.1. Outbound Web Service Gateways ...................................................................
37.2. Inbound Web Service Gateways .....................................................................
37.3. Web Service Namespace Support ...................................................................
37.4. Outbound URI Configuration ...........................................................................
Controlling URI Encoding ................................................................................
37.5. WS Message Headers ...................................................................................
37.6. MTOM Support ..............................................................................................
XML Support - Dealing with XML Payloads ................................................................
38.1. Namespace Support .......................................................................................
XPath Expressions .........................................................................................
Providing Namespaces (Optional) to XPath Expressions ...........................
Using XPath Expressions with Default Namespaces .................................
38.2. Transforming XML Payloads ...........................................................................
Configuring Transformers as Beans .................................................................
UnmarshallingTransformer ......................................................................
Using MarshallingTransformer ........................................................
XsltPayloadTransformer ..........................................................................
Using ResultTransformer Implementations .........................................
Namespace Support for XML Transformers ......................................................
Using an UnmarshallingTransformer ................................................
Using a MarshallingTransformer .....................................................

5.1.1.RELEASE

Spring Integration

517
517
517
518
518
519
519
520
527
529
532
532
533
534
534
535
535
536
537
537
538
539
540
540
541
542
543
544
545
545
546
546
548
548
548
550
551
551
552
553
553
554
555
555
555
556
556
557
557
557

xvii

Spring Integration Reference Manual

Using an XsltPayloadTransformer .................................................... 558
Namespace Configuration and Result Transformers ......................................... 559
XsltPayloadTransformer and  ..... 560
38.3. Transforming XML Messages with XPath ........................................................ 560
Simple XPath Transformation .......................................................................... 560
Node Mappers ................................................................................................ 561
XML Payload Converter .................................................................................. 561
38.4. Splitting XML Messages ................................................................................. 562
38.5. Routing XML Messages with XPath ................................................................ 563
XML Payload Converter .................................................................................. 564
38.6. XPath Header Enricher .................................................................................. 565
38.7. Using the XPath Filter .................................................................................... 566
38.8. #xpath SpEL Function .................................................................................... 567
38.9. XML Validating Filter ...................................................................................... 567
39. XMPP Support ......................................................................................................... 569
39.1. XMPP Connection .......................................................................................... 569
39.2. XMPP Messages ........................................................................................... 570
Inbound Message Channel Adapter ................................................................. 570
Outbound Message Channel Adapter .............................................................. 571
39.3. XMPP Presence ............................................................................................ 572
Inbound Presence Message Channel Adapter .................................................. 572
Outbound Presence Message Channel Adapter ............................................... 572
39.4. Advanced Configuration ................................................................................. 573
39.5. XMPP Message Headers ............................................................................... 574
39.6. XMPP Extensions .......................................................................................... 574
40. Zookeeper Support ................................................................................................... 577
40.1. Zookeeper Metadata Store ............................................................................. 577
40.2. Zookeeper Lock Registry ................................................................................ 577
40.3. Zookeeper Leadership Event Handling ............................................................ 578
VI. Appendices ....................................................................................................................... 579
A. Spring Expression Language (SpEL) ........................................................................... 580
A.1. SpEL Evaluation Context Customization ........................................................... 580
A.2. SpEL Functions ............................................................................................... 581
Built-in SpEL Functions ................................................................................... 582
A.3. Property Accessors ......................................................................................... 582
B. Message Publishing ................................................................................................... 584
B.1. Message Publishing Configuration .................................................................... 584
Annotation-driven Configuration with the @Publisher Annotation ..................... 584
XML-based Approach with the  element ............ 586
Asynchronous Publishing ........................................................................ 588
Producing and Publishing Messages Based on a Scheduled Trigger .................. 588
C. Transaction Support ................................................................................................... 590
C.1. Understanding Transactions in Message flows .................................................. 590
Poller Transaction Support .............................................................................. 591
C.2. Transaction Boundaries ................................................................................... 592
C.3. Transaction Synchronization ............................................................................ 593
C.4. Pseudo Transactions ....................................................................................... 595
D. Security in Spring Integration ...................................................................................... 596
D.1. Securing channels ........................................................................................... 596
D.2. Security Context Propagation ........................................................................... 598

5.1.1.RELEASE

Spring Integration

xviii

Spring Integration Reference Manual

E. Configuration .............................................................................................................
E.1. Namespace Support ........................................................................................
E.2. Configuring the Task Scheduler .......................................................................
E.3. Error Handling .................................................................................................
E.4. Global Properties .............................................................................................
E.5. Annotation Support ..........................................................................................
Using the @Poller Annotation .......................................................................
Using the @InboundChannelAdapter Annotation ..........................................
Using the @IntegrationComponentScan Annotation ....................................
E.6. Messaging Meta-Annotations ...........................................................................
Annotations on @Bean Methods ......................................................................
Creating a Bridge with Annotations ..................................................................
Advising Annotated Endpoints .........................................................................
E.7. Message Mapping Rules and Conventions ........................................................
Sample Scenarios ..........................................................................................
Annotation-based Mapping ..............................................................................
Complex Scenarios .........................................................................................
F. Testing support ..........................................................................................................
F.1. Testing Utilities ................................................................................................
TestUtils .........................................................................................................
Using the SocketUtils Class .......................................................................
Using OnlyOnceTrigger ..............................................................................
Support Components ......................................................................................
JUnit Rules and Conditions .............................................................................
Hamcrest and Mockito Matchers .....................................................................
F.2. Spring Integration and the Test Context ............................................................
F.3. Integration Mocks ............................................................................................
MockIntegration ..............................................................................................
F.4. Other Resources .............................................................................................
G. Spring Integration Samples ........................................................................................
G.1. Where to Get Samples ....................................................................................
G.2. Submitting Samples or Sample Requests .........................................................
How Can I Contribute My Own Samples? ........................................................
Code Contribution Process .............................................................................
Sample Requests ...........................................................................................
G.3. Samples Structure ...........................................................................................
G.4. Samples .........................................................................................................
Loan Broker ...................................................................................................
Design ...................................................................................................
Composed Message Processor ...............................................................
The Cafe Sample ...........................................................................................
The XML Messaging Sample ..........................................................................
H. Additional Resources .................................................................................................
I. Change History ...........................................................................................................
I.1. Changes between 4.3 and 5.0 ...........................................................................
I.2. New Components .............................................................................................
Java DSL .......................................................................................................
Testing Support ..............................................................................................
MongoDB Outbound Gateway .........................................................................
WebFlux Gateways and Channel Adapters ......................................................

5.1.1.RELEASE

Spring Integration

600
600
601
602
604
605
607
609
609
609
610
612
613
613
613
614
615
618
619
619
619
620
621
621
621
622
623
623
624
625
625
625
626
626
626
626
627
628
629
630
632
637
638
639
639
639
639
639
639
639

xix

Spring Integration Reference Manual

I.3.

I.4.
I.5.

I.6.

5.1.1.RELEASE

Content Type Conversion ...............................................................................
ErrorMessagePublisher and ErrorMessageStrategy .............................
JDBC Metadata Store .....................................................................................
General Changes .............................................................................................
Core Changes ................................................................................................
Gateway Changes ..........................................................................................
Aggregator Performance Changes ...................................................................
Splitter Changes .............................................................................................
JMS Changes ................................................................................................
Mail Changes .................................................................................................
Feed Changes ................................................................................................
File Changes ..................................................................................................
FTP and SFTP Changes ................................................................................
Integration Properties ......................................................................................
Stream Changes ............................................................................................
Barrier Changes .............................................................................................
AMQP Changes .............................................................................................
HTTP Changes ..............................................................................................
MQTT Changes ..............................................................................................
STOMP Changes ...........................................................................................
Web Services Changes ..................................................................................
Redis Changes ...............................................................................................
TCP Changes ................................................................................................
Gemfire Changes ...........................................................................................
JDBC Changes ..............................................................................................
Metrics Changes ............................................................................................
@EndpointId Annotations .............................................................................
Changes between 4.2 and 4.3 ...........................................................................
New Components .............................................................................................
AMQP Async Outbound Gateway ....................................................................
MessageGroupFactory ................................................................................
PersistentMessageGroup ..........................................................................
FTP and SFTP Streaming Inbound Channel Adapters ......................................
StreamTransformer ....................................................................................
Integration Graph ............................................................................................
JDBC Lock Registry .......................................................................................
LeaderInitiator for LockRegistry ..........................................................
General Changes .............................................................................................
Core Changes ................................................................................................
Outbound Gateway within a Chain ..........................................................
Asynchronous Service Activator ..............................................................
Messaging Annotation Support changes ..................................................
Mail Changes .................................................................................................
Customizable User Flag ..........................................................................
Mail Message Mapping ...........................................................................
JMS Changes ................................................................................................
Header Mapper ......................................................................................
Asynchronous Gateway ..........................................................................
Aggregator Changes .......................................................................................
TCP/UDP Changes .........................................................................................

Spring Integration

639
639
640
640
640
641
641
641
641
641
641
641
642
643
643
643
643
643
643
644
644
644
644
644
645
645
645
645
645
645
645
645
646
646
646
646
646
646
646
646
646
646
647
647
647
647
647
647
647
647

xx

Spring Integration Reference Manual

Events ...................................................................................................
Stream Deserializers ...............................................................................
TCP Message Mapper ............................................................................
File Changes ..................................................................................................
Destination Directory Creation .................................................................
Buffer Size .............................................................................................
Appending and Flushing .........................................................................
Preserving Timestamps ...........................................................................
Splitter Changes .....................................................................................
File Filters ..............................................................................................
AMQP Changes .............................................................................................
Content Type Message Converter ...........................................................
Headers for Delayed Message Handling ..................................................
AMQP-Backed Channels .........................................................................
Redis Changes ...............................................................................................
List Push/Pop Direction ...........................................................................
Queue Inbound Gateway Default Serializer ..............................................
HTTP Changes ..............................................................................................
SFTP Changes ...............................................................................................
Factory Bean ..........................................................................................
chmod Changes .....................................................................................
FTP Changes .................................................................................................
Session Changes ...................................................................................
Router Changes .............................................................................................
Header Mapping .............................................................................................
General ..................................................................................................
AMQP Header Mapping ..........................................................................
Groovy Scripts ................................................................................................
@InboundChannelAdapter Changes ............................................................
XMPP Changes ..............................................................................................
WireTap Late Binding .....................................................................................
ChannelMessageStoreQueryProvider Changes ........................................
WebSocket Changes ......................................................................................
I.7. Changes between 4.1 and 4.2 ...........................................................................
I.8. New Components .............................................................................................
Major Management/JMX Rework .....................................................................
MongoDB Metadata Store ...............................................................................
SecuredChannel Annotation ............................................................................
SecurityContext Propagation .....................................................................
FileSplitter ......................................................................................................
Zookeeper Support .........................................................................................
Thread Barrier ................................................................................................
STOMP Support .............................................................................................
Codec ............................................................................................................
Message PreparedStatement Setter ................................................................
I.9. General Changes .............................................................................................
WireTap .........................................................................................................
File Changes ..................................................................................................
Appending New Lines .............................................................................
Ignoring Hidden Files ..............................................................................

5.1.1.RELEASE

Spring Integration

647
647
648
648
648
648
648
648
648
648
648
648
649
649
649
649
649
649
649
649
649
650
650
650
650
650
650
650
650
650
651
651
651
651
651
651
651
651
651
652
652
652
652
652
652
652
652
652
653
653

xxi

Spring Integration Reference Manual

Writing InputStream Payloads ..............................................................
HeadDirectoryScanner ......................................................................
Last Modified Filter .................................................................................
Watch Service Directory Scanner ............................................................
Persistent File List Filter Changes ...........................................................
Class Package Change ..................................................................................
TCP Changes ................................................................................................
TCP Serializers ......................................................................................
Server Socket Exceptions .......................................................................
TCP Server Port .....................................................................................
TCP Gateway Remote Timeout ...............................................................
TCP SSLSession Available for Header Mapping .......................................
TCP Events ............................................................................................
@InboundChannelAdapter Changes ............................................................
API Changes ..................................................................................................
JMS Changes ................................................................................................
Reply Listener Lazy Initialization ..............................................................
Conversion Errors in Message-Driven Endpoints ......................................
Default Acknowledge Mode .....................................................................
Shared Subscriptions ..............................................................................
Conditional Pollers ..........................................................................................
AMQP Changes .............................................................................................
Publisher Confirmations ..........................................................................
Correlation Data .....................................................................................
Inbound Gateway Properties ...................................................................
XPath Splitter Improvements ...........................................................................
HTTP Changes ..............................................................................................
CORS ....................................................................................................
Inbound Gateway Timeout ......................................................................
Form Data ..............................................................................................
Gateway Changes ..........................................................................................
Gateway Methods can Return CompletableFuture .........................
MessagingGateway Annotation ................................................................
Aggregator Changes .......................................................................................
Aggregator Performance .........................................................................
Output Message Group Processor ...........................................................
FTP and SFTP Changes ................................................................................
Inbound Channel Adapters ......................................................................
Gateway Partial Results ..........................................................................
Delegating Session Factory .....................................................................
Default Sftp Session Factory ...................................................................
Message Session Callback .....................................................................
Websocket Changes .......................................................................................
Application Event Adapters changes ................................................................
I.10. Changes between 4.0 and 4.1 .........................................................................
New Components ...........................................................................................
Promise Gateway .............................................................................
WebSocket support ................................................................................
Scatter-Gather Enterprise Integration Pattern ...........................................
Routing Slip Pattern ................................................................................

5.1.1.RELEASE

Spring Integration

653
653
653
653
653
653
653
653
653
654
654
654
654
654
654
654
654
655
655
655
655
655
655
655
655
656
656
656
656
656
656
656
656
656
656
657
657
657
657
657
657
657
658
658
658
658
658
658
658
658

xxii

Spring Integration Reference Manual

Idempotent Receiver Pattern ...................................................................
Boon JsonObjectMapper .....................................................................
Redis Queue Gateways ..........................................................................
PollSkipAdvice ..................................................................................
General Changes ...........................................................................................
AMQP Inbound Endpoints, Channel .........................................................
AMQP Outbound Endpoints ....................................................................
SimpleMessageStore ..............................................................................
Web Service Outbound Gateway: encode-uri .......................................
Http Inbound Channel Adapter and Status Code .......................................
MQTT Adapter Changes .........................................................................
FTP and SFTP Adapter Changes ............................................................
Splitter and Iterator .................................................................................
Aggregator .............................................................................................
Content Enricher Improvements ..............................................................
Header Channel Registry ........................................................................
Orderly Shutdown ...................................................................................
Management for RecipientListRouter ...............................................
AbstractHeaderMapper: NON_STANDARD_HEADERS token ...................
AMQP Channels: template-channel-transacted .............................
Syslog Adapter .......................................................................................
Asynchronous Gateway ..........................................................................
Aggregator Advice Chain ........................................................................
Outbound Channel Adapter and Scripts ...................................................
Resequencer Changes ...........................................................................
Optional POJO method parameter ...........................................................
QueueChannel backed Queue type ........................................................
ChannelInterceptor Changes ............................................................
IMAP PEEK ...........................................................................................
I.11. Changes between 3.0 and 4.0 .........................................................................
New Components ...........................................................................................
MQTT Channel Adapters ........................................................................
@EnableIntegration ..........................................................................
@IntegrationComponentScan ............................................................
"@EnableMessageHistory" ..................................................................
@MessagingGateway ............................................................................
Spring Boot @EnableAutoConfiguration ...........................................
@GlobalChannelInterceptor ............................................................
@IntegrationConverter ....................................................................
@EnablePublisher ..............................................................................
Redis Channel Message Stores ..............................................................
MongodDB Channel Message Store ........................................................
@EnableIntegrationMBeanExport ....................................................
ChannelSecurityInterceptorFactoryBean ....................................
Redis Command Gateway ......................................................................
RedisLockRegistry and GemfireLockRegistry ...............................
@Poller ................................................................................................
@InboundChannelAdapter and SmartLifecycle for Annotated
Endpoints ...............................................................................................
Twitter Search Outbound Gateway ..........................................................

5.1.1.RELEASE

Spring Integration

658
659
659
659
659
659
659
659
659
659
659
660
660
660
660
660
660
660
661
661
661
661
661
661
661
661
661
661
662
662
662
662
662
662
662
662
662
662
663
663
663
663
663
663
663
663
663
664
664

xxiii

Spring Integration Reference Manual

Gemfire Metadata Store ..........................................................................
@BridgeFrom and @BridgeTo Annotations ............................................
Meta-messaging Annotations ...................................................................
General Changes ...........................................................................................
Requires Spring Framework 4.0 ..............................................................
Header Type for XPath Header Enricher ..................................................
Object To JSON Transformer: Node Result ..............................................
JMS Header Mapping .............................................................................
JMS Outbound Channel Adapter .............................................................
JMS Inbound Channel Adapter ................................................................
Datatype Channels .................................................................................
Simpler Retry Advice Configuration .........................................................
Correlation Endpoint: Time-based Release Strategy .................................
Redis Metadata Store .............................................................................
JdbcChannelMessageStore and PriorityChannel ...........................
AMQP Endpoints Delivery Mode .............................................................
FTP Timeouts ........................................................................................
Twitter: StatusUpdatingMessageHandler ..........................................
JPA Retrieving Gateway: id-expression ..............................................
TCP Deserialization Events .....................................................................
Messaging Annotations on @Bean Definitions ...........................................
I.12. Changes Between 2.2 and 3.0 ........................................................................
New Components ...........................................................................................
HTTP Request Mapping ..........................................................................
Spring Expression Language (SpEL) Configuration ...................................
SpEL Functions Support .........................................................................
SpEL PropertyAccessors Support ............................................................
Redis: New Components ........................................................................
Header Channel Registry ........................................................................
MongoDB support: New ConfigurableMongoDbMessageStore ............
Syslog Support .......................................................................................
tail Support .........................................................................................
JMX Support ..........................................................................................
TCP/IP Connection Events and Connection Management ..........................
Inbound Channel Adapter Script Support .................................................
Content Enricher: Headers Enrichment Support ........................................
General Changes ...........................................................................................
Message ID Generation ..........................................................................
"" Changes ...........................................................................
HTTP Endpoint Changes ........................................................................
Jackson Support (JSON) ........................................................................
Chain Elements id Attribute ...................................................................
Aggregator empty-group-min-timeout property ..........................................
Persistent File List Filters (file, (S)FTP) ....................................................
Scripting Support: Variables Changes ......................................................
Direct Channel Load Balancing configuration ............................................
PublishSubscribeChannel Behavior ..........................................................
FTP, SFTP and FTPS Changes ..............................................................
requires-reply Attribute for Outbound Gateways ........................................
AMQP Outbound Gateway Header Mapping ............................................

5.1.1.RELEASE

Spring Integration

664
664
664
664
664
664
664
665
665
665
665
665
665
665
665
665
666
666
666
666
666
666
666
666
667
667
667
667
667
667
667
668
668
668
668
668
668
669
669
669
669
670
670
670
670
670
670
670
671
672

xxiv

Spring Integration Reference Manual

Stored Procedure Components Improvements ..........................................
Web Service Outbound URI Configuration ...............................................
Redis Adapter Changes ..........................................................................
Advising Filters .......................................................................................
Advising Endpoints using Annotations ......................................................
ObjectToStringTransformer Improvements ................................................
JPA Support Changes ............................................................................
Delayer: delay expression .......................................................................
JDBC Message Store Improvements .......................................................
IMAP Idle Connection Exceptions ............................................................
Message Headers and TCP ....................................................................
JMS Message Driven Channel Adapter ....................................................
RMI Inbound Gateway ............................................................................
XsltPayloadTransformer ..................................................................
I.13. Changes between 2.1 and 2.2 .........................................................................
New Components ...........................................................................................
RedisStore Inbound and Outbound Channel Adapters ...........................
MongoDB Inbound and Outbound Channel Adapters ................................
JPA Endpoints ........................................................................................
General Changes ...........................................................................................
Spring 3.1 Used by Default .....................................................................
Adding Behavior to Endpoints .................................................................
Transaction Synchronization and Pseudo Transactions .............................
File Adapter: Improved File Overwrite and Append Handling ......................
Reply-Timeout Added to More Outbound Gateways ..................................
Spring-AMQP 1.1 ...................................................................................
JDBC Support - Stored Procedures Components ......................................
JDBC Support: Outbound Gateway .........................................................
JDBC Support: Channel-specific Message Store Implementation ...............
Orderly Shutdown ...................................................................................
JMS Outbound Gateway Improvements ...................................................
ObjectToJsonTransformer ................................................................
HTTP Support ........................................................................................
I.14. Changes between 2.0 and 2.1 .........................................................................
New Components ...........................................................................................
JSR-223 Scripting Support ......................................................................
GemFire Support ....................................................................................
AMQP Support .......................................................................................
MongoDB Support ..................................................................................
Redis Support ........................................................................................
Support for Spring’s Resource abstraction ...............................................
Stored Procedure Components ................................................................
XPath and XML Validating Filter ..............................................................
Payload Enricher ....................................................................................
FTP and SFTP Outbound Gateways ........................................................
FTP Session Caching .............................................................................
Framework Refactoring ...................................................................................
Standardizing Router Configuration ..........................................................
XML Schemas updated to 2.1 .................................................................
Source Control Management and Build Infrastructure .......................................

5.1.1.RELEASE

Spring Integration

672
673
673
673
673
673
673
674
674
674
674
674
674
674
675
675
675
675
675
675
675
675
676
676
676
676
677
677
677
677
677
677
678
678
678
678
678
678
679
679
679
679
680
680
680
680
680
680
681
681

xxv

Spring Integration Reference Manual

Source Code Now Hosted on Github .......................................................
Improved Source Code Visibility with Sonar .............................................
New Samples .................................................................................................
I.15. Changes between Versions 1.0 and 2.0 ...........................................................
Spring 3 support .............................................................................................
Support for the Spring Expression Language (SpEL) ................................
Conversion Service and Converter ..........................................................
TaskScheduler and Trigger ..............................................................
RestTemplate and HttpMessageConverter ......................................
Enterprise Integration Pattern Additions ...........................................................
Message History .....................................................................................
Message Store .......................................................................................
Claim Check ..........................................................................................
Control Bus ............................................................................................
New Channel Adapters and Gateways .............................................................
TCP and UDP Adapters ..........................................................................
Twitter Adapters .....................................................................................
XMPP Adapters ......................................................................................
FTP and FTPS Adapters .........................................................................
SFTP Adapters .......................................................................................
Feed Adapters ........................................................................................
Other Additions ..............................................................................................
Groovy Support ......................................................................................
Map Transformers ..................................................................................
JSON Transformers ................................................................................
Serialization Transformers .......................................................................
Framework Refactoring ...................................................................................
New Source Control Management and Build Infrastructure ................................
New Spring Integration Samples .....................................................................
Spring Tool Suite Visual Editor for Spring Integration ........................................

5.1.1.RELEASE

Spring Integration

682
682
682
682
682
682
682
682
683
683
683
683
683
683
683
683
683
684
684
684
684
684
684
684
684
684
684
685
685
685

xxvi

Spring Integration Reference Manual

© 2009-2018 Pivotal Software, Inc. All rights reserved.
Note
Copies of this document may be made for your own use and for distribution to others, provided
that you do not charge any fee for such copies and further provided that each copy contains this
Copyright Notice, whether distributed in print or electronically.

5.1.1.RELEASE

Spring Integration

xxvii

Part I. Preface
This chapter includes:
• Chapter 1, Requirements
• Chapter 2, Code Conventions
• Chapter 3, Conventions in This Guide

Spring Integration Reference Manual

1. Requirements
This section details the compatible Java and Spring Framework versions.

1.1 Compatible Java Versions
For Spring Integration 5.1.x, the minimum compatible Java version is Java SE 8. Older versions of Java
are not supported.

1.2 Compatible Versions of the Spring Framework
Spring Integration 5.1.x requires Spring Framework 5.1 or later.

5.1.1.RELEASE

Spring Integration

2

Spring Integration Reference Manual

2. Code Conventions
Spring Framework 2.0 introduced support for namespaces, which simplifies the XML configuration of
the application context and lets Spring Integration provide broad namespace support.
In this reference guide, the int namespace prefix is used for Spring Integration’s core namespace
support. Each Spring Integration adapter type (also called a module) provides its own namespace, which
is configured by using the following convention:
The following example shows the int, int-event, and int-stream namespaces in use:



For a detailed explanation regarding Spring Integration’s namespace support, see Section E.1,
“Namespace Support”.
Note
The namespace prefix can be freely chosen. You may even choose not to use any namespace
prefixes at all. Therefore, you should apply the convention that best suits your application. Be
aware, though, that SpringSource Tool Suite™ (STS) uses the same namespace conventions for
Spring Integration as used in this reference guide.

5.1.1.RELEASE

Spring Integration

3

Spring Integration Reference Manual

3. Conventions in This Guide
In some cases, to aid formatting when specifying long fully qualified class names, we shorten
org.springframework to o.s and org.springframework.integration to o.s.i, such as with
o.s.i.transaction.TransactionSynchronizationFactory.

5.1.1.RELEASE

Spring Integration

4

Part II. What’s New?
For those who are already familiar with Spring Integration, this chapter provides a brief overview of the
new features of version 5.1. If you are interested in the changes and features that were introduced in
earlier versions, see the Appendix I, Change History.

Spring Integration Reference Manual

4. What’s New in Spring Integration 5.1?
This chapter provides an overview of the new features and improvements that have been introduced
with Spring Integration 5.1. If you are interested in more details, see the Issue Tracker tickets that were
resolved as part of the 5.1 development process.

4.1 New Components
The following components are new in 5.1:
• the section called “AmqpDedicatedChannelAdvice”

AmqpDedicatedChannelAdvice
See Section 14.13, “Strict Message Ordering”.

Improved Function Support
The java.util.function interfaces now have improved integration support in the Framework
components. Also Kotlin lambdas now can be used for handler and source methods.
See Section 10.11, “java.util.function Interfaces Support”.

@LongRunningTest
A JUnit 5 @LongRunningTest conditional annotation is provided to check the environment or system
properties for the RUN_LONG_INTEGRATION_TESTS entry with the value of true to determine if test
should be run or skipped.
See the section called “JUnit Rules and Conditions”.

4.2 General Changes
The following changes have been made in version 5.1:
• the section called “Java DSL”
• the section called “Dispatcher Exceptions”
• the section called “Global Channel Interceptors”
• the section called “ObjectToJsonTransformer”
• the section called “Integration Flows: Generated Bean Names”
• the section called “Aggregator Changes”
• the section called “@Publisher annotation changes”
• Section 4.13, “Integration Graph Customization”
• Section 4.14, “Integration Global Properties”

5.1.1.RELEASE

Spring Integration

6

Spring Integration Reference Manual

• Section 4.15, “The receiveTimeout for @Poller”

Java DSL
The IntegrationFlowContext is now an interface and IntegrationFlowRegistration is an
inner interface of IntegrationFlowContext.
A new logAndReply() operator has been introduced for convenience when you wish to log at the
end of a flow for request-reply configurations. This avoid confusion with log() which is treated as a
one-way end flow component.
A generated bean name for any NamedComponent within an integration flow is now based on the
component type for better readability from visual tools, logs analyzers and metrics collectors.
The GenericHandler.handle() now excepts a MessageHeaders type for the second argument.

Dispatcher Exceptions
Exceptions caught and re-thrown by AbstractDispatcher are now more consistent:
• A MessagingException of any kind that has a failedMessage property is re-thrown unchanged.
• All other exceptions are wrapped in a MessageDeliveryException with the failedMessage
property set.
Previously:
• A MessagingException of any kind that has a failedMessage property was re-thrown
unchanged
• A MessagingException that had no failedMessage property was wrapped in a
MessagingException with the failedMessage property set.
• Other RuntimeException instances were re-thrown unchanged.
• Checked exceptions were wrapped in a MessageDeliveryException with the failedMessage
property set.

Global Channel Interceptors
Global channel interceptors now apply to dynamically registered channels, such as through
the IntegrationFlowContext when using the Java DSL or beans that are initialized using
beanFactory.initializeBean(). Previously, when beans were created after the application
context was refreshed, interceptors were not applied.

Channel Interceptors
ChannelInterceptor.postReceive() is no longer called when no message is received; it is
no longer necessary to check for a null Message. Previously, the method was called. If you
have an interceptor that relies on the previous behavior, implement afterReceiveCompleted()
instead, since that method is invoked, regardless of whether a message is received or not.
Furthermore, the PolledAmqpChannel and PolledJmsChannel previously did not invoke
afterReceiveCompleted() with null; they now do.

5.1.1.RELEASE

Spring Integration

7

Spring Integration Reference Manual

ObjectToJsonTransformer
A new ResultType.BYTES mode is introduced for the ObjectToJsonTransformer.
See the section called “JSON Transformers” for more information.

Integration Flows: Generated Bean Names
Starting with version 5.0.5, generated bean names for the components in an IntegrationFlow
include the flow bean name, followed by a dot, as a prefix. For example, if a flow bean were named
flowBean, a generated bean might be named flowBean.generatedBean.
See Section 11.13, “Working With Message Flows” for more information.

Aggregator Changes
If the groupTimeout is evaluated to a negative value, an aggregator now expires the group
immediately. Only null is considered as a signal to do nothing for the current message.
A
new
popSequence
property
has
been
introduced
to
allow
(by
default)
to
call
a
MessageBuilder.popSequenceDetails()
for
the
output
message. Also an AbstractAggregatingMessageGroupProcessor returns now an
AbstractIntegrationMessageBuilder instead of the whole Message for optimization.
See Section 8.4, “Aggregator” for more information.

@Publisher annotation changes
Starting with version 5.1, you must explicitly turn on the @Publisher AOP functionality
by using @EnablePublisher or by using the  child element on
.
See the section called “Annotation-driven Configuration with the @Publisher Annotation” for more
information.

4.3 Files Changes
If you are using FileExistsMode.APPEND or FileExistsMode.APPEND_NO_FLUSH you can
provide a newFileCallback that will be called when creating a new file. This callback receives the
newly created file and the message that triggered the callback. This could be used to write a CSV
header, for an example.
The FileReadingMessageSource now doesn’t check and create a directory until its start() is
called. So, if an Inbound Channel Adapter for the FileReadingMessageSource has autoStartup
= false, there are no failures against the file system during application start up.
See Chapter 17, File Support for more information.

4.4 AMQP Changes
We have made ID and Timestamp header mapping changes in the DefaultAmqpHeaderMapper.
See the note near the bottom of Section 14.12, “AMQP Message Headers” for more information.

5.1.1.RELEASE

Spring Integration

8

Spring Integration Reference Manual

The contentType header is now correctly mapped as an entry in the general headers map. See the
section called “contentType Header” for more information.

4.5 JDBC Changes
A confusing max-rows-per-poll property on the JDBC Inbound Channel Adapter and JDBC
Outbound Gateway has been deprecated in favor of the newly introduced max-rows property.
The JdbcMessageHandler supports now a batchUpdate functionality when the payload of the
request message is an instance of an Iterable type.
See Chapter 21, JDBC Support for more information.

4.6 FTP and SFTP Changes
A RotatingServerAdvice is now available to poll multiple servers and directories with the inbound
channel adapters. See Section 18.6, “Inbound Channel Adapters: Polling Multiple Servers and
Directories” and Section 30.8, “Inbound Channel Adapters: Polling Multiple Servers and Directories” for
more information.
Also, inbound adapter localFilenameExpression instances can contain the #remoteDirectory
variable, which contains the remote directory being polled. The generic type of the
comparators (used to sort the fetched file list for the streaming adapters) has changed from
Comparator> to Comparator. See Section 18.5, “FTP Streaming
Inbound Channel Adapter” and Section 30.7, “SFTP Streaming Inbound Channel Adapter” for more
information.
In addition, the synchronizers for inbound channel adapters can now be provided with a Comparator.
This is useful when using maxFetchSize to limit the files retrieved.
The CachingSessionFactory has a new property testSession which, when true, causes the
factory to perform a test() operation on the Session when checking out an existing session from
the cache.
See Section 30.4, “SFTP Session Caching” and Section 18.10, “FTP Session Caching” for more
information.
The outbound gateway MPUT command now supports a message payload with a collection of files or
strings. See Section 30.11, “SFTP Outbound Gateway” and Section 18.9, “FTP Outbound Gateway”
for more information.

4.7 TCP Support
When using SSL, host verification is now enabled, by default, to prevent man-in-the-middle attacks with
a trusted certificate. See the section called “Host Verification” for more information.
In addition the key and trust
DefaultTcpSSLContextSupport.

store

types

can

now

be

configured

on

the

4.8 Twitter Support
Since the Spring Social project has moved to end of life status, Twitter support in Spring Integration has
been moved to the Extensions project. See Spring Integration Social Twitter for more information.

5.1.1.RELEASE

Spring Integration

9

Spring Integration Reference Manual

4.9 JMS Support
The
JmsSendingMessageHandler
now
provides
deliveryModeExpression
and
timeToLiveExpression options to determine respective QoS options for JMS message to send
at runtime. The DefaultJmsHeaderMapper now allows to map inbound JMSDeliveryMode
and JMSExpiration properties via setting to true respective setMapInboundDeliveryMode()
and setMapInboundExpiration() options. When a JmsMessageDrivenEndpoint or
JmsInboundGateway is stopped, the associated listener container is now shut down; this closes its
shared connection and any consumers. You can configure the endpoints to revert to the previous
behavior.
See Chapter 23, JMS Support for more information.

4.10 HTTP/WebFlux Support
The statusCodeExpression (and Function) is now supplied with the RequestEntity as a
root object for evaluation context, so request headers, method, URI and body are available for target
status code calculation.
See Chapter 20, HTTP Support and Chapter 35, WebFlux Support for more information.

4.11 JMX Changes
Object name key values are now quoted if they contain any characters other than those allowed in a
Java identifier (or period .). e.g. org.springframework.integration:type=MessageChannel,
name="input:foo.myGroup.errors".
This
has
the
side
effect
that
previously
"allowed"
names,
with
such
characters,
will
now
be
quoted.
e.g.
org.springframework.integration:type=MessageChannel,
name="input#foo.myGroup.errors".

4.12 Micrometer Support Changes
It is now simpler to customize the standard Micrometer meters created by the framework. See the section
called “Micrometer Integration” for more information.

4.13 Integration Graph Customization
It is now possible to add additional properties to the IntegrationNode s via
Function> additionalPropertiesCallback
on the IntegrationGraphServer. See Section 12.8, “Integration Graph” for more information.

4.14 Integration Global Properties
The Integration global properties (including defaults) can now be printed in the logs, when a DEBUG logic
level is turned on for the org.springframework.integration category. See Section E.4, “Global
Properties” for more information.

4.15 The receiveTimeout for @Poller
The @Poller annotation now provides a receiveTimeout option for convenience. See the section
called “Using the @Poller Annotation” for more information.

5.1.1.RELEASE

Spring Integration

10

Part III. Overview of Spring
Integration Framework
Spring Integration provides an extension of the Spring programming model to support the well known
Enterprise Integration Patterns. It enables lightweight messaging within Spring-based applications and
supports integration with external systems through declarative adapters. Those adapters provide a
higher level of abstraction over Spring’s support for remoting, messaging, and scheduling. Spring
Integration’s primary goal is to provide a simple model for building enterprise integration solutions while
maintaining the separation of concerns that is essential for producing maintainable, testable code.

Spring Integration Reference Manual

5. Spring Integration Overview
This chapter provides a high-level introduction to Spring Integration’s core concepts and components.
It includes some programming tips to help you make the most of Spring Integration.

5.1 Background
One of the key themes of the Spring Framework is Inversion of Control (IoC). In its broadest sense,
this means that the framework handles responsibilities on behalf of the components that are managed
within its context. The components themselves are simplified, because they are relieved of those
responsibilities. For example, dependency injection relieves the components of the responsibility of
locating or creating their dependencies. 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 system that is easier to test, understand, maintain, and extend.
Furthermore, the Spring framework and portfolio provide a comprehensive programming model for
building enterprise applications. Developers benefit from the consistency of this model and especially
from the fact that it is based upon well established best practices, such as programming to interfaces and
favoring composition over inheritance. Spring’s simplified abstractions and powerful support libraries
boost 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 programming
model into the messaging domain and builds upon Spring’s existing enterprise integration support to
provide an even higher level of abstraction. It supports message-driven architectures where inversion
of control applies to runtime concerns, such as when certain business logic should run and where the
response should be sent. It supports routing and transformation of messages so that different transports
and different data formats can be integrated without impacting testability. In other words, the messaging
and integration concerns are handled by the framework. Business components are further isolated from
the infrastructure, and developers are relieved of complex integration responsibilities.
As an extension of the Spring programming model, Spring Integration provides a wide variety of
configuration options, including annotations, XML with namespace support, XML with generic "bean"
elements, and direct usage of the underlying API. That API is based upon well defined strategy interfaces
and non-invasive, delegating adapters. Spring Integration’s design is inspired by the recognition of
a strong affinity between common patterns within Spring and the well known patterns described in
Enterprise Integration Patterns, by Gregor Hohpe and Bobby Woolf (Addison Wesley, 2004). Developers
who have read that book should be immediately comfortable with the Spring Integration concepts and
terminology.

5.2 Goals and Principles
Spring 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:
• Components should be loosely coupled for modularity and testability.

5.1.1.RELEASE

Spring Integration

12

Spring Integration Reference Manual

• 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 reuse
and portability.

5.3 Main Components
From a vertical perspective, a layered architecture facilitates separation of concerns, and interfacebased contracts between layers promote loose coupling. Spring-based applications are typically
designed this way, and the Spring framework and portfolio provide a strong foundation for following
this best practice for the full stack of an enterprise application. Message-driven architectures add a
horizontal perspective, yet these same goals are still relevant. Just as "layered architecture" is
an extremely generic and abstract paradigm, messaging systems typically follow the similarly abstract
"pipes-and-filters" model. The "filters" represent any components capable of producing or
consuming messages, and the "pipes" transport the messages between filters so that the components
themselves remain loosely-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 layer whose contracts are defined as interfaces. Likewise, the "filters" themselves
should be managed within a layer that is logically above the application’s service layer, interacting with
those services through interfaces in much 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 used
by the framework while handling that object. It consists of a payload and headers. The payload can be
of any type, and the headers hold commonly required information such as ID, timestamp, correlation ID,
and return address. Headers are also used for passing values to and from connected transports. For
example, when creating a message from a received file, the file name may be stored in a header to be
accessed by downstream components. Likewise, if a message’s content is ultimately going to be sent by
an outbound mail adapter, the various properties (to, from, cc, subject, and others) may be configured
as message header values by an upstream component. Developers can also store any arbitrary keyvalue pairs in the headers.

Figure 5.1. Message

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

5.1.1.RELEASE

Spring Integration

13

Spring Integration Reference Manual

Figure 5.2. Message Channel
A message channel may follow either point-to-point or publish-subscribe semantics. With a point-topoint channel, no more than one consumer can receive each message sent to the channel. Publishsubscribe channels, on the other hand, attempt to broadcast each message to all subscribers on the
channel. Spring Integration supports both of these models.
Whereas "point-to-point" and "publish-subscribe" define the two options for how many consumers
ultimately receive each message, there is another important consideration: Should the channel buffer
messages? In Spring Integration, pollable channels are capable of buffering Messages within a
queue. The advantage of buffering is that it allows for throttling the inbound messages and thereby
prevents 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 the other hand, a consumer connected to a subscribable channel is simply message-driven. the
section called “Message Channel Implementations” has a detailed discussion of the variety of channel
implementations available in Spring Integration.

Message Endpoint
One of the primary goals of Spring Integration is to simplify the development of enterprise integration
solutions through inversion of control. This means that you should not have to implement consumers
and producers directly, and you should not even have to build messages and invoke send or receive
operations on a message channel. Instead, you should be able to focus on your specific domain model
with 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 you should necessarily connect your existing application code directly. Any real-world enterprise
integration solution requires some amount of code focused upon integration concerns such as routing
and transformation. The important thing is to achieve separation of concerns between the integration
logic and the business logic. In other words, as with the Model-View-Controller (MVC) paradigm for web
applications, the goal should be to provide a thin but dedicated layer that translates inbound requests
into service layer invocations and then translates service layer return values into outbound replies. The
next section provides an overview of the message endpoint types that handle these responsibilities, and,
in upcoming chapters, you can see how Spring Integration’s declarative configuration options provide
a non-invasive way to use each of these.

5.4 Message Endpoints
A Message Endpoint represents the "filter" of a pipes-and-filters architecture. As mentioned earlier,
the endpoint’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 message objects or the message channels. This is similar to the role of a controller in the MVC
paradigm. Just as a controller handles HTTP requests, the message endpoint handles messages. Just
as controllers are mapped to URL patterns, message endpoints are mapped to message channels. The
goal is the same in both cases: isolate application code from the infrastructure. These concepts and all
of the patterns that follow are discussed at length in the Enterprise Integration Patterns book. Here, we

5.1.1.RELEASE

Spring Integration

14

Spring Integration Reference Manual

provide only a high-level description of the main endpoint types supported by Spring Integration and
the roles associated with those types. The chapters that follow elaborate and provide sample code as
well as configuration examples.

Message Transformer
A message transformer is responsible for converting a message’s content or structure and returning
the modified message. Probably the most common type of transformer is one that converts the payload
of the message from one format to another (such as from XML to java.lang.String). Similarly, a
transformer can add, remove, or modify the message’s header values.

Message Filter
A message filter determines whether a message should be passed to an output channel at all. This
simply requires a boolean test method that may check for a particular payload content type, a property
value, the presence of a header, or other conditions. If the message is accepted, it is sent to the
output channel. If not, it is dropped (or, for a more severe implementation, an Exception could be
thrown). Message filters are often used in conjunction with a publish-subscribe channel, where multiple
consumers may receive the same message and use the criteria of the filter to narrow down the set of
messages to be processed.
Note
Be careful not to confuse the generic use of "filter" within the pipes-and-filters architectural
pattern with this specific endpoint type that selectively narrows down the messages flowing
between two channels. The pipes-and-filters concept of a "filter" matches more closely with
Spring Integration’s message endpoint: any component that can be connected to a message
channel in order to send or receive messages.

Message Router
A message router is responsible for deciding what channel or channels (if any) should receive the
message next. Typically, the decision is based upon the message’s content or the metadata available in
the message headers. A message router is often used as a dynamic alternative to a statically configured
output 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 multiple
subscribers, as described earlier.

Figure 5.3. Message Router

Splitter
A splitter is another type of message endpoint whose responsibility is to accept a message from its input
channel, split that message into multiple messages, and send each of those to its output channel. This

5.1.1.RELEASE

Spring Integration

15

Spring Integration Reference Manual

is typically used for dividing a "composite" payload object into a group of messages containing the
subdivided payloads.

Aggregator
Basically a mirror-image of the splitter, the aggregator is a type of message endpoint that receives
multiple messages and combines them into a single message. In fact, aggregators are often downstream
consumers in a pipeline that includes a splitter. Technically, the aggregator is more complex than a
splitter, because it is required to maintain state (the messages to be aggregated), to decide when the
complete 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, discard them, or send them to a
separate channel. Spring Integration provides a CorrelationStrategy, a ReleaseStrategy, and
configurable settings for timeout, whether to send partial results upon timeout, and a 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 of
returning a value, an output message Channel may also be provided.
Note
The 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 the method does not expect a messagetyped parameter). Whenever the service object’s method returns a value, that return value is likewise
converted to a reply message if necessary (if it is not already a message type). That reply message is
sent to the output channel. If no output channel has been configured, the reply is sent to the channel
specified in the message’s "return address", if available.
A request-reply service activator endpoint connects a target object’s method to input and output
Message Channels.

Figure 5.4. Service Activator
Note
As discussed earlier, in Message Channel, channels can be pollable or subscribable. In the
preceding diagram, this is depicted by the "clock" symbol and the solid arrow (poll) and the
dotted arrow (subscribe).

5.1.1.RELEASE

Spring Integration

16

Spring Integration Reference Manual

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 does some
mapping between the message and whatever object or resource is received from or sent to the other
system (file, HTTP Request, JMS message, and others). Depending on the transport, the channel
adapter may also populate or extract message header values. Spring Integration provides a number of
channel adapters, which are described in upcoming chapters.

Figure 5.5. An inbound channel adapter endpoint connects a source system to a MessageChannel.
Note
Message sources can be pollable (for example, POP3) or message-driven_ (for example, IMAP
Idle). In the preceding diagram, this is depicted by the "clock" symbol and the solid arrow (poll)
and the dotted arrow (message-driven).

Figure 5.6. An outbound channel adapter endpoint connects a MessageChannel to a target system.
Note
As discussed earlier in Message Channel, channels can be pollable or subscribable. In the
preceding diagram, this is depicted by the "clock" symbol and the solid arrow (poll) and the
dotted arrow (subscribe).

Endpoint Bean Names
Consuming endpoints (anything with an inputChannel) consist of two beans, the consumer and the
message handler. The consumer has a reference to the message handler and invokes it as messages
arrive.
Consider the following XML example:


Given the preceding example, the bean names are as follows:
• Consumer: someService (the id)
• Handler: someService.handler

5.1.1.RELEASE

Spring Integration

17

Spring Integration Reference Manual

When using Enterprise Integration Pattern (EIP) annotations, the names depend on several factors.
Consider the following example of an annotated POJO:
@Component
public class SomeComponent {
@ServiceActivator(inputChannel = ...)
public String someMethod(...) {
...
}
}

Given the preceding example, the bean names are as follows:
• Consumer: someComponent.someMethod.serviceActivator
• Handler: someComponent.someMethod.serviceActivator.handler
Starting with version 5.0.4, you can modify these names by using the @EndpointId annotation, as the
following example shows:
@Component
public class SomeComponent {
@EndpointId("someService")
@ServiceActivator(inputChannel = ...)
public String someMethod(...) {
...
}
}

Given the preceding example, the bean names are as follows:
• Consumer: someService
• Handler: someService.handler
The @EndpointId creates names as created by the id attribute with XML configuration. Consider the
following example of an annotated bean:
@Configuratiom
public class SomeConfiguration {
@Bean
@ServiceActivator(inputChannel = ...)
public MessageHandler someHandler() {
...
}
}

Given the preceding example, the bean names are as follows:
• Consumer: someConfiguration.someHandler.serviceActivator
• Handler: someHandler (the @Bean name)
Starting with version 5.0.4, you can modify these names by using the @EndpointId annotation, as the
following example shows:

5.1.1.RELEASE

Spring Integration

18

Spring Integration Reference Manual

@Configuratiom
public class SomeConfiguration {
@Bean("someService.handler")

❶

@EndpointId("someService")
@ServiceActivator(inputChannel = ...)
public MessageHandler someHandler() {
...
}

❷

}

❶

Handler: someService.handler (the bean name)

❷

Consumer: someService (the endpoint ID)

The @EndpointId annotation creates names as created by the id attribute with XML configuration,
as long as you use the convention of appending .handler to the @Bean name.
There is one special case where a third bean is created: For architectural reasons, if a
MessageHandler @Bean does not define an AbstractReplyProducingMessageHandler, the
framework wraps the provided bean in a ReplyProducingMessageHandlerWrapper. This wrapper
supports request handler advice handling and emits the normal produced no reply debug log messages.
Its bean name is the handler bean name plus .wrapper (when there is an @EndpointId — otherwise,
it is the normal generated handler name).
Similarly Pollable Message Sources create two beans, a SourcePollingChannelAdapter (SPCA)
and a MessageSource.
Consider the following XML configuration:


Given the preceding XML configuration, the bean names are as follows:
• SPCA: someAdapter (the id)
• Handler: someAdapter.source
Consider the following Java configuration of a POJO to define an @EndpointId:
@EndpointId("someAdapter")
@InboundChannelAdapter(channel = "channel3", poller = @Poller(fixedDelay = "5000"))
public String pojoSource() {
...
}

Given the preceding Java configuration example, the bean names are as follows:
• SPCA: someAdapter
• Handler: someAdapter.source
Consider the following Java configuration of a bean to define an @EndpointID:
@Bean("someAdapter.source")
@EndpointId("someAdapter")
@InboundChannelAdapter(channel = "channel3", poller = @Poller(fixedDelay = "5000"))
public MessageSource source() {
return () -> {
...
};
}

5.1.1.RELEASE

Spring Integration

19

Spring Integration Reference Manual

Given the preceding example, the bean names are as follows:
• SPCA: someAdapter
• Handler: someAdapter.source (as long as you use the convention of appending .source to the
@Bean name)

5.5 Configuration and @EnableIntegration
Throughout this document, you can see references to XML namespace support for declaring elements
in a Spring Integration flow. This support is provided by a series of namespace parsers that generate
appropriate bean definitions to implement a particular component. For example, many endpoints consist
of a MessageHandler bean and a ConsumerEndpointFactoryBean into which the handler and an
input channel name are injected.
The first time a Spring Integration namespace element is encountered, the framework automatically
declares a number of beans (a task scheduler, an implicit channel creator, and others) that are used
to support the runtime environment.
Important
Version 4.0 introduced the @EnableIntegration annotation, to allow the registration of Spring
Integration infrastructure beans (see the Javadoc). This annotation is required when only Java
configuration is used — for example with Spring Boot or Spring Integration Messaging Annotation
support and Spring Integration Java DSL with no XML integration configuration.
The @EnableIntegration annotation is also useful when you have a parent context with no Spring
Integration components and two or more child contexts that use Spring Integration. It lets these common
components be declared once only, in the parent context.
The @EnableIntegration annotation registers many infrastructure components with the application
context. In particular, it:
• Registers some built-in beans, such as errorChannel and its LoggingHandler, taskScheduler
for pollers, jsonPath SpEL-function, and others.
• Adds several BeanFactoryPostProcessor instances to enhance the BeanFactory for global
and default integration environment.
• Adds several BeanPostProcessor instances to enhance or convert and wrap particular beans for
integration purposes.
• Adds annotation processors to parse messaging annotations and registers components for them with
the application context.
The @IntegrationComponentScan annotation also permits classpath scanning. This annotation
plays a similar role as the standard Spring Framework @ComponentScan annotation, but it is restricted
to components and annotations that are specific to Spring Integration, which the standard Spring
Framework component scan mechanism cannot reach. For an example, see the section called
“@MessagingGateway Annotation”.
The @EnablePublisher annotation registers a PublisherAnnotationBeanPostProcessor
bean and configures the default-publisher-channel for those @Publisher annotations that
are provided without a channel attribute. If more than one @EnablePublisher annotation is found,

5.1.1.RELEASE

Spring Integration

20

Spring Integration Reference Manual

they must all have the same value for the default channel. See the section called “Annotation-driven
Configuration with the @Publisher Annotation” for more information.
The
@GlobalChannelInterceptor
annotation
has
been
introduced
to
mark
ChannelInterceptor beans for global channel interception. This annotation is an analogue of the
 XML element (see the section called “Global Channel Interceptor
Configuration”). @GlobalChannelInterceptor annotations can be placed at the class level (with a
@Component stereotype annotation) or on @Bean methods within @Configuration classes. In either
case, the bean must implement ChannelInterceptor.
Starting with version 5.1, global channel interceptors apply to dynamically registered channels — such
as beans that are initialized by using beanFactory.initializeBean() or through the
IntegrationFlowContext when using the Java DSL. Previously, interceptors were not applied when
beans were created after the application context was refreshed.
The @IntegrationConverter annotation marks Converter, GenericConverter, or
ConverterFactory beans as candidate converters for integrationConversionService. This
annotation is an analogue of the  XML element (see the section called “Payload
Type Conversion”). You can place @IntegrationConverter annotations at the class level (with a
@Component stereotype annotation) or on @Bean methods within @Configuration classes.
See Section E.5, “Annotation Support” for more information about messaging mnnotations.

5.6 Programming Considerations
You should use plain old java objects (POJOs) whenever possible and only expose the framework in
your code when absolutely necessary. See Section 5.8, “POJO Method invocation” for more information.
If you do expose the framework to your classes, there are some considerations that need to be taken
into account, especially during application startup:
• If your component is ApplicationContextAware, you should generally not use the
ApplicationContext in the setApplicationContext() method. Instead, store a reference
and defer such uses until later in the context lifecycle.
• If your component is an InitializingBean or uses @PostConstruct methods, do not send any
messages from these initialization methods. The application context is not yet initialized when these
methods are called, and sending such messages is likely to fail. If you need to send a messages
during startup, implement ApplicationListener and wait for the ContextRefreshedEvent.
Alternatively, implement SmartLifecycle, put your bean in a late phase, and send the messages
from the start() method.

Considerations When Using Packaged (for example, Shaded) Jars
Spring Integration bootstraps certain features by using Spring Framework’s SpringFactories
mechanism to load several IntegrationConfigurationInitializer classes. This includes the core jar as well as certain others, including -http and -jmx. The information for this process is stored
in a META-INF/spring.factories file in each jar.
Some developers prefer to repackage their application and all dependencies into a single jar by using
well known tools, such as the Apache Maven Shade Plugin.
By default, the shade plugin does not merge the spring.factories files when producing the shaded
jar.

5.1.1.RELEASE

Spring Integration

21

Spring Integration Reference Manual

In addition to spring.factories, other META-INF files (spring.handlers
spring.schemas) are used for XML configuration. These files also need to be merged.

and

Important
Spring Boot’s executable jar mechanism takes a different approach, in that it nests the jars, thus
retaining each spring.factories file on the class path. So, with a Spring Boot application,
nothing more is needed if you use its default executable jar format.
Even if you do not use Spring Boot, you can still use the tooling provided by Boot to enhance the shade
plugin by adding transformers for the above mentioned files.
You may wish to consult the current spring-boot-starter-parent pom to see the current settings that boot
uses. The following example shows how to configure the plugin:
...


org.apache.maven.plugins
maven-shade-plugin

true
true


org.springframework.boot
spring-boot-maven-plugin
${spring.boot.version}




package

shade



META-INF/spring.handlers


META-INF/spring.factories


META-INF/spring.schemas








...

5.1.1.RELEASE

Spring Integration

22

Spring Integration Reference Manual

Specifically,
Add the spring-boot-maven-plugin as a dependency.

❶

❷ Configure the transformers.
Example 5.1 pom.xml
You can add a property for ${spring.boot.version} or use an explicit version.

5.7 Programming Tips and Tricks
This section documents some of the ways to get the most from Spring Integration.

XML Schemas
When using XML configuration, to avoid getting false schema validation errors, you should use a
"Spring-aware" IDE, such as the Spring Tool Suite (STS), Eclipse with the Spring IDE plugins, or
IntelliJ IDEA. These IDEs know how to resolve the correct XML schema from the classpath (by using
the META-INF/spring.schemas file in the jars). When using STS or Eclipse with the plugin, you must
enable Spring Project Nature on the project.
The schemas hosted on the internet for certain legacy modules (those that existed in version 1.0) are the
1.0 versions for compatibility reasons. If your IDE uses these schemas, you are likely to see false errors.
Each of these online schemas has a warning similar to the following:
Important
This schema is for the 1.0 version of Spring Integration Core. We cannot update it to the current
schema because that will break any applications using 1.0.3 or lower. For subsequent versions,
the unversioned schema is resolved from the classpath and obtained from the jar. Please refer
to github:
https://github.com/spring-projects/spring-integration/tree/master/spring-integration-core/src/
main/resources/org/springframework/integration/config
The affected modules are
• core (spring-integration.xsd)
• file
• http
• jms
• mail
• rmi
• security
• stream
• ws
• xml

5.1.1.RELEASE

Spring Integration

23

Spring Integration Reference Manual

Finding Class Names for Java and DSL Configuration
With XML configuration and Spring Integration Namespace support, the XML parsers hide how target
beans are declared and wired together. For Java configuration, it is important to understand the
Framework API for target end-user applications.
The first-class citizens for EIP implementation are Message, Channel, and Endpoint (see Section 5.3,
“Main Components”, earlier in this chapter). Their implementations (contracts) are:
• org.springframework.messaging.Message: See Chapter 7, Message;
• org.springframework.messaging.MessageChannel: See Section 6.1, “Message Channels”;
• org.springframework.integration.endpoint.AbstractEndpoint: See Section 6.2,
“Poller”.
The first two are simple enough to understand how to implement, configure, and use. The last one
deserves more attention
The AbstractEndpoint is widely used throughout the Spring Framework for different component
implementations. Its main implementations are:
• EventDrivenConsumer, used when we subscribe to a SubscribableChannel to listen for
messages.
• PollingConsumer, used when we poll for messages from a PollableChannel.
When you use messaging annotations or the Java DSL, you need ot worry about these
components, because the Framework automatically produces them with appropriate annotations and
BeanPostProcessor implementations. When building components manually, you should use the
ConsumerEndpointFactoryBean to help determine the target AbstractEndpoint consumer
implementation to create, based on the provided inputChannel property.
On the other hand, the ConsumerEndpointFactoryBean delegates to an another
first class citizen in the Framework: org.springframework.messaging.MessageHandler.
The goal of the implementation of this interface is to handle the message
consumed by the endpoint from the channel. All EIP components in Spring
Integration are MessageHandler implementations (for example, AggregatingMessageHandler,
MessageTransformingHandler, AbstractMessageSplitter, and others). The target protocol
outbound adapters (FileWritingMessageHandler, HttpRequestExecutingMessageHandler,
AbstractMqttMessageHandler, and others) are also MessageHandler implementations. When
you develop Spring Integration applications with Java configuration, you should look into the
Spring Integration module to find an appropriate MessageHandler implementation to use for the
@ServiceActivator\ configuration. For example, to send an XMPP message (see Chapter 39, XMPP
Support) you should configure something like the following:
@Bean
@ServiceActivator(inputChannel = "input")
public MessageHandler sendChatMessageHandler(XMPPConnection xmppConnection) {
ChatMessageSendingMessageHandler handler = new ChatMessageSendingMessageHandler(xmppConnection);
DefaultXmppHeaderMapper xmppHeaderMapper = new DefaultXmppHeaderMapper();
xmppHeaderMapper.setRequestHeaderNames("*");
handler.setHeaderMapper(xmppHeaderMapper);
return handler;
}

5.1.1.RELEASE

Spring Integration

24

Spring Integration Reference Manual

The MessageHandler implementations represent the outbound and processing part of the message
flow.
The inbound message flow side has its own components, which are divided into
polling and listening behaviors. The listening (message-driven) components are simple and
typically require only one target class implementation to be ready to produce messages.
Listening components can be one-way MessageProducerSupport implementations, (such as
AbstractMqttMessageDrivenChannelAdapter and ImapIdleChannelAdapter) or requestreply MessagingGatewaySupport implementations (such as AmqpInboundGateway and
AbstractWebServiceInboundGateway).
Polling inbound endpoints are for those protocols that do not provide a listener API or are not intended for
such a behavior, including any file based protocol (such as FTP), any data bases (RDBMS or NoSQL),
and others.
These inbound endpoints consist of two components: the poller configuration, to initiate the polling
task periodically, and a message source class to read data from the target protocol and produce
a message for the downstream integration flow. The first class for the poller configuration is
a SourcePollingChannelAdapter. It is one more AbstractEndpoint implementation, but
especially for polling to initiate an integration flow. Typically, with the messaging annotations or Java
DSL, you should not worry about this class. The Framework produces a bean for it, based on the
@InboundChannelAdapter configuration or a Java DSL builder spec.
Message source components are more important for the target application development, and
they all implement the MessageSource interface (for example, MongoDbMessageSource and
AbstractTwitterMessageSource). With that in mind, our config for reading data from an RDBMS
table with JDBC could resemble the following:

@Bean
@InboundChannelAdapter(value = "fooChannel", poller = @Poller(fixedDelay="5000"))
public MessageSource storedProc(DataSource dataSource) {
return new JdbcPollingChannelAdapter(dataSource, "SELECT * FROM foo where status = 0");
}

You can find all the required inbound and outbound classes for the target protocols in the particular
Spring Integration module (in most cases, in the respective package). For example, the springintegration-websocket adapters are:
• o.s.i.websocket.inbound.WebSocketInboundChannelAdapter:
Implements
MessageProducerSupport to listen for frames on the socket and produce message to the channel.
• o.s.i.websocket.outbound.WebSocketOutboundMessageHandler:
The
one-way
AbstractMessageHandler implementation to convert incoming messages to the appropriate
frame and send over websocket.
If you are familiar with Spring Integration XML configuration, starting with version 4.3, we provide
information in the XSD element definitions about which target classes are used to declare beans for the
adapter or gateway, as the following example shows:

5.1.1.RELEASE

Spring Integration

25

Spring Integration Reference Manual




Configures a Consumer Endpoint for the 'o.s.i.amqp.outbound.AsyncAmqpOutboundGateway'
that will publish an AMQP Message to the provided Exchange and expect a reply Message.
The sending thread returns immediately; the reply is sent asynchronously; uses
'AsyncRabbitTemplate.sendAndReceive()'.



5.8 POJO Method invocation
As discussed in Section 5.6, “Programming Considerations”, we recommend using a POJO
programming style, as the following example shows:
@ServiceActivator
public String myService(String payload) { ... }

In this case, the framework extracts a String payload, invokes your method, and wraps the result in a
message to send to the next component in the flow (the original headers are copied to the new message).
In fact, if you use XML configuration, you do not even need the @ServiceActivator annotation, as
the following paired examples show:


public String myService(String payload) { ... }

You can omit the method attribute as long as there is no ambiguity in the public methods on the class.
You can also obtain header information in your POJO methods, as the following example shows:
@ServiceActivator
public String myService(@Payload String payload, @Header("foo") String fooHeader) { ... }

You can also dereference properties on the message, as the following example shows:
@ServiceActivator
public String myService(@Payload("payload.foo") String foo, @Header("bar.baz") String barbaz) { ... }

Because various POJO method invocations are available, versions prior to 5.0 used
SpEL (Spring Expression Language) to invoke the POJO methods. SpEL (even
interpreted) is usually "fast
enough" for these operations, when compared to
the actual work usually done in the methods. However, starting with version 5.0,
the org.springframework.messaging.handler.invocation.InvocableHandlerMethod is
used by default whenever possible. This technique is usually faster to execute than interpreted SpEL
and is consistent with other Spring messaging projects. The InvocableHandlerMethod is similar
to the technique used to invoke controller methods in Spring MVC. There are certain methods that
are still always invoked when using SpEL. Examples include annotated parameters with dereferenced
properties, as discussed earlier. This is because SpEL has the capability to navigate a property path.
There may be some other corner cases that we have not considered that also do not work with
InvocableHandlerMethod instances. For this reason, we automatically fall back to using SpEL in
those cases.
If you wish, you can also set up your POJO method such that it always uses SpEL, with the
UseSpelInvoker annotation, as the following example shows:

5.1.1.RELEASE

Spring Integration

26

Spring Integration Reference Manual

@UseSpelInvoker(compilerMode = "IMMEDIATE")
public void bar(String bar) { ... }

If the compilerMode property is omitted, the spring.expression.compiler.mode system
property determines the compiler mode. See SpEL compilation for more information about compiled
SpEL.

5.1.1.RELEASE

Spring Integration

27

Part IV. Core Messaging
This section covers all aspects of the core messaging API in Spring Integration. It covers messages,
message channels, and message endpoints. It also covers many of the enterprise integration patterns,
such as filter, router, transformer, service activator , splitter, and aggregator. The section also contains
material about system management, including the control bus and message history support.

Spring Integration Reference Manual

6. Messaging Channels
6.1 Message Channels
While the Message plays the crucial role of encapsulating data, it is the MessageChannel that
decouples 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 is true if the message is sent successfully. If the send call
times out or is interrupted, it returns false.
PollableChannel
Since message channels may or may not buffer messages (as discussed in the Chapter 5,
Spring Integration Overview), two sub-interfaces define the buffering (pollable) and non-buffering
(subscribable) channel behavior. The following listing shows the definition of the PollableChannel
interface:
public interface PollableChannel extends MessageChannel {
Message receive();
Message receive(long timeout);
}

As with the send methods, when receiving a message, the return value is null in the case of a timeout
or interrupt.
SubscribableChannel
The SubscribableChannel base interface is implemented by channels that send messages directly
to their subscribed MessageHandler instances. Therefore, they do not provide receive methods for
polling. Instead, they define methods for managing those subscribers. The following listing shows the
definition of the SubscribableChannel interface:
public interface SubscribableChannel extends MessageChannel {
boolean subscribe(MessageHandler handler);
boolean unsubscribe(MessageHandler handler);
}

Message Channel Implementations
Spring Integration provides several different message channel implementations. The following sections
briefly describe each one.

5.1.1.RELEASE

Spring Integration

29

Spring Integration Reference Manual

PublishSubscribeChannel
The PublishSubscribeChannel implementation broadcasts any Message sent to it to all of its
subscribed handlers. This is most often used for sending event messages, whose primary role
is notification (as opposed to document messages, which are generally intended to be processed
by 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 no
receive() method). Instead, any subscriber must itself be a MessageHandler, and the subscriber’s
handleMessage(Message) method is invoked in turn.
Prior to version 3.0, invoking the send method on a PublishSubscribeChannel that had
no subscribers returned false. When used in conjunction with a MessagingTemplate, a
MessageDeliveryException was thrown. Starting with version 3.0, the behavior has changed such
that a send is always considered successful if at least the minimum subscribers are present (and
successfully handle the message). This behavior can be modified by setting the minSubscribers
property, which defaults to 0.
Note
If you use a TaskExecutor, only the presence of the correct number of subscribers is used for
this determination, because the actual handling of the message is performed asynchronously.
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 multiple
consumers, only one of them should receive any Message sent to that channel. It provides a default noargument constructor (providing an essentially unbounded capacity of Integer.MAX_VALUE) as well
as a constructor that accepts the queue capacity, as the following listing shows:

public QueueChannel(int capacity)

A channel that has not reached its capacity limit storeS messages in its internal queue, and the send()
method returns immediately, even if no receiver is ready to handle the message. If the queue has
reached capacity, the sender blocks until room is available. Alternatively, if you use the send call
that accepts a timeout, the queue blocks until either room is available or the timeout period elapses,
whichever occurs first. Similarly, a receive call returns immediately if a message is available on the
queue, but, if the queue is empty, then a receive call may block until either a message is available or
the timeout elapses. In either case, it is possible to force an immediate return regardless of the queue’s
state by passing a timeout value of 0. Note, however, that calls to the no-arg versions of send() and
receive() block indefinitely.
PriorityChannel
Whereas the QueueChannel enforces first-in-first-out (FIFO) ordering, the PriorityChannel is an
alternative implementation that allows for messages to be ordered within the channel based upon a
priority. By default, the priority is determined by the priority header within each message. However,
for custom priority determination logic, a comparator of type Comparator> can be
provided to the PriorityChannel constructor.

5.1.1.RELEASE

Spring Integration

30

Spring Integration Reference Manual

RendezvousChannel
The RendezvousChannel enables a "direct-handoff" scenario, wherein a sender blocks until
another party invokes the channel’s receive() method. The other party blocks until the sender sends
the message. Internally, this implementation is quite similar to the QueueChannel, except that it
uses a SynchronousQueue (a zero-capacity implementation of BlockingQueue). This works well in
situations where the sender and receiver operate in different threads, but asynchronously dropping the
message in a queue is not appropriate. In other words, with a RendezvousChannel, the sender knows
that some receiver has accepted the message, whereas with a QueueChannel, the message would
have been stored to the internal queue and potentially never received.
Tip
Keep in mind that all of these queue-based channels are storing messages in-memory only by
default. When persistence is required, you can either provide a message-store attribute within the
queue element to reference a persistent MessageStore implementation or you can replace the
local channel with one that is backed by a persistent broker, such as a JMS-backed channel or
channel adapter. The latter option lets you take advantage of any JMS provider’s implementation
for message persistence, as discussed in Chapter 23, JMS Support. However, when buffering in
a queue is not necessary, the simplest approach is to rely upon the DirectChannel, discussed
in the next section.
The RendezvousChannel is also useful for implementing request-reply operations. The sender
can 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
immediately call 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-reply components.
DirectChannel
The DirectChannel has point-to-point semantics but otherwise is more similar to the
PublishSubscribeChannel than any of the queue-based channel implementations described
earlier. It implements the SubscribableChannel interface instead of the PollableChannel
interface, so it dispatches messages directly to a subscriber. As a point-to-point channel, however, it
differs from the PublishSubscribeChannel in that it sends each Message to a single subscribed
MessageHandler.
In addition to being the simplest point-to-point channel option, one of its most important features is that
it enables a single thread to perform the operations on "both sides" of the channel. For example, if a
handler subscribes to a DirectChannel, then sending a Message to that channel triggers invocation 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 transactions
that must span across the channel while still benefiting from the abstraction and loose coupling that
the channel provides. If the send call is invoked within the scope of a transaction, the outcome of the
handler’s invocation (for example, updating a database record) plays a role in determining the ultimate
result of that transaction (commit or rollback).

5.1.1.RELEASE

Spring Integration

31

Spring Integration Reference Manual

Note
Since the DirectChannel is the simplest option and does not add any additional overhead that
would be required for scheduling and managing the threads of a poller, it is the default channel type
within Spring Integration. The general idea is to define the channels for an application, consider
which of those need to provide buffering or to throttle input, and modify those to be queue-based
PollableChannels. Likewise, if a channel needs to broadcast messages, it should not be a
DirectChannel but rather a PublishSubscribeChannel. Later, we show how each of these
channels can be configured.
The DirectChannel internally delegates to a message dispatcher to invoke its subscribed message
handlers, and that dispatcher can have a load-balancing strategy exposed by load-balancer or
load-balancer-ref attributes (mutually exclusive). The load balancing strategy is used by the
message dispatcher to help determine how messages are distributed amongst message handlers
when multiple message handlers subscribe to the same channel. As a convenience, the loadbalancer attribute exposes an enumeration of values pointing to pre-existing implementations of
LoadBalancingStrategy. round-robin (load-balances across the handlers in rotation) and none
(for the cases where one wants to explicitly disable load balancing) are the only available values.
Other strategy implementations may be added in future versions. However, since version 3.0, you can
provide your own implementation of the LoadBalancingStrategy and inject it by using the loadbalancer-ref attribute, which should point to a bean that implements LoadBalancingStrategy,
as the following example shows:






Note that the load-balancer and load-balancer-ref attributes are mutually exclusive.
The load-balancing also works in conjunction with a boolean failover property. If the "failover"
value is true (the default), the dispatcher falls back to any subsequent handlers (as necessary) when
preceding handlers throw exceptions. The order is determined by an optional order value defined on
the handlers themselves or, if no such value exists, the order in which the handlers subscribed.
If a certain situation requires that the dispatcher always try to invoke the first handler and then fall back
in the same 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-balancing is enabled. Without load-balancing, however, the invocation of handlers always begins
with the first, according to their order. For example, this approach works well when there is a clear
definition of primary, secondary, tertiary, and so on. When using the namespace support, the order
attribute on any endpoint determines the order.
Note
Keep in mind that load-balancing and failover apply only when a channel has more than one
subscribed message handler. When using the namespace support, this means that more than
one endpoint shares the same channel reference defined in the input-channel attribute.

5.1.1.RELEASE

Spring Integration

32

Spring Integration Reference Manual

ExecutorChannel
The ExecutorChannel is a point-to-point channel that supports the same dispatcher configuration as
DirectChannel (load-balancing strategy and the failover boolean property). The key difference
between these two dispatching channel types is that the ExecutorChannel delegates to an instance
of TaskExecutor to perform the dispatch. This means that the send method typically does not block,
but it also means that the handler invocation may not occur in the sender’s thread. It therefore does not
support transactions that span the sender and receiving handler.
Caution
The sender can sometimes block. For example, when using a TaskExecutor with a rejection
policy that throttles the client (such as the ThreadPoolExecutor.CallerRunsPolicy), the
sender’s thread can execute the method any time the thread pool is at its maximum capacity and
the executor’s work queue is full. Since that situation would only occur in a non-predictable way,
you should not rely upon it for transactions.
Scoped Channel
Spring Integration 1.0 provided a ThreadLocalChannel implementation, but that has been removed
as of 2.0. Now the more general way to handle the same requirement is to add a scope attribute to a
channel. The value of the attribute can be the name of a scope that is available within the context. For
example, in a web environment, certain scopes are available, and any custom scope implementations
can be registered with the context. The following example shows a thread-local scope being applied to
a channel, including the registration of the scope itself:











The channel defined in the previous example also delegates to a queue internally, but the channel is
bound to the current thread, so the contents of the queue are similarly bound. That way, the thread
that sends to the channel can later receive those same messages, but no other thread would be able
to access them. While thread-scoped channels are rarely needed, they can be useful in situations
where DirectChannel instances are being used to 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 the terminal channel.
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 capture meaningful information about the messages passing through the system in a noninvasive way. Since the Message instances are sent to and received from MessageChannel
instances, those channels provide an opportunity for intercepting the send and receive operations. The
ChannelInterceptor strategy interface, shown in the following listing, provides methods for each
of those operations:

5.1.1.RELEASE

Spring Integration

33

Spring Integration Reference Manual

public interface ChannelInterceptor {
Message preSend(Message message, MessageChannel channel);
void postSend(Message message, MessageChannel channel, boolean sent);
void afterSendCompletion(Message message, MessageChannel channel, boolean sent, Exception ex);
boolean preReceive(MessageChannel channel);
Message postReceive(Message message, MessageChannel channel);
void afterReceiveCompletion(Message message, MessageChannel channel, Exception ex);
}

After implementing the interface, registering the interceptor with a channel is just a matter of making
the following call:

channel.addInterceptor(someChannelInterceptor);

The methods that return a Message instance can be used for transforming the Message or can return
null to prevent further processing (of course, any of the methods can throw a RuntimeException).
Also, the preReceive method can return false to prevent the receive operation from proceeding.
Note
Keep in mind that receive() calls are only relevant for PollableChannels. In fact, the
SubscribableChannel interface does not even define a receive() method. The reason for
this is that when a Message is sent to a SubscribableChannel, it is sent directly to zero or more
subscribers, depending on the type of channel (for example, a PublishSubscribeChannel
sends to all of its subscribers). Therefore, the preReceive(...), postReceive(...), and
afterReceiveCompletion(...) interceptor methods are invoked only when the interceptor
is applied to a PollableChannel.
Spring Integration also provides an implementation of the Wire Tap pattern. It is a simple interceptor
that sends the Message to another channel without otherwise altering the existing flow. It can be very
useful for debugging and monitoring. An example is shown in the section called “Wire Tap”.
Because it is rarely necessary to implement all of the interceptor methods, the interface provides no-op
methods (methods returning void method have no code, the Message-returning methods return the
Message as-is, and the boolean method returns true).
Tip
The order of invocation for the interceptor methods depends on the type of channel. As described
earlier, the queue-based channels are the only ones where the receive method is intercepted
in the first place. Additionally, the relationship between send and receive interception depends
on the timing of the separate sender and receiver threads. For example, if a receiver is already
blocked while waiting for a message, the order could be as follows: preSend, preReceive,
postReceive, postSend. However, if a receiver polls after the sender has placed a message on
the channel and has already returned, the order would be as follows: preSend, postSend (sometime-elapses), preReceive, postReceive. The time that elapses in such a case depends on a
number of factors and is therefore generally unpredictable (in fact, the receive may never happen).
The type of queue also plays a role (for example, rendezvous versus priority). In short, you cannot

5.1.1.RELEASE

Spring Integration

34

Spring Integration Reference Manual

rely on the order beyond the fact that preSend precedes postSend and preReceive precedes
postReceive.
Starting with Spring Framework 4.1 and Spring Integration 4.1, the ChannelInterceptor provides
new methods: afterSendCompletion() and afterReceiveCompletion(). They are invoked
after send()' and 'receive() calls, regardless of any exception that is raised, which allow for
resource cleanup. Note that the channel invokes these methods on the ChannelInterceptor list in
the reverse order of the initial preSend() and preReceive() calls.
Starting with version 5.1, global channel interceptors now apply to dynamically registered channels
- such as through beans that are initialized by using beanFactory.initializeBean() or
IntegrationFlowContext when using the Java DSL. Previously, interceptors were not applied when
beans were created after the application context was refreshed.
Also, starting with version 5.1, ChannelInterceptor.postReceive() is no longer called when
no message is received; it is no longer necessary to check for a null Message. Previously,
the method was called. If you have an interceptor that relies on the previous behavior, implement
afterReceiveCompleted() instead, since that method is invoked, regardless of whether a message
is received or not.

MessagingTemplate
When the endpoints and their various configuration options are introduced, Spring Integration provides
a foundation for messaging components that enables non-invasive invocation of your application code
from the messaging system. However, it is sometimes necessary to invoke the messaging system from
your application code. For convenience when implementing such use cases, Spring Integration provides
a MessagingTemplate that supports a variety of operations across the message channels, including
request and reply scenarios. For example, it is possible to send a request and wait for a reply, as follows:
MessagingTemplate template = new MessagingTemplate();
Message reply = template.sendAndReceive(someChannel, new GenericMessage("test"));

In the preceding example, a temporary anonymous channel would be created internally by the template.
The sendTimeout and receiveTimeout properties may also be set on the template, and other exchange
types are also supported. The following listing shows the signatures for such methods:
public boolean send(final MessageChannel channel, final Message message) { ...
}
public Message sendAndReceive(final MessageChannel channel, final Message request) { ...
}
public Message receive(final PollableChannel channel) { ...
}

Note
A less invasive approach that lets you invoke simple interfaces with payload or header
values instead of Message instances is described in the section called “Enter the
GatewayProxyFactoryBean”.

Configuring Message Channels
To create a message channel instance, you can use the  element, as follows:

5.1.1.RELEASE

Spring Integration

35

Spring Integration Reference Manual



The default channel type is point-to-point. To create a publish-subscribe channel, use the  element, as follows:


When you use the  element without any sub-elements, it creates a DirectChannel
instance (a SubscribableChannel).
However, you can alternatively provide a variety of  sub-elements to create any of the pollable
channel types (as described in the section called “Message Channel Implementations”). The following
sections shows examples of each channel type.
DirectChannel Configuration
As mentioned earlier, DirectChannel is the default type. The following listing shows who to define
one in XML:


A default channel has a round-robin load-balancer and also has failover enabled (see the section called
“DirectChannel” for more detail). To disable one or both of these, add a  subelement and configure the attributes as follows:







Datatype Channel Configuration
Sometimes, a consumer can process only a particular type of payload, forcing you to ensure the payload
type of the input messages. The first thing that comes to mind may be to use a message filter. However,
all that message filter can do is filter out messages that are not compliant with the requirements of the
consumer. Another way would be to use a content-based router and route messages with non-compliant
data-types to specific transformers to enforce transformation and conversion to the required data type.
This would work, but a simpler way to accomplish the same thing is to apply the Datatype Channel
pattern. You can use separate datatype channels for each specific payload data type.
To create a datatype channel that accepts only messages that contain a certain payload type, provide
the data type’s fully-qualified class name in the channel element’s datatype attribute, as the following
example shows:


Note that the type check passes for any type that is assignable to the channel’s datatype. In other
words, the numberChannel in the preceding example would accept messages whose payload is
java.lang.Integer or java.lang.Double. Multiple types can be provided as a comma-delimited
list, as the following example shows:


5.1.1.RELEASE

Spring Integration

36

Spring Integration Reference Manual

So the numberChannel in the preceding example accepts only messages with a data type of
java.lang.Number. But what happens if the payload of the message is not of the required type?
It depends on whether you have defined a bean named integrationConversionService that is
an instance of Spring’s Conversion Service. If not, then an Exception would be thrown immediately.
However, if you have defined an integrationConversionService bean, it is used in an attempt to
convert the message’s payload to the acceptable type.
You can even register custom converters. For example, suppose you send a message with a String
payload to the numberChannel we configured above. You might handle the message as follows:
MessageChannel inChannel = context.getBean("numberChannel", MessageChannel.class);
inChannel.send(new GenericMessage("5"));

Typically this would be a perfectly legal operation. However, since we use Datatype Channel, the result
of such operation would generate an exception similar to the following:
Exception in thread "main" org.springframework.integration.MessageDeliveryException:
Channel 'numberChannel'
expected one of the following datataypes [class java.lang.Number],
but received [class java.lang.String]
…

The exception happens because we require the payload type to be a Number, but we sent a String.
So we need something to convert a String to a Number. For that, we can implement a converter
similar to the following example:
public static class StringToIntegerConverter implements Converter {
public Integer convert(String source) {
return Integer.parseInt(source);
}
}

Then we can register it as a converter with the Integration Conversion Service, as the following example
shows:



When the converter element is parsed, it creates the integrationConversionService bean if
one is not already defined. With that converter in place, the send operation would now be successful,
because the datatype channel uses that converter to convert the String payload to an Integer.
For more information regarding payload type conversion, see the section called “Payload Type
Conversion”.
Beginning with version 4.0, the integrationConversionService is invoked by the
DefaultDatatypeChannelMessageConverter, which looks up the conversion service in the
application context. To use a different conversion technique, you can specify the message-converter
attribute on the channel. This must be a reference to a MessageConverter implementation. Only the
fromMessage method is used. It provides the converter with access to the message headers (in case
the conversion might need information from the headers, such as content-type). The method can
return only the converted payload or a full Message object. If the latter, the converter must be careful
to copy all the headers from the inbound message.
Alternatively, you can declare a  of type MessageConverter with an ID of
datatypeChannelMessageConverter, and that converter is used by all channels with a datatype.

5.1.1.RELEASE

Spring Integration

37

Spring Integration Reference Manual

QueueChannel Configuration
To create a QueueChannel, use the  sub-element. You may specify the channel’s capacity
as follows:




Note
If you do not provide a value for the capacity attribute on this  sub-element, the resulting
queue is unbounded. To avoid issues such as running out of memory, we highly recommend that
you set an explicit value for a bounded queue.
Persistent QueueChannel Configuration

Since a QueueChannel provides the capability to buffer messages but does so in-memory only
by default, it also introduces a possibility that messages could be lost in the event of a system
failure. To mitigate this risk, a QueueChannel may be backed by a persistent implementation
of the MessageGroupStore strategy interface. For more details on MessageGroupStore and
MessageStore, see Section 12.4, “Message Store”.
Important
The capacity attribute is not allowed when the message-store attribute is used.
When a QueueChannel receives a Message, it adds the message to the message store. When a
Message is polled from a QueueChannel, it is removed from the message store.
By default, a QueueChannel stores its messages in an in-memory queue, which can lead to the lost
message scenario mentioned earlier. However, Spring Integration provides persistent stores, such as
the JdbcChannelMessageStore.
You can configure a message store for any QueueChannel by adding the message-store attribute,
as the following example shows:








The Spring Integration JDBC module also provides a schema Data Definition Language
(DDL) for a number of popular databases. These schemas are located in the
org.springframework.integration.jdbc.store.channel package of that module (spring-integrationjdbc).
Important
One important feature is that, with any transactional persistent store (such as
JdbcChannelMessageStore), as long as the poller has a transaction configured, a message

5.1.1.RELEASE

Spring Integration

38

Spring Integration Reference Manual

removed from the store can be permanently removed only if the transaction completes
successfully. Otherwise the transaction rolls back, and the Message is not lost.
Many other implementations of the message store are available as the growing number of Spring
projects related to "NoSQL" data stores come to provide underlying support for these stores. You can
also provide your own implementation of the MessageGroupStore interface if you cannot find one
that meets your particular needs.
Since version 4.0, we recommend that QueueChannel instances be configured to use a
ChannelMessageStore, if possible. These are generally optimized for this use, as compared to a
general message store. If the ChannelMessageStore is a ChannelPriorityMessageStore, the
messages are received in FIFO within priority order. The notion of priority is determined by the message
store implementation. For example, the following example shows the Java configuration for the the
section called “MongoDB Channel Message Store”:
@Bean
public BasicMessageGroupStore mongoDbChannelMessageStore(MongoDbFactory mongoDbFactory) {
MongoDbChannelMessageStore store = new MongoDbChannelMessageStore(mongoDbFactory);
store.setPriorityEnabled(true);
return store;
}
@Bean
public PollableChannel priorityQueue(BasicMessageGroupStore mongoDbChannelMessageStore) {
return new PriorityChannel(new MessageGroupQueue(mongoDbChannelMessageStore, "priorityQueue"));
}

Note
Pay attention to the MessageGroupQueue class. That is a BlockingQueue implementation to
use the MessageGroupStore operations.
The same implementation with Java DSL might look like the following example:
@Bean
public IntegrationFlow priorityFlow(PriorityCapableChannelMessageStore mongoDbChannelMessageStore) {
return IntegrationFlows.from((Channels c) ->
c.priority("priorityChannel", mongoDbChannelMessageStore, "priorityGroup"))
....
.get();
}

Another option to customize the QueueChannel environment is provided by the ref attribute of the
 sub-element or its particular constructor. This attribute supplies the reference to any
java.util.Queue implementation. For example, a Hazelcast distributed IQueue can be configured
as follows:
@Bean
public HazelcastInstance hazelcastInstance() {
return Hazelcast.newHazelcastInstance(new Config()
.setProperty("hazelcast.logging.type", "log4j"));
}
@Bean
public PollableChannel distributedQueue() {
return new QueueChannel(hazelcastInstance()
.getQueue("springIntegrationQueue"));
}

5.1.1.RELEASE

Spring Integration

39

Spring Integration Reference Manual

PublishSubscribeChannel Configuration
To create a PublishSubscribeChannel, use the  element. When
using this element, you can also specify the task-executor used for publishing messages (if none
is specified, it publishes in the sender’s thread), as follows:


If you provide a resequencer or aggregator downstream from a PublishSubscribeChannel, you can
set the apply-sequence property on the channel to true. Doing so indicates that the channel should
set the sequence-size and sequence-number message headers as well as the correlation ID prior
to passing along the messages. For example, if there are five subscribers, the sequence-size would
be set to 5, and the messages would have sequence-number header values ranging from 1 to 5.
Along with the Executor, you can also configure an ErrorHandler. By default, the
PublishSubscribeChannel uses a MessagePublishingErrorHandler implementation to send
an error to the MessageChannel from the errorChannel header or into the global errorChannel
instance. If an Executor is not configured, the ErrorHandler is ignored and exceptions are thrown
directly to the caller’s thread.
If you provide a Resequencer or Aggregator downstream from a PublishSubscribeChannel,
you can set the apply-sequence property on the channel to true. Doing so indicates that the channel
should set the sequence-size and sequence-number message headers as well as the correlation ID
prior to passing along the messages. For example, if there are five subscribers, the sequence-size would
be set to 5, and the messages would have sequence-number header values ranging from 1 to 5.
The following example shows how to set the apply-sequence header to true:


Note
The apply-sequence value is false by default so that a publish-subscribe channel can send
the exact same message instances to multiple outbound channels. Since Spring Integration
enforces immutability of the payload and header references, when the flag is set to true, the
channel creates new Message instances with the same payload reference but different header
values.
ExecutorChannel
To create an ExecutorChannel, add the  sub-element with a task-executor
attribute. The attribute’s value can reference any TaskExecutor within the context. For example,
doing so enables configuration of a thread pool for dispatching messages to subscribed handlers. As
mentioned earlier, doing so breaks the single-threaded execution context between sender and receiver
so that any active transaction context is not shared by the invocation of the handler (that is, the handler
may throw an Exception, but the send invocation has already returned successfully). The following
example shows how to use the dispatcher element and specify an executor in the task-executor
attribute:




5.1.1.RELEASE

Spring Integration

40

Spring Integration Reference Manual

Note
The load-balancer and failover options are also both available on the  subelement, as described earlier in the section called “DirectChannel Configuration”. The same
defaults apply. Consequently, the channel has a round-robin load-balancing strategy with failover
enabled unless explicit configuration is provided for one or both of those attributes, as the following
example shows:




PriorityChannel Configuration
To create a PriorityChannel, use the  sub-element, as the following example
shows:




By default, the channel consults the priority header of the message. However, you can instead
provide a custom Comparator reference. Also, note that the PriorityChannel (like the other types)
does support the datatype attribute. As with the QueueChannel, it also supports a capacity
attribute. The following example demonstrates all of these:




Since version 4.0, the priority-channel child element supports the message-store
option (comparator and capacity are not allowed in that case). The message
store must be a PriorityCapableChannelMessageStore. Implementations of the
PriorityCapableChannelMessageStore are currently provided for Redis, JDBC, and MongoDB.
See the section called “QueueChannel Configuration” and Section 12.4, “Message Store” for more
information. You can find sample configuration in the section called “Backing Message Channels”.
RendezvousChannel Configuration
A RendezvousChannel is created when the queue sub-element is a . It does
not provide any additional configuration options to those described earlier, and its queue does not accept
any capacity value, since it is a zero-capacity direct handoff queue. The following example shows how
to declare a RendezvousChannel:




Scoped Channel Configuration
Any channel can be configured with a scope attribute, as the following example shows:


5.1.1.RELEASE

Spring Integration

41

Spring Integration Reference Manual

Channel Interceptor Configuration
Message channels may also have interceptors, as described in the section called “Channel
Interceptors”. The  sub-element can be added to a  (or the more
specific element types). You can provide the ref attribute to reference any Spring-managed object that
implements the ChannelInterceptor interface, as the following example shows:






In general, we recommend defining the interceptor implementations in a separate location, since they
usually provide common behavior that can be reused across multiple channels.
Global Channel Interceptor Configuration
Channel interceptors provide a clean and concise way of applying cross-cutting behavior per individual
channel. If the same behavior should be applied on multiple channels, configuring the same set of
interceptors for each channel would not be the most efficient way. To avoid repeated configuration while
also enabling interceptors to apply to multiple channels, Spring Integration provides global interceptors.
Consider the following pair of examples:







Each  element lets you define a global interceptor, which is applied on all
channels that match any patterns defined by the pattern attribute. In the preceding case, the global
interceptor is applied on the thing1 channel and all other channels that begin with thing2 or input but
not to channels starting with thing3 (since version 5.0).
Warning
The addition of this syntax to the pattern causes one possible (though perhaps unlikely) problem.
If you have a bean named !thing1 and you included a pattern of !thing1 in your channel
interceptor’s pattern patterns, it no longer matches. The pattern now matches all beans not
named thing1. In this case, you can escape the ! in the pattern with \. The pattern \!thing1
matches a bean named !thing1.
The order attribute lets you manage where this interceptor is injected when there are multiple
interceptors on a given channel. For example, channel inputChannel could have individual interceptors
configured locally (see below), as the following example shows:






A reasonable question is "how is a global interceptor injected in relation to
other interceptors configured locally or through other global interceptor

5.1.1.RELEASE

Spring Integration

42

Spring Integration Reference Manual

definitions?" The current implementation provides a simple mechanism for defining the order of
interceptor execution. A positive number in the order attribute ensures interceptor injection after any
existing interceptors, while a negative number ensures that the interceptor is injected before existing
interceptors. This means that, in the preceding example, the global interceptor is injected after (since
its order is greater than 0) the wire-tap interceptor configured locally. If there were another global
interceptor with a matching pattern, its order would be determined by comparing the values of both
interceptors' order attributes. To inject a global interceptor before the existing interceptors, use a
negative value for the order attribute.
Note
Note that both the order and pattern attributes are optional. The default value for order will
be 0 and for pattern, the default is * (to match all channels).
Starting
with
version
4.3.15,
you
can
configure
the
spring.integration.postProcessDynamicBeans = true property to apply any global
interceptors to dynamically created MessageChannel beans. See Section E.4, “Global Properties” for
more information.
Wire Tap
As mentioned earlier, Spring Integration provides a simple wire tap interceptor. You can configure a wire
tap on any channel within an  element. Doing so is especially useful for debugging
and can be used in conjunction with Spring Integration’s logging channel adapter as follows:







Tip
The logging-channel-adapter also accepts an expression attribute so that you can evaluate a
SpEL expression against the payload and headers variables. Alternatively, to log the full message
toString() result, provide a value of true for the log-full-message attribute. By default, it
is false so that only the payload is logged. Setting it to true enables logging of all headers
in addition to the payload. The expression option provides the most flexibility (for example,
expression="payload.user.name").
One of the common misconceptions about the wire tap and other similar components (Section B.1,
“Message Publishing Configuration”) is that they are automatically asynchronous in nature. By default,
wire tap as a component is not invoked asynchronously. Instead, Spring Integration focuses on a single
unified approach to configuring asynchronous behavior: the message channel. What makes certain
parts of the message flow synchronous or asynchronous is the type of Message Channel that has been
configured within that flow. That is one of the primary benefits of the message channel abstraction. From
the inception of the framework, we have always emphasized the need and the value of the message
channel as a first-class citizen of the framework. It is not just an internal, implicit realization of the EIP
pattern. It is fully exposed as a configurable component to the end user. So, the wire tap component is
only responsible for performing the following tasks:

5.1.1.RELEASE

Spring Integration

43

Spring Integration Reference Manual

• Intercept a message flow by tapping into a channel (for example, channelA)
• Grab each message
• Send the message to another channel (for example, channelB)
It is essentially a variation of the bridge pattern, but it is encapsulated within a channel definition (and
hence easier to enable and disable without disrupting a flow). Also, unlike the bridge, it basically forks
another message flow. Is that flow synchronous or asynchronous? The answer depends on the type of
message channel that channelB is. We have the following options: direct channel, pollable channel, and
executor channel. The last two break the thread boundary, making communication over such channels
asynchronous, because the dispatching of the message from that channel to its subscribed handlers
happens on a different thread than the one used to send the message to that channel. That is what is
going to make your wire-tap flow synchronous or asynchronous. It is consistent with other components
within the framework (such as message publisher) and adds a level of consistency and simplicity by
sparing you from worrying in advance (other than writing thread-safe code) about whether a particular
piece of code should be implemented as synchronous or asynchronous. The actual wiring of two pieces
of code (say, component A and component B) over a message channel is what makes their collaboration
synchronous or asynchronous. You may even want to change from synchronous to asynchronous in
the future, and message channel lets you to do it swiftly without ever touching the code.
One final point regarding the wire tap is that, despite the rationale provided above for not being
asynchronous by default, you should keep in mind that it is usually desirable to hand off the message
as soon as possible. Therefore, it would be quite common to use an asynchronous channel option as
the wire tap’s outbound channel. However we doe not enforce asynchronous behavior by default. There
are a number of use cases that would break if we did, including that you might not want to break a
transactional boundary. Perhaps you use the wire tap pattern for auditing purposes, and you do want
the audit messages to be sent within the original transaction. As an example, you might connect the
wire tap to a JMS outbound channel adapter. That way, you get the best of both worlds: 1) the sending
of a JMS Message can occur within the transaction while 2) it is still a "fire-and-forget" action,
thereby preventing any noticeable delay in the main message flow.
Important
Starting with version 4.0, it is important to avoid circular references when an interceptor
(such as the WireTap class) references a channel. You need to exclude such channels
from those being intercepted by the current interceptor. This can be done with appropriate
patterns or programmatically. If you have a custom ChannelInterceptor that references a
channel, consider implementing VetoCapableInterceptor. That way, the framework asks
the interceptor if it is OK to intercept each channel that is a candidate, based on the supplied
pattern. You can also add runtime protection in the interceptor methods to ensure that the channel
is not one that is referenced by the interceptor. The WireTap uses both of these techniques.
Starting with version 4.3, the WireTap has additional constructors that take a channelName instead
of a MessageChannel instance. This can be convenient for Java configuration and when channel
auto-creation logic is being used. The target MessageChannel bean is resolved from the provided
channelName later, on the first interaction with the interceptor.
Important
Channel resolution requires a BeanFactory, so the wire tap instance must be a Spring-managed
bean.

5.1.1.RELEASE

Spring Integration

44

Spring Integration Reference Manual

This late-binding approach also allows simplification of typical wire-tapping patterns with Java DSL
configuration, as the following example shows:
@Bean
public PollableChannel myChannel() {
return MessageChannels.queue()
.wireTap("loggingFlow.input")
.get();
}
@Bean
public IntegrationFlow loggingFlow() {
return f -> f.log();
}

Conditional Wire Taps
Wire taps can be made conditional by using the selector or selector-expression attributes.
The selector references a MessageSelector bean, which can determine at runtime whether the
message should go to the tap channel. Similarly, the selector-expression is a boolean SpEL
expression that performs the same purpose: If the expression evaluates to true, the message is sent
to the tap channel.
Global Wire Tap Configuration
It is possible to configure a global wire tap as a special case of the the section called “Global Channel
Interceptor Configuration”. To do so, configure a top level wire-tap element. Now, in addition to the
normal wire-tap namespace support, the pattern and order attributes are supported and work in
exactly the same way as they do for the channel-interceptor. The following examlpe shows how
to configure a global wire tap:


Tip
A global wire tap provides a convenient way to configure a single-channel wire tap externally
without modifying the existing channel configuration. To do so, set the pattern attribute to the
target channel name. For example, you can use this technique to configure a test case to verify
messages on a channel.

Special Channels
If namespace support is enabled, two special channels are defined within the application context
by default: errorChannel and nullChannel. The nullChannel acts like /dev/null, logging any
message sent to it at the DEBUG level and returning immediately. Any time you face channel resolution
errors for a reply that you do not care about, you can set the affected component’s output-channel
attribute to nullChannel (the name, nullChannel, is reserved within the application context). The
errorChannel is used internally for sending error messages and may be overridden with a custom
configuration. This is discussed in greater detail in Section E.3, “Error Handling”.
See also Section 11.2, “Message Channels” in the Java DSL chapter for more information about
message channel and interceptors.

6.2 Poller
This section describes how polling works in Spring Integration.

5.1.1.RELEASE

Spring Integration

45

Spring Integration Reference Manual

Polling Consumer
When Message Endpoints (Channel Adapters) are connected to channels and instantiated, they
produce one of the following instances:
• PollingConsumer
• EventDrivenConsumer
The actual implementation depends on the type of channel to which these
endpoints connect. A channel adapter connected to a channel that implements the
org.springframework.messaging.SubscribableChannel interface produces an instance of
EventDrivenConsumer. On the other hand, a channel adapter connected to a channel that
implements the org.springframework.messaging.PollableChannel interface (such as a
QueueChannel) produces an instance of PollingConsumer.
Polling consumers let Spring Integration components actively poll for Messages rather than process
messages in an event-driven manner.
They represent a critical cross-cutting concern in many messaging scenarios. In Spring Integration,
polling consumers are based on the pattern with the same name, which is described in the book
Enterprise Integration Patterns, by Gregor Hohpe and Bobby Woolf. You can find a description of the
pattern on the book’s website.

Pollable Message Source
Spring Integration offers a second variation of the polling consumer pattern. When inbound channel
adapters are used, these adapters are often wrapped by a SourcePollingChannelAdapter. For
example, when retrieving messages from a remote FTP Server location, the adapter described in
Section 18.4, “FTP Inbound Channel Adapter” is configured with a poller to periodically retrieve
messages. So, when components are configured with pollers, the resulting instances are of one of the
following types:
• PollingConsumer
• SourcePollingChannelAdapter
This means that pollers are used in both inbound and outbound messaging scenarios. Here are some
use cases in which pollers are used:
• Polling certain external systems, such as FTP Servers, Databases, and Web Services
• Polling internal (pollable) message channels
• Polling internal services (such as repeatedly executing methods on a Java class)
Note
AOP advice classes can be applied to pollers, in an advice-chain, such as a transaction
advice to start a transaction. Starting with version 4.1, a PollSkipAdvice is provided. Pollers
use triggers to determine the time of the next poll. The PollSkipAdvice can be used to
suppress (skip) a poll, perhaps because there is some downstream condition that would prevent

5.1.1.RELEASE

Spring Integration

46

Spring Integration Reference Manual

the message being processed. To use this advice, you have to provide it with an implementation of
a PollSkipStrategy. Starting with version 4.2.5, a SimplePollSkipStrategy is provided.
To use it, you can add an instance as a bean to the application context, inject it into a
PollSkipAdvice, and add that to the poller’s advice chain. To skip polling, call skipPolls().
To resume polling, call reset(). Version 4.2 added more flexibility in this area. See the section
called “Conditional Pollers for Message Sources”.
This chapter is meant to only give a high-level overview of polling consumers and how they fit into
the concept of message channels (see Section 6.1, “Message Channels”) and channel adapters (see
Section 6.3, “Channel Adapter”). For more information regarding messaging endpoints in general and
polling consumers in particular, see Section 10.1, “Message Endpoints”.

Deferred Acknowledgment Pollable Message Source
Starting with version 5.0.1, certain modules provide MessageSource implementations that support
deferring acknowledgment until the downstream flow completes (or hands off the message to another
thread). This is currently limited to the AmqpMessageSource and the KafkaMessageSource provided
by the spring-kafka-integration extension project, version 3.0.1 or higher.
With
these
message
sources,
the
IntegrationMessageHeaderAccessor.ACKNOWLEDGMENT_CALLBACK header (see the section
called “MessageHeaderAccessor API”) is added to the message. The value of the header is an
instance of AcknowledgmentCallback, as the following example shows:
@FunctionalInterface
public interface AcknowledgmentCallback {
void acknlowledge(Status status);
boolean isAcknowledged();
void noAutoAck();
default boolean isAutoAck();
enum Status {
/**
* Mark the message as accepted.
*/
ACCEPT,
/**
* Mark the message as rejected.
*/
REJECT,
/**
* Reject the message and requeue so that it will be redelivered.
*/
REQUEUE
}
}

Not all message sources (for example, Kafka) support the REJECT status. It is treated the same as
ACCEPT.
Applications can acknowledge a message at any time, as the following example shows:

5.1.1.RELEASE

Spring Integration

47

Spring Integration Reference Manual

Message received = source.receive();
...
StaticMessageHeaderAccessor.getAcknowledgmentCallback(received)
.acknowledge(Status.ACCEPT);

If the MessageSource is wired into a SourcePollingChannelAdapter, when the poller
thread returns to the adapter after the downstream flow completes, the adapter checks
whether the acknowledgment has already been acknowledged and, if not, sets its status to
ACCEPT it (or REJECT if the flow throws an exception). The status values are defined in the
AcknowledgmentCallback.Status enumeration.
Spring Integration provides MessageSourcePollingTemplate to perform ad-hoc polling
of a MessageSource. This, too, takes care of setting ACCEPT or REJECT on the
AcknowledgmentCallback when the MessageHandler callback returns (or throws an exception).
The following example shows how to poll with the MessageSourcePollingTemplate:
MessageSourcePollingTemplate template =
new MessageSourcePollingTemplate(this.source);
template.poll(h -> {
...
});

In both cases (SourcePollingChannelAdapter and MessageSourcePollingTemplate), you
can disable auto ack/nack by calling noAutoAck() on the callback. You might do this if you hand off
the message to another thread and wish to acknowledge later. Not all implementations support this (for
example, Apache Kafka does not, because the offset commit has to be performed on the same thread).

Conditional Pollers for Message Sources
This section covers how to use conditional pollers.
Background
Advice objects, in an advice-chain on a poller, advise the whole polling task (both message
retrieval and processing). These "around advice" methods do not have access to any context for the
poll — only the poll itself. This is fine for requirements such as making a task transactional or skipping a
poll due to some external condition, as discussed earlier. What if we wish to take some action depending
on the result of the receive part of the poll or if we want to adjust the poller depending on conditions?
For those instances, Spring Integration offers "Smart" Polling.
"Smart" Polling
Version 4.2 introduced the AbstractMessageSourceAdvice. Any Advice objects in the advicechain that subclass this class are applied only to the receive operation. Such classes implement the
following methods:
• beforeReceive(MessageSource
source) This method is called before the
MessageSource.receive() method. It lets you examine and reconfigure the source. Returning
false cancels this poll (similar to the PollSkipAdvice mentioned earlier).
• Message afterReceive(Message result, MessageSource source) This
method is called after the receive() method. Again, you can reconfigure the source or take any
action (perhaps depending on the result, which can be null if there was no message created by the
source). You can even return a different message

5.1.1.RELEASE

Spring Integration

48

Spring Integration Reference Manual

Thread safety
If an advice mutates the MessageSource, you should not configure the poller with a
TaskExecutor. If an advice mutates the source, such mutations are not thread safe and could
cause unexpected results, especially with high frequency pollers. If you need to process poll
results concurrently, consider using a downstream ExecutorChannel instead of adding an
executor to the poller.
Advice Chain Ordering
You should understand how the advice chain is processed during initialization. Advice objects
that do not extend AbstractMessageSourceAdvice are applied to the whole poll process
and are all invoked first, in order, before any AbstractMessageSourceAdvice. Then
AbstractMessageSourceAdvice objects are invoked in order around the MessageSource
receive() method. If you have, for example, Advice objects a, b, c, d, where b and d
are AbstractMessageSourceAdvice, the objects are applied in the following order: a, c,
b, d. Also, if a MessageSource is already a Proxy, the AbstractMessageSourceAdvice
is invoked after any existing Advice objects. If you wish to change the order, you must wire up
the proxy yourself.
SimpleActiveIdleMessageSourceAdvice
This advice is a simple implementation of AbstractMessageSourceAdvice. When used in
conjunction with a DynamicPeriodicTrigger, it adjusts the polling frequency, depending on whether
or not the previous poll resulted in a message or not. The poller must also have a reference to the same
DynamicPeriodicTrigger.
Important: Async Handoff
SimpleActiveIdleMessageSourceAdvice modifies the trigger based on the receive()
result. This works only if the advice is called on the poller thread. It does not work if the poller has
a task-executor. To use this advice where you wish to use async operations after the result
of a poll, do the async handoff later, perhaps by using an ExecutorChannel.
CompoundTriggerAdvice
This advice allows the selection of one of two triggers based on whether a poll returns a message or not.
Consider a poller that uses a CronTrigger. CronTrigger instances are immutable, so they cannot
be altered once constructed. Consider a use case where we want to use a cron expression to trigger
a poll once each hour but, if no message is received, poll once per minute and, when a message is
retrieved, revert to using the cron expression.
The advice (and poller) use a CompoundTrigger for this purpose. The trigger’s primary trigger can
be a CronTrigger. When the advice detects that no message is received, it adds the secondary trigger
to the CompoundTrigger. When the CompoundTrigger instance’s nextExecutionTime method
is invoked, it delegates to the secondary trigger, if present. Otherwise, it delegates to the primary trigger.
The poller must also have a reference to the same CompoundTrigger.
The following example shows the configuration for the hourly cron expression with a fallback to every
minute:

5.1.1.RELEASE

Spring Integration

49

Spring Integration Reference Manual
















 





Important: Async Handoff
CompoundTriggerAdvice modifies the trigger based on the receive() result. This works only
if the advice is called on the poller thread. It does not work if the poller has a task-executor.
To use this advice where you wish to use async operations after the result of a poll, do the async
handoff later, perhaps by using an ExecutorChannel.

6.3 Channel Adapter
A channel adapter is a message endpoint that enables connecting a single sender or receiver to a
message channel. Spring Integration provides a number of adapters to support various transports,
such as JMS, file, HTTP, web services, mail, and more. Upcoming chapters of this reference guide
discuss each adapter. However, this chapter focuses on the simple but flexible method-invoking channel
adapter support. There are both inbound and outbound adapters, and each may be configured with XML
elements provided in the core namespace. These provide an easy way to extend Spring Integration, as
long as you have a method that can be invoked as either a source or a destination.

Configuring An Inbound Channel Adapter
An inbound-channel-adapter element can invoke any method on a Spring-managed object and
send a non-null return value to a MessageChannel after converting the method’s output to a Message.
When the adapter’s subscription is activated, a poller tries to receive messages from the source. The
poller is scheduled with the TaskScheduler according to the provided configuration. To configure the
polling interval or cron expression for an individual channel adapter, you can provide a poller element
with one of the scheduling attributes, such as fixed-rate or cron. The following example defines two
inbound-channel-adapter instances:







5.1.1.RELEASE

Spring Integration

50

Spring Integration Reference Manual

See also the section called “Channel Adapter Expressions and Scripts”.
Note
If no poller is provided, then a single default poller must be registered within the context. See the
section called “Endpoint Namespace Support” for more detail.
Important: Poller Configuration
Some
inbound-channel-adapter
types
are
backed
by
a
SourcePollingChannelAdapter, which means they contain a poller configuration that polls
the MessageSource (to invoke a custom method that produces the value that becomes a
Message payload) based on the configuration specified in the Poller. The following example
shows the configuration of two pollers:



In the the first configuration, the polling task is invoked once per poll, and, during each task (poll),
the method (which results in the production of the message) is invoked once, based on the maxmessages-per-poll attribute value. In the second configuration, the polling task is invoked 10
times per poll or until it returns null, thus possibly producing ten messages per poll while each
poll happens at one-second intervals. However, what happens if the configuration looks like the
following example:


Note that there is no max-messages-per-poll specified. As we cover later, the identical poller
configuration in the PollingConsumer (for example, service-activator, filter, router, and others)
would have a default value of -1 for max-messages-per-poll, which means "execute the
polling task non-stop unless the polling method returns null (perhaps
because there are no more messages in the `QueueChannel)`" and then sleep
for one second.
However, in the SourcePollingChannelAdapter, it is a bit different. The default value for
max-messages-per-poll is 1, unless you explicitly set it to a negative value (such as -1).
This makes sure that the poller can react to lifecycle events (such as start and stop) and prevents
it from potentially spinning in an infinite loop if the implementation of the custom method of the
MessageSource has a potential to never return null and happens to be non-interruptible.
However, if you are sure that your method can return null and you need to poll for as many sources
as available per each poll, you should explicitly set max-messages-per-poll to a negative
value, as the following example shows:


Configuring An Outbound Channel Adapter
An outbound-channel-adapter element can also connect a MessageChannel to any POJO
consumer method that should be invoked with the payload of messages sent to that channel. The
following example shows how to define an outbound channel adapter:

5.1.1.RELEASE

Spring Integration

51

Spring Integration Reference Manual




If the channel being adapted is a PollableChannel, you must provide a poller sub-element, as the
following example shows:





You should use a ref attribute if the POJO consumer implementation can be reused in other
 definitions. However, if the consumer implementation is referenced
by only a single definition of the , you can define it as an inner bean,
as the following example shows:




Note
Using both the ref attribute and an inner handler definition in the same  configuration is not allowed, as it creates an ambiguous condition. Such a configuration
results in an exception being thrown.
Any channel adapter can be created without a channel reference, in which case it implicitly creates an
instance of DirectChannel. The created channel’s name matches the id attribute of the  or  element. Therefore, if channel is not
provided, id is required.

Channel Adapter Expressions and Scripts
Like many other Spring Integration components, the  and
 also provide support for SpEL expression evaluation. To use SpEL,
provide the expression string in the expression attribute instead of providing the ref and method
attributes that are used for method-invocation on a bean. When an expression is evaluated, it follows the
same contract as method-invocation where: the expression for an 
generates a message any time the evaluation result is a non-null value, while the expression for an
 must be the equivalent of a void-returning method invocation.
Starting with Spring Integration 3.0, an  can also be configured
with a SpEL  (or even with a 



Navigation menu