Spring Integration Reference Manual

Spring%20Integration%20Reference%20Manual

User Manual:

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

DownloadSpring Integration Reference Manual
Open PDF In BrowserView PDF
Spring Integration Reference Manual
4.3.6.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

Copyright © 2009 2010 2011 2012 2013 2014 2015 2016 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
I. Preface ................................................................................................................................... 1
Requirements ..................................................................................................................... ii
1. Compatible Java Versions ....................................................................................... ii
2. Compatible Versions of the Spring Framework ......................................................... ii
3. Code Conventions .................................................................................................. ii
1. Conventions in this Book ................................................................................................ 4
II. What’s new? .......................................................................................................................... 5
2. What’s new in Spring Integration 4.3? ............................................................................. 6
2.1. New Components ................................................................................................ 6
AMQP Async Outbound Gateway ....................................................................... 6
MessageGroupFactory ........................................................................................ 6
PersistentMessageGroup .................................................................................... 6
FTP/SFTP Streaming Inbound Channel Adapters ................................................. 6
Stream Transformer ........................................................................................... 6
Integration Graph ............................................................................................... 6
JDBC Lock Registry ........................................................................................... 6
Leader Initiator for Lock Registry ........................................................................ 6
2.2. General Changes ................................................................................................ 7
Core Changes .................................................................................................... 7
Outbound Gateway within Chain ................................................................. 7
Async Service Activator .............................................................................. 7
Messaging Annotation Support changes ...................................................... 7
Mail Changes ..................................................................................................... 7
Customizable User Flag ............................................................................. 7
Mail Message Mapping ............................................................................... 7
JMS Changes .................................................................................................... 7
Header Mapper .......................................................................................... 7
Async Gateway .......................................................................................... 7
Aggregator Changes .......................................................................................... 7
TCP/UDP Changes ............................................................................................ 8
Events ....................................................................................................... 8
Stream Deserializers .................................................................................. 8
TCP Message Mapper ................................................................................ 8
File Changes ..................................................................................................... 8
Destination Directory Creation ..................................................................... 8
Buffer Size ................................................................................................. 8
Appending and Flushing ............................................................................. 8
Preserving Timestamps .............................................................................. 8
Splitter Changes ........................................................................................ 8
AMQP Changes ................................................................................................. 9
Content Type Message Converter ............................................................... 9
Headers for Delayed Message Handling ...................................................... 9
AMQP-Backed Channels ............................................................................ 9
Redis Changes .................................................................................................. 9
List Push/Pop Direction .............................................................................. 9
Queue Inbound Gateway Default Serializer .................................................. 9
HTTP Changes .................................................................................................. 9

4.3.6.RELEASE

Spring Integration

iii

Spring Integration Reference Manual

SFTP Changes .................................................................................................. 9
Factory Bean ............................................................................................. 9
chmod ....................................................................................................... 9
FTP Changes ................................................................................................... 10
Session Changes ..................................................................................... 10
Router Changes ............................................................................................... 10
Header Mapping ............................................................................................... 10
General .................................................................................................... 10
AMQP Header Mapping ............................................................................ 10
Groovy Scripts ................................................................................................. 10
@InboundChannelAdapter ................................................................................ 10
XMPP changes ................................................................................................ 10
WireTap Late Binding ....................................................................................... 11
ChannelMessageStoreQueryProvider ................................................................ 11
WebSocket Changes ........................................................................................ 11
Barrier Changes ............................................................................................... 11
AMQP Changes ............................................................................................... 11
III. Overview of Spring Integration Framework ............................................................................ 12
3. Spring Integration Overview .......................................................................................... 13
3.1. Background ....................................................................................................... 13
3.2. Goals and Principles .......................................................................................... 13
3.3. Main Components ............................................................................................. 14
Message .......................................................................................................... 14
Message Channel ............................................................................................ 14
Message Endpoint ............................................................................................ 15
3.4. Message Endpoints ........................................................................................... 15
Transformer ..................................................................................................... 16
Filter ................................................................................................................ 16
Router .............................................................................................................. 16
Splitter ............................................................................................................. 16
Aggregator ....................................................................................................... 17
Service Activator .............................................................................................. 17
Channel Adapter .............................................................................................. 18
3.5. Configuration and @EnableIntegration ................................................................ 18
3.6. Programming Considerations .............................................................................. 20
3.7. Programming Tips and Tricks ............................................................................. 20
IV. Core Messaging .................................................................................................................. 23
4. Messaging Channels .................................................................................................... 24
4.1. Message Channels ............................................................................................ 24
The MessageChannel Interface ......................................................................... 24
PollableChannel ....................................................................................... 24
SubscribableChannel ................................................................................ 24
Message Channel Implementations ................................................................... 24
PublishSubscribeChannel .......................................................................... 25
QueueChannel ......................................................................................... 25
PriorityChannel ......................................................................................... 25
RendezvousChannel ................................................................................. 26
DirectChannel .......................................................................................... 26
ExecutorChannel ...................................................................................... 27
Scoped Channel ....................................................................................... 28

4.3.6.RELEASE

Spring Integration

iv

Spring Integration Reference Manual

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 .............................................................................................
4.2. Poller ................................................................................................................
Polling Consumer .............................................................................................
Pollable Message Source .................................................................................
Conditional Pollers for Message Sources ...........................................................
Background ..............................................................................................
"Smart" Polling .........................................................................................
SimpleActiveIdleMessageSourceAdvice .....................................................
CompoundTriggerAdvice ...........................................................................
4.3. Channel Adapter ...............................................................................................
Configuring An Inbound Channel Adapter ..........................................................
Configuring An Outbound Channel Adapter ........................................................
Channel Adapter Expressions and Scripts .........................................................
4.4. Messaging Bridge ..............................................................................................
Introduction ......................................................................................................
Configuring Bridge ............................................................................................
5. Message Construction ..................................................................................................
5.1. Message ...........................................................................................................
The Message Interface .....................................................................................
Message Headers ............................................................................................
MessageHeaderAccessor API ...................................................................
Message ID Generation ............................................................................
Message Implementations .................................................................................
The MessageBuilder Helper Class ....................................................................
6. Message Routing .........................................................................................................
6.1. Routers .............................................................................................................
Overview ..........................................................................................................
Common Router Parameters .............................................................................
Inside and Outside of a Chain ...................................................................
Top-Level (Outside of a Chain) .................................................................
Router Implementations ....................................................................................
PayloadTypeRouter ..................................................................................
HeaderValueRouter ..................................................................................
RecipientListRouter ...................................................................................

4.3.6.RELEASE

Spring Integration

28
30
30
31
31
32
34
35
35
36
36
36
36
37
39
39
39
40
40
40
41
41
41
42
42
43
43
44
45
45
45
46
47
47
47
47
48
49
50
50
52
52
52
54
54
55
56
56
56
57

v

Spring Integration Reference Manual

RecipientListRouterManagement ...............................................................
XPath Router ...........................................................................................
Routing and Error handling .......................................................................
Configuring (Generic) Router ............................................................................
Configuring a Content Based Router with XML ...........................................
Configuring a Router with Annotations .......................................................
Dynamic Routers ..............................................................................................
Manage Router Mappings using the Control Bus ........................................
Manage Router Mappings using JMX ........................................................
Routing Slip .............................................................................................
Process Manager Enterprise Integration Pattern .........................................
6.2. Filter .................................................................................................................
Introduction ......................................................................................................
Configuring Filter ..............................................................................................
Configuring a Filter with XML ....................................................................
Configuring a Filter with Annotations .........................................................
6.3. Splitter ..............................................................................................................
Introduction ......................................................................................................
Programming model .........................................................................................
Configuring Splitter ...........................................................................................
Configuring a Splitter using XML ...............................................................
Configuring a Splitter with Annotations .......................................................
6.4. Aggregator ........................................................................................................
Introduction ......................................................................................................
Functionality .....................................................................................................
Programming model .........................................................................................
AggregatingMessageHandler .....................................................................
ReleaseStrategy .......................................................................................
CorrelationStrategy ...................................................................................
LockRegistry ............................................................................................
Configuring an Aggregator ................................................................................
Configuring an Aggregator with XML .........................................................
Configuring an Aggregator with Annotations ...............................................
Managing State in an Aggregator: MessageGroupStore ......................................
6.5. Resequencer .....................................................................................................
Introduction ......................................................................................................
Functionality .....................................................................................................
Configuring a Resequencer ...............................................................................
6.6. Message Handler Chain .....................................................................................
Introduction ......................................................................................................
Configuring a Chain ..........................................................................................
6.7. Scatter-Gather ...................................................................................................
Introduction ......................................................................................................
Functionality .....................................................................................................
Configuring a Scatter-Gather Endpoint ..............................................................
6.8. Thread Barrier ...................................................................................................
7. Message Transformation ...............................................................................................
7.1. Transformer .......................................................................................................
Introduction ......................................................................................................
Configuring Transformer ...................................................................................

4.3.6.RELEASE

Spring Integration

58
58
59
59
59
60
61
64
64
64
67
67
67
68
68
70
70
70
70
71
71
72
72
72
73
73
73
75
77
77
77
77
84
85
86
86
87
87
89
89
89
92
92
92
93
94
97
97
97
97

vi

Spring Integration Reference Manual

Configuring Transformer with XML ............................................................ 97
Common Transformers ............................................................................. 98
Configuring a Transformer with Annotations ............................................. 103
Header Filter .................................................................................................. 103
Codec-Based Transformers ............................................................................. 104
7.2. Content Enricher .............................................................................................. 104
Introduction .................................................................................................... 104
Header Enricher ............................................................................................. 104
Configuring a Header Enricher with Java Configuration ............................. 106
Configuring a Header Enricher with the Java DSL .................................... 106
Header Channel Registry ........................................................................ 106
Payload Enricher ............................................................................................ 107
Configuration .......................................................................................... 108
Examples ............................................................................................... 109
7.3. Claim Check .................................................................................................... 111
Introduction .................................................................................................... 111
Incoming Claim Check Transformer ................................................................. 111
Outgoing Claim Check Transformer ................................................................. 112
A word on Message Store .............................................................................. 113
7.4. Codec ............................................................................................................. 114
Introduction .................................................................................................... 114
EncodingPayloadTransformer .......................................................................... 114
DecodingTransformer ...................................................................................... 114
CodecMessageConverter ................................................................................ 114
Kryo ............................................................................................................... 114
Customizing Kryo ................................................................................... 114
8. Messaging Endpoints .................................................................................................. 117
8.1. Message Endpoints ......................................................................................... 117
Message Handler ........................................................................................... 117
Event Driven Consumer .................................................................................. 117
Polling Consumer ........................................................................................... 118
Namespace Support ....................................................................................... 119
Change Polling Rate at Runtime ..................................................................... 123
Payload Type Conversion ............................................................................... 124
Asynchronous polling ...................................................................................... 125
Endpoint Inner Beans ..................................................................................... 126
8.2. Endpoint Roles ................................................................................................ 126
8.3. Leadership Event Handling ............................................................................... 127
8.4. Messaging Gateways ....................................................................................... 128
Enter the GatewayProxyFactoryBean ............................................................... 128
Gateway XML Namespace Support ................................................................. 128
Setting the Default Reply Channel ................................................................... 129
Gateway Configuration with Annotations and/or XML ........................................ 129
Mapping Method Arguments to a Message ...................................................... 131
@MessagingGateway Annotation .................................................................... 132
Invoking No-Argument Methods ....................................................................... 133
Error Handling ................................................................................................ 134
Asynchronous Gateway .................................................................................. 135
Introduction ............................................................................................ 135
ListenableFuture ..................................................................................... 136

4.3.6.RELEASE

Spring Integration

vii

Spring Integration Reference Manual

AsyncTaskExecutor ................................................................................
CompletableFuture .................................................................................
Reactor Promise .....................................................................................
Gateway behavior when no response arrives ...................................................
8.5. Service Activator ..............................................................................................
Introduction ....................................................................................................
Configuring Service Activator ..........................................................................
Asynchronous Service Activator ......................................................................
8.6. Delayer ...........................................................................................................
Introduction ....................................................................................................
Configuring Delayer ........................................................................................
Delayer and Message Store ............................................................................
8.7. Scripting support ..............................................................................................
Script configuration .........................................................................................
8.8. Groovy support ................................................................................................
Groovy configuration .......................................................................................
Control Bus ....................................................................................................
8.9. Adding Behavior to Endpoints ..........................................................................
Introduction ....................................................................................................
Provided Advice Classes ................................................................................
Retry Advice ..........................................................................................
Circuit Breaker Advice ............................................................................
Expression Evaluating Advice ..................................................................
Custom Advice Classes ..................................................................................
Other Advice Chain Elements .........................................................................
Handle Message Advice .................................................................................
Advising Filters ...............................................................................................
Advising Endpoints Using Annotations .............................................................
Ordering Advices within an Advice Chain .........................................................
Advised Handler Properties .............................................................................
Idempotent Receiver Enterprise Integration Pattern ..........................................
8.10. Logging Channel Adapter ...............................................................................
Configuring with Java Configuration .................................................................
9. System Management ..................................................................................................
9.1. Metrics and Management .................................................................................
Configuring Metrics Capture ............................................................................
MessageChannel Metric Features ...................................................................
MessageHandler Metric Features ....................................................................
Time-Based Average Estimates .......................................................................
Metrics Factory ...............................................................................................
9.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 ObjectNames ..............................................................................
JMX Improvements .................................................................................

4.3.6.RELEASE

Spring Integration

136
137
138
139
141
141
141
143
143
143
143
145
146
147
149
149
151
152
152
153
153
158
159
159
160
160
161
161
162
162
162
164
165
166
166
166
167
168
168
169
170
170
171
172
172
172
173
173
174
175

viii

Spring Integration Reference Manual

Orderly Shutdown Managed Operation ....................................................
9.3. Message History ..............................................................................................
Message History Configuration ........................................................................
9.4. Message Store ................................................................................................
MessageGroupFactory ....................................................................................
Persistence MessageGroupStore and Lazy-Load ..............................................
9.5. Metadata Store ................................................................................................
Idempotent Receiver and Metadata Store ........................................................
MetadataStoreListener ....................................................................................
9.6. Control Bus .....................................................................................................
9.7. Orderly Shutdown ............................................................................................
9.8. Integration Graph .............................................................................................
Graph Runtime Model .....................................................................................
9.9. Integration Graph Controller .............................................................................
V. Integration Endpoints ..........................................................................................................
10. Endpoint Quick Reference Table ...............................................................................
11. AMQP Support .........................................................................................................
11.1. Introduction ....................................................................................................
11.2. Inbound Channel Adapter ...............................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
11.3. Inbound Gateway ...........................................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
11.4. Inbound Endpoint Acknowledge Mode .............................................................
11.5. Outbound Channel Adapter ............................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
11.6. Outbound Gateway ........................................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
11.7. Async Outbound Gateway ..............................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
11.8. Outbound Message Conversion ......................................................................
11.9. Outbound User Id ..........................................................................................
11.10. Delayed Message Exchange .........................................................................
11.11. AMQP Backed Message Channels ................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
11.12. AMQP Message Headers .............................................................................
11.13. AMQP Samples ...........................................................................................
12. Spring ApplicationEvent Support ................................................................................
12.1. Receiving Spring Application Events ...............................................................
12.2. Sending Spring Application Events ..................................................................
13. Feed Adapter ...........................................................................................................
13.1. Introduction ....................................................................................................
13.2. Feed Inbound Channel Adapter ......................................................................
14. File Support .............................................................................................................
14.1. Introduction ....................................................................................................

4.3.6.RELEASE

Spring Integration

177
177
178
179
181
181
182
183
183
183
184
185
188
189
191
192
196
196
196
199
200
201
202
203
203
204
205
206
207
209
209
210
212
212
213
213
214
214
215
215
216
218
220
220
220
222
222
222
224
224

ix

Spring Integration Reference Manual

14.2. Reading Files ................................................................................................
Namespace Support .......................................................................................
WatchServiceDirectoryScanner ........................................................................
Limiting Memory Consumption ........................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
'Tail’ing Files ..................................................................................................
14.3. Writing files ...................................................................................................
Generating File Names ...................................................................................
Specifying the Output Directory .......................................................................
Dealing with Existing Destination Files .............................................................
Flushing Files When using APPEND_NO_FLUSH ............................................
File Timestamps .............................................................................................
File Outbound Channel Adapter ......................................................................
Outbound Gateway .........................................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
14.4. File Transformers ...........................................................................................
14.5. File Splitter ....................................................................................................
15. FTP/FTPS Adapters ..................................................................................................
15.1. Introduction ....................................................................................................
15.2. FTP Session Factory .....................................................................................
15.3. Delegating Session Factory ............................................................................
15.4. FTP Inbound Channel Adapter .......................................................................
Recovering from Failures ................................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
15.5. FTP Streaming Inbound Channel Adapter .......................................................
Configuring with Java Configuration .................................................................
15.6. FTP Outbound Channel Adapter .....................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
15.7. FTP Outbound Gateway .................................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
Outbound Gateway Partial Success (mget and mput) .......................................
15.8. FTP Session Caching ....................................................................................
15.9. RemoteFileTemplate ......................................................................................
15.10. MessageSessionCallback .............................................................................
16. GemFire Support ......................................................................................................
16.1. Introduction ....................................................................................................
16.2. Inbound Channel Adapter ...............................................................................
16.3. Continuous Query Inbound Channel Adapter ...................................................
16.4. Outbound Channel Adapter ............................................................................
16.5. Gemfire Message Store .................................................................................
16.6. Gemfire Lock Registry ....................................................................................
16.7. Gemfire Metadata Store .................................................................................
17. HTTP Support ..........................................................................................................
17.1. Introduction ....................................................................................................
17.2. Http Inbound Components ..............................................................................

4.3.6.RELEASE

Spring Integration

224
226
228
229
229
230
230
232
232
233
234
235
235
235
236
236
237
237
238
240
240
240
242
242
245
246
247
248
249
249
250
251
252
256
257
257
258
259
259
261
261
261
261
262
263
264
264
266
266
266

x

Spring Integration Reference Manual

17.3. Http Outbound Components ...........................................................................
17.4. HTTP Namespace Support .............................................................................
Introduction ....................................................................................................
Inbound ..........................................................................................................
Request Mapping Support ...............................................................................
Cross-Origin Resource Sharing (CORS) Support ..............................................
Response StatusCode ....................................................................................
URI Template Variables and Expressions ........................................................
Outbound .......................................................................................................
Mapping URI Variables ...................................................................................
Controlling URI Encoding ................................................................................
17.5. Timeout Handling ...........................................................................................
17.6. HTTP Proxy configuration ...............................................................................
17.7. HTTP Header Mappings .................................................................................
17.8. Integration Graph Controller ...........................................................................
17.9. HTTP Samples ..............................................................................................
Multipart HTTP request - RestTemplate (client) and Http Inbound Gateway
(server) ..........................................................................................................
18. JDBC Support ..........................................................................................................
18.1. Inbound Channel Adapter ...............................................................................
Polling and Transactions .................................................................................
Max-rows-per-poll versus Max-messages-per-poll .............................................
18.2. Outbound Channel Adapter ............................................................................
18.3. Outbound Gateway ........................................................................................
18.4. JDBC Message Store .....................................................................................
The Generic JDBC Message Store ..................................................................
Backing Message Channels ............................................................................
Initializing the Database ..................................................................................
Partitioning a Message Store ..........................................................................
18.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 .......................................................................................................
18.6. JDBC Lock Registry .......................................................................................
19. JPA Support .............................................................................................................
19.1. Supported Persistence Providers ....................................................................
19.2. Java Implementation ......................................................................................
19.3. Namespace Support .......................................................................................
Common XML Namespace Configuration Attributes ..........................................
Providing JPA Query Parameters ....................................................................
Transaction Handling ......................................................................................
19.4. Inbound Channel Adapter ...............................................................................
Configuration Parameter Reference .................................................................
19.5. Outbound Channel Adapter ............................................................................

4.3.6.RELEASE

Spring Integration

268
269
269
269
270
271
272
273
273
275
276
276
279
280
280
281
281
283
283
284
285
285
287
288
288
289
291
291
291
292
292
292
294
295
296
297
297
298
299
300
300
301
302
302
304
304
305
306
307

xi

Spring Integration Reference Manual

20.

21.

22.

23.

Using an Entity Class .....................................................................................
Using JPA Query Language (JPA QL) .............................................................
Using Native Queries ......................................................................................
Using Named Queries ....................................................................................
Configuration Parameter Reference .................................................................
19.6. Outbound Gateways .......................................................................................
Common Configuration Parameters .................................................................
Updating Outbound Gateway ..........................................................................
Retrieving Outbound Gateway .........................................................................
JPA Outbound Gateway Samples ....................................................................
JMS Support ............................................................................................................
20.1. Inbound Channel Adapter ...............................................................................
Transactions ...................................................................................................
20.2. Message-Driven Channel Adapter ...................................................................
Inbound Conversion Errors .............................................................................
20.3. Outbound Channel Adapter ............................................................................
Transactions ...................................................................................................
20.4. Inbound Gateway ...........................................................................................
20.5. Outbound Gateway ........................................................................................
Gateway Reply Correlation .............................................................................
Async Gateway ..............................................................................................
Attribute Reference .........................................................................................
20.6. Mapping Message Headers to/from JMS Message ...........................................
20.7. Message Conversion, Marshalling and Unmarshalling ......................................
20.8. JMS Backed Message Channels .....................................................................
20.9. Using JMS Message Selectors .......................................................................
20.10. JMS Samples ..............................................................................................
Mail Support .............................................................................................................
21.1. Mail-Sending Channel Adapter .......................................................................
21.2. Mail-Receiving Channel Adapter .....................................................................
21.3. Inbound Mail Message Mapping .....................................................................
21.4. Mail Namespace Support ...............................................................................
21.5. Marking IMAP Messages When \Recent is Not Supported ................................
21.6. Email Message Filtering .................................................................................
21.7. Transaction Synchronization ...........................................................................
MongoDb Support .....................................................................................................
22.1. Introduction ....................................................................................................
22.2. Connecting to MongoDb .................................................................................
22.3. MongoDB Message Store ...............................................................................
MongoDB Channel Message Store ..................................................................
MongoDB Metadata Store ...............................................................................
22.4. MongoDB Inbound Channel Adapter ...............................................................
22.5. MongoDB Outbound Channel Adapter .............................................................
MQTT Support .........................................................................................................
23.1. Introduction ....................................................................................................
23.2. Inbound (message-driven) Channel Adapter ....................................................
Adding/Removing Topics at Runtime ...............................................................
Configuring with Java Configuration .................................................................
23.3. Outbound Channel Adapter ............................................................................
Configuring with Java Configuration .................................................................

4.3.6.RELEASE

Spring Integration

307
307
308
309
310
311
312
313
314
315
317
317
318
318
319
320
320
320
322
323
325
326
328
328
329
330
331
332
332
332
333
334
338
338
339
341
341
341
342
342
343
344
346
347
347
347
348
349
349
350

xii

Spring Integration Reference Manual

24. Redis Support ..........................................................................................................
24.1. Introduction ....................................................................................................
24.2. Connecting to Redis .......................................................................................
24.3. Messaging with Redis ....................................................................................
Redis Publish/Subscribe channel .....................................................................
Redis Inbound Channel Adapter ......................................................................
Redis Outbound Channel Adapter ...................................................................
Redis Queue Inbound Channel Adapter ...........................................................
Redis Queue Outbound Channel Adapter ........................................................
Redis Application Events ................................................................................
24.4. Redis Message Store .....................................................................................
Redis Channel Message Stores ......................................................................
24.5. Redis Metadata Store ....................................................................................
24.6. RedisStore Inbound Channel Adapter .............................................................
24.7. RedisStore Outbound Channel Adapter ...........................................................
24.8. Redis Outbound Command Gateway ..............................................................
24.9. Redis Queue Outbound Gateway ....................................................................
24.10. Redis Queue Inbound Gateway ....................................................................
24.11. Redis Lock Registry .....................................................................................
25. Resource Support .....................................................................................................
25.1. Introduction ....................................................................................................
25.2. Resource Inbound Channel Adapter ................................................................
26. RMI Support .............................................................................................................
26.1. Introduction ....................................................................................................
26.2. Outbound RMI ...............................................................................................
26.3. Inbound RMI ..................................................................................................
26.4. RMI namespace support ................................................................................
26.5. Configuring with Java Configuration ................................................................
27. SFTP Adapters .........................................................................................................
27.1. Introduction ....................................................................................................
27.2. SFTP Session Factory ...................................................................................
Configuration Properties ..................................................................................
27.3. Proxy Factory Bean .......................................................................................
27.4. Delegating Session Factory ............................................................................
27.5. SFTP Session Caching ..................................................................................
27.6. RemoteFileTemplate ......................................................................................
27.7. SFTP Inbound Channel Adapter .....................................................................
Recovering from Failures ................................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
27.8. SFTP Streaming Inbound Channel Adapter .....................................................
Configuring with Java Configuration .................................................................
27.9. SFTP Outbound Channel Adapter ...................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
27.10. SFTP Outbound Gateway .............................................................................
Configuring with Java Configuration .................................................................
Configuring with the Java DSL ........................................................................
Outbound Gateway Partial Success (mget and mput) .......................................
27.11. SFTP/JSCH Logging ....................................................................................

4.3.6.RELEASE

Spring Integration

352
352
352
353
353
353
354
354
355
356
356
357
357
358
360
361
362
363
364
365
365
365
367
367
367
367
367
368
369
369
369
370
372
372
373
373
374
376
376
377
378
379
379
380
381
382
386
386
387
388

xiii

Spring Integration Reference Manual

27.12. MessageSessionCallback .............................................................................
28. STOMP Support .......................................................................................................
28.1. Introduction ....................................................................................................
28.2. Overview .......................................................................................................
28.3. STOMP Inbound Channel Adapter ..................................................................
28.4. STOMP Outbound Channel Adapter ...............................................................
28.5. STOMP Headers Mapping ..............................................................................
28.6. STOMP Integration Events .............................................................................
28.7. STOMP Adapters Java Configuration ..............................................................
28.8. STOMP Namespace Support ..........................................................................
29. Stream Support ........................................................................................................
29.1. Introduction ....................................................................................................
29.2. Reading from streams ....................................................................................
29.3. Writing to streams ..........................................................................................
29.4. Stream namespace support ............................................................................
30. Syslog Support .........................................................................................................
30.1. Introduction ....................................................................................................
30.2. Syslog  .................................................................
Example Configuration ....................................................................................
31. TCP and UDP Support .............................................................................................
31.1. Introduction ....................................................................................................
31.2. UDP Adapters ...............................................................................................
31.3. TCP Connection Factories ..............................................................................
TCP Caching Client Connection Factory ..........................................................
TCP Failover Client Connection Factory ..........................................................
31.4. TCP Connection Interceptors ..........................................................................
31.5. TCP Connection Events .................................................................................
31.6. TCP Adapters ................................................................................................
31.7. TCP Gateways ..............................................................................................
31.8. TCP Message Correlation ..............................................................................
Overview ........................................................................................................
Gateways .......................................................................................................
Collaborating Outbound and Inbound Channel Adapters ...................................
Transferring Headers ......................................................................................
31.9. A Note About NIO ..........................................................................................
Thread Pool Task Executor with CALLER_RUNS Policy ...................................
31.10. SSL/TLS Support .........................................................................................
Overview ........................................................................................................
Getting Started ...............................................................................................
Advanced Techniques .....................................................................................
31.11. IP Configuration Attributes ............................................................................
31.12. IP Message Headers ....................................................................................
31.13. Annotation-Based Configuration ....................................................................
32. Twitter Support .........................................................................................................
32.1. Introduction ....................................................................................................
32.2. Twitter OAuth Configuration ............................................................................
32.3. Twitter Template ............................................................................................
32.4. Twitter Inbound Adapters ...............................................................................
Inbound Message Channel Adapter .................................................................
Direct Inbound Message Channel Adapter .......................................................

4.3.6.RELEASE

Spring Integration

388
389
389
389
389
389
390
390
391
392
394
394
394
394
394
396
396
396
396
399
399
399
401
405
405
406
407
408
410
411
411
411
411
412
414
414
416
416
416
417
418
425
426
429
429
429
429
430
431
431

xiv

Spring Integration Reference Manual

33.

34.

35.

36.

Mentions Inbound Message Channel Adapter ..................................................
Search Inbound Message Channel Adapter .....................................................
32.5. Twitter Outbound Adapter ...............................................................................
Twitter Outbound Update Channel Adapter ......................................................
Twitter Outbound Direct Message Channel Adapter ..........................................
32.6. Twitter Search Outbound Gateway ..................................................................
WebSockets Support ................................................................................................
33.1. Introduction ....................................................................................................
33.2. Overview .......................................................................................................
33.3. WebSocket Inbound Channel Adapter .............................................................
33.4. WebSocket Outbound Channel Adapter ..........................................................
33.5. WebSockets Namespace Support ...................................................................
Web Services Support ..............................................................................................
34.1. Outbound Web Service Gateways ...................................................................
34.2. Inbound Web Service Gateways .....................................................................
34.3. Web Service Namespace Support ...................................................................
34.4. Outbound URI Configuration ...........................................................................
34.5. WS Message Headers ...................................................................................
XML Support - Dealing with XML Payloads ................................................................
35.1. Introduction ....................................................................................................
35.2. Namespace Support .......................................................................................
XPath Expressions .........................................................................................
Providing Namespaces (Optional) to XPath Expressions ...........................
Using XPath Expressions with Default Namespaces .................................
35.3. Transforming XML Payloads ...........................................................................
Configuring Transformers as Beans .................................................................
UnmarshallingTransformer ......................................................................
MarshallingTransformer ...........................................................................
XsltPayloadTransformer ..........................................................................
ResultTransformers .................................................................................
Namespace Support for XML Transformers ......................................................
Namespace Configuration and ResultTransformers ...........................................
35.4. Transforming XML Messages Using XPath ......................................................
35.5. Splitting XML Messages .................................................................................
35.6. Routing XML Messages Using XPath ..............................................................
XML Payload Converter ..................................................................................
35.7. XPath Header Enricher ..................................................................................
35.8. Using the XPath Filter ....................................................................................
35.9. #xpath SpEL Function ....................................................................................
35.10. XML Validating Filter ....................................................................................
XMPP Support .........................................................................................................
36.1. Introduction ....................................................................................................
36.2. XMPP Connection ..........................................................................................
36.3. XMPP Messages ...........................................................................................
Inbound Message Channel Adapter .................................................................
Outbound Message Channel Adapter ..............................................................
36.4. XMPP Presence ............................................................................................
Inbound Presence Message Channel Adapter ..................................................
Outbound Presence Message Channel Adapter ...............................................
36.5. Advanced Configuration .................................................................................

4.3.6.RELEASE

Spring Integration

431
431
432
432
433
433
435
435
435
436
437
438
442
442
442
443
444
445
447
447
447
448
448
449
450
450
451
451
451
452
453
454
456
457
458
460
460
461
462
463
464
464
464
465
465
466
466
466
467
467

xv

Spring Integration Reference Manual

36.6. XMPP Message Headers ...............................................................................
36.7. XMPP Extensions ..........................................................................................
37. Zookeeper Support ...................................................................................................
37.1. Introduction ....................................................................................................
37.2. Zookeeper Metadata Store .............................................................................
37.3. Zookeeper Lock Registry ................................................................................
37.4. Zookeeper Leadership Event Handling ............................................................
VI. Appendices .......................................................................................................................
A. Spring Expression Language (SpEL) ...........................................................................
A.1. Introduction .....................................................................................................
A.2. SpEL Evaluation Context Customization ...........................................................
A.3. SpEL Functions ...............................................................................................
A.4. PropertyAccessors ...........................................................................................
B. Message Publishing ...................................................................................................
B.1. Message Publishing Configuration ....................................................................
Annotation-driven approach via @Publisher annotation .....................................
XML-based approach via the  element ..........................
Producing and publishing messages based on a scheduled trigger ....................
C. Transaction Support ...................................................................................................
C.1. Understanding Transactions in Message flows ..................................................
Poller Transaction Support ..............................................................................
C.2. Transaction Boundaries ...................................................................................
C.3. Transaction Synchronization ............................................................................
C.4. Pseudo Transactions .......................................................................................
D. Security in Spring Integration ......................................................................................
D.1. Introduction .....................................................................................................
D.2. Securing channels ...........................................................................................
D.3. SecurityContext Propagation ............................................................................
E. Spring Integration Samples .........................................................................................
E.1. Introduction .....................................................................................................
E.2. Where to get Samples .....................................................................................
E.3. Submitting Samples or Sample Requests .........................................................
E.4. Samples Structure ...........................................................................................
E.5. Samples ..........................................................................................................
Loan Broker ...................................................................................................
The Cafe Sample ...........................................................................................
The XML Messaging Sample ..........................................................................
F. Configuration ..............................................................................................................
F.1. Introduction .....................................................................................................
F.2. Namespace Support ........................................................................................
F.3. Configuring the Task Scheduler ........................................................................
F.4. Error Handling .................................................................................................
F.5. Global Properties .............................................................................................
F.6. Annotation Support ..........................................................................................
Messaging Meta-Annotations ..........................................................................
Annotations on @Beans .................................................................................
Creating a Bridge with Annotations ..................................................................
Advising Annotated Endpoints .........................................................................
F.7. Message Mapping rules and conventions ..........................................................
Simple Scenarios ............................................................................................

4.3.6.RELEASE

Spring Integration

468
469
472
472
472
472
472
474
475
475
475
476
477
479
479
479
481
483
485
485
486
487
487
489
491
491
491
492
494
494
494
494
495
496
497
501
505
506
506
506
507
508
509
510
514
515
517
517
517
517

xvi

Spring Integration Reference Manual

Complex Scenarios .........................................................................................
G. Additional Resources .................................................................................................
G.1. Spring Integration Home ..................................................................................
H. Change History ..........................................................................................................
H.1. Changes between 4.1 and 4.2 .........................................................................
H.2. New Components ............................................................................................
Major Management/JMX Rework .....................................................................
MongoDB Metadata Store ...............................................................................
SecuredChannel Annotation ............................................................................
SecurityContext Propagation ...........................................................................
FileSplitter ......................................................................................................
Zookeeper Support .........................................................................................
Thread Barrier ................................................................................................
STOMP Support .............................................................................................
Codec ............................................................................................................
Message PreparedStatement Setter ................................................................
H.3. General Changes ............................................................................................
Wire Tap ........................................................................................................
File Changes ..................................................................................................
Appending New Lines .............................................................................
Ignoring Hidden Files ..............................................................................
Writing InputStream Payloads .................................................................
HeadDirectoryScanner ............................................................................
Last Modified Filter .................................................................................
WatchService 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 ..............................................................................
API Changes ..................................................................................................
JMS Changes ................................................................................................
Reply Listener Lazy Initialization ..............................................................
Conversion Errors in Message-Driven Endpoints ......................................
Default Acknowledge Mode .....................................................................
Shared Subscriptions ..............................................................................
Conditional Pollers ..........................................................................................
AMQP Changes .............................................................................................
Publisher Confirms .................................................................................
Correlation Data .....................................................................................
The Inbound Gateway properties .............................................................
XPath Splitter Improvements ...........................................................................
HTTP Changes ..............................................................................................
CORS ....................................................................................................
Inbound Gateway Timeout ......................................................................

4.3.6.RELEASE

Spring Integration

520
522
522
523
523
523
523
523
523
523
523
523
524
524
524
524
524
524
524
524
524
524
525
525
525
525
525
525
525
525
525
525
526
526
526
526
526
526
526
526
527
527
527
527
527
527
527
527
527
528

xvii

Spring Integration Reference Manual

Form Data ..............................................................................................
Gateway Changes ..........................................................................................
Gateway Methods can Return CompletableFuture ...............................
MessagingGateway Annotation ................................................................
Aggregator Changes .......................................................................................
Aggregator Performance .........................................................................
Output Message Group Processor ...........................................................
(S)FTP Changes ............................................................................................
Inbound channel adapters .......................................................................
Gateway Partial Results ..........................................................................
Delegating Session Factory .....................................................................
Default Sftp Session Factory ...................................................................
Message Session Callback .....................................................................
Websocket Changes .......................................................................................
Application Event Adapters changes ................................................................
H.4. Changes between 4.0 and 4.1 .........................................................................
New Components ...........................................................................................
Promise Gateway .............................................................................
WebSocket support ................................................................................
Scatter-Gather EIP pattern ......................................................................
Routing Slip Pattern ................................................................................
Idempotent Receiver Pattern ...................................................................
BoonJsonObjectMapper ..........................................................................
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 StatusCode ........................................
MQTT Adapter Changes .........................................................................
FTP/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 .......................................................................................
Async Gateway ......................................................................................
Aggregator Advice Chain ........................................................................
Outbound Channel Adapter and Scripts ...................................................
Resequencer Changes ...........................................................................
Optional POJO method parameter ...........................................................
QueueChannel: backed Queue type ........................................................
ChannelInterceptor Changes ...................................................................
IMAP PEEK ...........................................................................................

4.3.6.RELEASE

Spring Integration

528
528
528
528
528
528
528
528
528
528
529
529
529
529
529
529
529
529
530
530
530
530
530
530
530
530
530
530
531
531
531
531
531
531
531
531
532
532
532
532
532
532
532
532
532
533
533
533
533
533

xviii

Spring Integration Reference Manual

H.5. Changes between 3.0 and 4.0 ......................................................................... 533
New Components ........................................................................................... 533
MQTT Channel Adapters ........................................................................ 533
@EnableIntegration ................................................................................ 533
@IntegrationComponentScan .................................................................. 533
@EnableMessageHistory ........................................................................ 533
@MessagingGateway ............................................................................. 534
Spring Boot @EnableAutoConfiguration ................................................... 534
@GlobalChannelInterceptor ..................................................................... 534
@IntegrationConverter ............................................................................ 534
@EnablePublisher .................................................................................. 534
Redis Channel Message Stores .............................................................. 534
MongodDB Channel Message Store ........................................................ 534
@EnableIntegrationMBeanExport ............................................................ 534
ChannelSecurityInterceptorFactoryBean ................................................... 535
Redis Command Gateway ...................................................................... 535
RedisLockRegistry and GemfireLockRegistry ............................................ 535
@Poller .................................................................................................. 535
@InboundChannelAdapter and SmartLifecycle for Annotated Endpoints ..... 535
Twitter Search Outbound Gateway .......................................................... 535
Gemfire Metadata Store .......................................................................... 535
@BridgeFrom and @BridgeTo Annotations .............................................. 535
Meta Messaging Annotations .................................................................. 535
General Changes ........................................................................................... 536
Requires Spring Framework 4.0 .............................................................. 536
Header Type for XPath Header Enricher .................................................. 536
Object To Json Transformer: Node Result ............................................... 536
JMS Header Mapping ............................................................................. 536
JMS Outbound Channel Adapter ............................................................. 536
JMS Inbound Channel Adapter ................................................................ 536
Datatype Channels ................................................................................. 536
Simpler Retry Advice Configuration ......................................................... 536
Correlation Endpoint: Time-based Release Strategy ................................. 537
Redis Metadata Store ............................................................................. 537
JdbcChannelMessageStore and PriorityChannel ....................................... 537
AMQP Endpoints Delivery Mode ............................................................. 537
FTP Timeouts ........................................................................................ 537
Twitter: StatusUpdatingMessageHandler .................................................. 537
JPA Retrieving Gateway: id-expression .................................................... 537
TCP Deserialization Events ..................................................................... 537
Messaging Annotations on @Bean Definitions .......................................... 538
H.6. Changes Between 2.2 and 3.0 ......................................................................... 538
New Components ........................................................................................... 538
HTTP Request Mapping .......................................................................... 538
Spring Expression Language (SpEL) Configuration ................................... 538
SpEL Functions Support ......................................................................... 538
SpEL PropertyAccessors Support ............................................................ 538
Redis: New Components ........................................................................ 538
Header Channel Registry ........................................................................ 539
MongoDB support: New ConfigurableMongoDbMessageStore ................... 539

4.3.6.RELEASE

Spring Integration

xix

Spring Integration Reference Manual

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 ............................................
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 ..........................................................................
H.7. 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/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 ...................................................................................

4.3.6.RELEASE

Spring Integration

539
539
539
539
540
540
540
540
540
540
541
541
541
541
541
541
542
542
543
543
544
544
544
544
544
544
544
545
545
545
545
545
546
546
546
546
546
546
546
546
546
546
547
547
547
547
548
548
548
548

xx

Spring Integration Reference Manual

JMS Oubound Gateway Improvements ....................................................
object-to-json-transformer ........................................................................
HTTP Support ........................................................................................
H.8. 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 .......................................
Source Code now hosted on Github ........................................................
Improved Source Code Visibility with Sonar .............................................
New Samples .................................................................................................
H.9. Changes between 1.0 and 2.0 .........................................................................
Spring 3 support .............................................................................................
Support for the Spring Expression Language (SpEL) ................................
ConversionService 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/UDP Adapters .................................................................................
Twitter Adapters .....................................................................................
XMPP Adapters ......................................................................................
FTP/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 ........................................

4.3.6.RELEASE

Spring Integration

548
548
549
549
549
549
549
549
550
550
550
550
551
551
551
551
551
551
552
552
552
553
553
553
553
553
553
553
554
554
554
554
554
554
554
554
555
555
555
555
555
555
555
555
555
555
555
556
556
556

xxi

Part I. Preface

Spring Integration Reference Manual

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

1 Compatible Java Versions
For Spring Integration 4.3.x, the minimum compatible Java version is Java SE 6. Older versions of
Java are not supported.
Spring Integration 4.3.x is also compatible with Java SE 7 as well as Java SE 8.
Certain features (such as Optional payloads and CompletableFuture gateway method return
types) require Java 8.
While the jars are compatible with Java 6, Java 8 is required to build the project. see Checking out
and Building.

2 Compatible Versions of the Spring Framework
Spring Integration 4.3.x requires Spring Framework 4.3 or later.

3 Code Conventions
The Spring Framework 2.0 introduced support for namespaces, which simplifies the XML configuration
of the application context, and consequently Spring Integration provides broad namespace support. This
reference guide applies the following conventions for all code examples that use namespace support:
The int namespace prefix will be used for Spring Integration’s core namespace support. Each Spring
Integration adapter type (module) will provide its own namespace, which is configured using the following
convention:
int- followed by the name of the module, e.g. int-twitter, int-stream, …



For a detailed explanation regarding Spring Integration’s namespace support see Section F.2,
“Namespace Support”.
Note
Please note that the namespace prefix can be freely chosen. You may even choose not to use any
namespace prefixes at all. Therefore, apply the convention that suits your application needs best.

4.3.6.RELEASE

Spring Integration

ii

Spring Integration Reference Manual

Be aware, though, that SpringSource Tool Suite™ (STS) uses the same namespace conventions
for Spring Integration as used in this reference guide.

4.3.6.RELEASE

Spring Integration

iii

Spring Integration Reference Manual

1. Conventions in this Book
In some cases, to aid formatting, when specifying long fully-qualified class names, we shorten the
package org.springframework to o.s and org.springframework.integration to o.s.i,
such as with o.s.i.transaction.TransactionSynchronizationFactory.

4.3.6.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 4.3. If you are interested in the changes and features, that were introduced in
earlier versions, please see chapter: Appendix H, Change History

Spring Integration Reference Manual

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

2.1 New Components
AMQP Async Outbound Gateway
See Section 11.7, “Async Outbound Gateway”.

MessageGroupFactory
The new MessageGroupFactory strategy has been introduced to allow a control over MessageGroup
instances in MessageGroupStore logic. The SimpleMessageGroupFactory is provided for the
SimpleMessageGroup with the GroupType.HASH_SET as the default factory for the standard
MessageGroupStore implementations. See Section 9.4, “Message Store” for more information.

PersistentMessageGroup
The PersistentMessageGroup, - lazy-load proxy, - implementation is provided for persistent
MessageGroupStore s, which return this instance for the getMessageGroup() when their
lazyLoadMessageGroups is true (defaults). See Section 9.4, “Message Store” for more information.

FTP/SFTP Streaming Inbound Channel Adapters
New inbound channel adapters are provided that return an InputStream for each file allowing you
to retrieve remote files without writing them to the local file system See Section 15.5, “FTP Streaming
Inbound Channel Adapter” and Section 27.8, “SFTP Streaming Inbound Channel Adapter” for more
information.

Stream Transformer
A new StreamTransformer is provided to transform an InputStream payload to either a byte[]
or String. See the section called “Stream Transformer” for more information.

Integration Graph
A new IntegrationGraphServer together with the IntegrationGraphController REST
service are provided to expose the runtime model of a Spring Integration application as a graph. See
Section 9.8, “Integration Graph” for more information.

JDBC Lock Registry
A new JdbcLockRegistry is provided for distributed locks shared through the data base table. See
Section 18.6, “JDBC Lock Registry” for more information.

Leader Initiator for Lock Registry
A new LeaderInitiator implementation is provided based on the LockRegistry strategy. See
Section 8.3, “Leadership Event Handling” for more information.

4.3.6.RELEASE

Spring Integration

6

Spring Integration Reference Manual

2.2 General Changes
Core Changes
Outbound Gateway within Chain
Previously, it was possible to specify a reply-channel on an outbound gateway within a chain. It
was completely ignored; the gateway’s reply goes to the next chain element, or to the chain’s output
channel if the gateway is the last element. This condition is now detected and disallowed. If you have
such configuration, simply remove the reply-channel.
Async Service Activator
An option to make the Service Asynchronous has been added. See the section called “Asynchronous
Service Activator” for more information.
Messaging Annotation Support changes
The Messaging Annotation Support doesn’t require any more @MessageEndpoint (or any other
@Component) annotation declaration on the class level. To restore the previous behaviour
specify the spring.integration.messagingAnnotations.require.componentAnnotation
of spring.integration.properties as true. See Section F.5, “Global Properties” and
Section F.6, “Annotation Support” for more information.

Mail Changes
Customizable User Flag
The customizable userFlag added in 4.2.2 to provide customization of the flag used to denote that
the mail has been seen is now available using the XML namespace. See Section 21.5, “Marking IMAP
Messages When \Recent is Not Supported” for more information.
Mail Message Mapping
There is now an option to map inbound mail messages with the MessageHeaders containing the mail
headers and the payload containing the email content. Previously, the payload was always the raw
MimeMessage. See Section 21.3, “Inbound Mail Message Mapping” for more information.

JMS Changes
Header Mapper
The DefaultJmsHeaderMapper now maps the standard correlationId header as a message
property by invoking its toString() method. See Section 20.6, “Mapping Message Headers to/from
JMS Message” for more information.
Async Gateway
The JMS Outbound gateway now has an async property. See the section called “Async Gateway” for
more information.

Aggregator Changes
There is a change in behavior when a POJO aggregator releases a collection of Message objects;
this is rare but if your application does that, you will need to make a small change to your POJO. See
this Important note for more information.

4.3.6.RELEASE

Spring Integration

7

Spring Integration Reference Manual

TCP/UDP Changes
Events
A new TcpConnectionServerListeningEvent is emitted when a server connection factory is
started. See Section 31.5, “TCP Connection Events” for more information.
The destination-expression and socket-expression are now available for the . See Section 31.2, “UDP Adapters” for more information.
Stream Deserializers
The various deserializers that can’t allocate the final buffer until the whole message has been assembled
now support pooling of the raw buffer into which the data is received, rather than creating and discarding
a buffer for each message. See Section 31.3, “TCP Connection Factories” for more information.
TCP Message Mapper
The message mapper now, optionally, sets a configured content type header. See Section 31.12, “IP
Message Headers” for more information.

File Changes
Destination Directory Creation
The generated file name for the FileWritingMessageHandler can represent sub-path to save the
desired directory structure for file in the target directory. See the section called “Generating File Names”
for more information.
The FileReadingMessageSource now hides the WatchService directory scanning logic in the
inner class. The use-watch-service and watch-events options are provided to enable such
a behaviour. The top level WatchServiceDirectoryScanner has been deprecated because of
inconsistency around API. See the section called “WatchServiceDirectoryScanner” for more information.
Buffer Size
When writing files, you can now specify the buffer size to use.
Appending and Flushing
You can now avoid flushing files when appending and use a number of strategies to flush the data
during idle periods. See the section called “Flushing Files When using APPEND_NO_FLUSH” for more
information.
Preserving Timestamps
The outbound channel adapter can now be configured to set the destination file’s lastmodified
timestamp. See the section called “File Timestamps” for more information.
Splitter Changes
The FileSplitter will now automatically close an (S)FTP session when the file is completely read.
This applies when the outbound gateway returns an InputStream or the new (S)FTP streaming
channel adapters are being used. Also a new markers-json options has been introduced to convert
FileSplitter.FileMarker to JSON String for relaxed downstream network interaction. See
Section 14.5, “File Splitter” for more information.

4.3.6.RELEASE

Spring Integration

8

Spring Integration Reference Manual

AMQP Changes
Content Type Message Converter
The
outbound
endpoints
now
support
a
RabbitTemplate
configured
with
a
ContentTypeDelegatingMessageConverter such that the converter can be chosen based on the
message content type. See Section 11.8, “Outbound Message Conversion” for more information.
Headers for Delayed Message Handling
Spring AMQP 1.6 adds support for Delayed Message Exchanges. Header mapping now supports the
headers (amqp_delay and amqp_receivedDelay) used by this feature.
AMQP-Backed Channels
AMQP-backed channels now support message mapping. See Section 11.11, “AMQP Backed Message
Channels” for more information.

Redis Changes
List Push/Pop Direction
Previously, the queue channel adapters always used the Redis List in a fixed direction, pushing to
the left end and reading from the right end. It is now possible to configure the reading and writing
direction using rightPop and leftPush options for the RedisQueueMessageDrivenEndpoint
and RedisQueueOutboundChannelAdapter respectively. See the section called “Redis Queue
Inbound Channel Adapter” and the section called “Redis Queue Outbound Channel Adapter” for more
information.
Queue Inbound Gateway Default Serializer
The
default
serializer
in
the
inbound
gateway
has
been
changed
to
a
JdkSerializationRedisSerializer for compatibility with the outbound gateway. See
Section 24.10, “Redis Queue Inbound Gateway” for more information.

HTTP Changes
Previously, with requests that had a body (such as POST) that had no content-type header, the body
was ignored. With this release, the content type of such requests is considered to be application/
octet-stream as recommended by RFC 2616. See Section 17.2, “Http Inbound Components” for
more information.

SFTP Changes
Factory Bean
A new factory bean is provided to simplify the configuration of Jsch proxies for SFTP. See Section 27.3,
“Proxy Factory Bean” for more information.
chmod
The SFTP outbound gateway (for put and mput commands) and the SFTP outbound channel
adapter now support the chmod attribute to change the remote file permissions after uploading. See

4.3.6.RELEASE

Spring Integration

9

Spring Integration Reference Manual

Section 27.9, “SFTP Outbound Channel Adapter” and Section 27.10, “SFTP Outbound Gateway” for
more information.

FTP Changes
Session Changes
The FtpSession now supports null for the list() and listNames() method, since it is
possible by the underlying FTP Client. With that the FtpOutboundGateway can now be configured
without remoteDirectory expression. And the  can be
configured without remote-directory/remote-directory-expression. See Chapter 15, FTP/
FTPS Adapters for more information.

Router Changes
The ErrorMessageExceptionTypeRouter supports now the Exception superclass mappings
to avoid duplication for the same channel in case of several inheritors. For this purpose the
ErrorMessageExceptionTypeRouter loads mapping classes during initialization to fail-fast for a
ClassNotFoundException.
See Section 6.1, “Routers” for more information.

Header Mapping
General
AMQP, WS and XMPP header mappings (e.g. request-header-mapping, reply-headermapping) now support negated patterns. See Section 11.12, “AMQP Message Headers”, Section 34.5,
“WS Message Headers”, and Section 36.6, “XMPP Message Headers” for more information.
AMQP Header Mapping
Previously, only standard AMQP headers were mapped by default; users had to explicitly enable
mapping of user-defined headers. With this release all headers are mapped by default. In addition, the
inbound amqp_deliveryMode header is no longer mapped by default. See Section 11.12, “AMQP
Message Headers” for more information.

Groovy Scripts
Groovy scripts can now be configured with the compile-static hint or any other
CompilerConfiguration options. See the section called “Groovy configuration” for more
information.

@InboundChannelAdapter
The @InboundChannelAdapter has now an alias channel attribute for regular value. In addition the
target SourcePollingChannelAdapter components can now resolve the target outputChannel
bean from its provided name (outputChannelName options) in late-binding manner. See Section F.6,
“Annotation Support” for more information.

XMPP changes
The XMPP Extensions (XEP) are now supported by the XMPP channel adapters. See Section 36.7,
“XMPP Extensions” for more information.

4.3.6.RELEASE

Spring Integration

10

Spring Integration Reference Manual

WireTap Late Binding
The WireTap ChannelInterceptor now can accept a channelName which is resolved to the target
MessageChannel later, during the first active interceptor operation. See the section called “Wire Tap”
for more information.

ChannelMessageStoreQueryProvider
The ChannelMessageStoreQueryProvider now supports H2 database. See the section called
“Backing Message Channels” for more information.

WebSocket Changes
The
ServerWebSocketContainer
now
exposes
allowedOrigins
option
and
SockJsServiceOptions a suppressCors option. See Chapter 33, WebSockets Support for more
information.

Barrier Changes
The BarrierMessageHandler now supports a discard channel to which late-arriving trigger
messages are sent. See Section 6.8, “Thread Barrier” for more information.

AMQP Changes
The AMQP outbound endpoints now support setting a delay expression for when using the RabbitMQ
Delayed Message Exchange plugin. See Section 11.10, “Delayed Message Exchange” for more
information.

4.3.6.RELEASE

Spring Integration

11

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 via declarative adapters. Those adapters provide a higherlevel 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

3. Spring Integration Overview
3.1 Background
One of the key themes of the Spring Framework is inversion of control. 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 since 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 crosscutting 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
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 execute 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, so 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 of course 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 Enterprise
Integration Patterns as described in the book of the same name by Gregor Hohpe and Bobby Woolf
(Addison Wesley, 2004). Developers who have read that book should be immediately comfortable with
the Spring Integration concepts and terminology.

3.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.
• The framework should enforce separation of concerns between business logic and integration logic.

4.3.6.RELEASE

Spring Integration

13

Spring Integration Reference Manual

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

3.3 Main Components
From the 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 component that is capable of producing and/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
would typically be managed within a layer that is logically above the application’s service layer,
interacting with those services through interfaces much in the same way that a web-tier would.

Message
In Spring Integration, a Message is a generic wrapper for any Java object combined with metadata 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, etc.) may be configured
as Message header values by an upstream component. Developers can also store any arbitrary keyvalue pairs in the headers.

Figure 3.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.

4.3.6.RELEASE

Spring Integration

14

Spring Integration Reference Manual

Figure 3.2. Message Channel
A Message Channel may follow either Point-to-Point or Publish/Subscribe semantics. With a Point-toPoint channel, at most one consumer can receive each Message sent to the channel. Publish/Subscribe
channels, on the other hand, will attempt to broadcast each Message to all of its subscribers. Spring
Integration supports both of these.
Whereas "Point-to-Point" and "Publish/Subscribe" define the two options for how many consumers will
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 variety of
channel implementations available in Spring Integration will be discussed in detail in the section called
“Message Channel Implementations”.

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 will
necessarily connect your existing application code directly. Any real-world enterprise integration solution
will require some amount of code focused upon integration concerns such as routing and transformation.
The important thing is to achieve separation of concerns between such integration logic and business
logic. In other words, as with the Model-View-Controller paradigm for web applications, the goal should
be to provide a thin but dedicated layer that translates inbound requests into service layer invocations,
and then translates service layer return values into outbound replies. The next section will provide an
overview of the Message Endpoint types that handle these responsibilities, and in upcoming chapters,
you will see how Spring Integration’s declarative configuration options provide a non-invasive way to
use each of these.

3.4 Message Endpoints
A Message Endpoint represents the "filter" of a pipes-and-filters architecture. As mentioned above, the
endpoint’s primary role is to connect application code to the messaging framework and to do so in a noninvasive 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 are discussed at length
along with all of the patterns that follow in the Enterprise Integration Patterns book. Here, we provide

4.3.6.RELEASE

Spring Integration

15

Spring Integration Reference Manual

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

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

Filter
A Message Filter determines whether a Message should be passed to an output channel at all. This
simply requires a boolean test method that may check for a particular payload content type, a property
value, the presence of a header, etc. If the Message is accepted, it is sent to the output channel, but if
not it will be 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 filter to narrow down the set of Messages to be processed
based on some criteria.
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 "filter" matches more closely with Spring Integration’s
Message Endpoint: any component that can be connected to Message Channel(s) in order to
send and/or receive Messages.

Router
A Message Router is responsible for deciding what channel or channels should receive the Message
next (if any). Typically the decision is based upon the Message’s content and/or 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 above.

Figure 3.3. 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 then send each of those to its output channel.

4.3.6.RELEASE

Spring Integration

16

Spring Integration Reference Manual

This is typically used for dividing a "composite" payload object into a group of Messages containing the
sub-divided 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 or to discard 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 necessary (if the method does not expect
a Message-typed parameter). Whenever the service object’s method returns a value, that return value
will likewise be converted to a reply Message if necessary (if it’s not already a Message). That reply
Message is sent to the output channel. If no output channel has been configured, then the reply will be
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 3.4. Service Activator
Note
As discussed in Message Channel above, channels can be Pollable or Subscribable; in this
diagram, this is depicted by the "clock" symbol and the solid arrow (poll) and the dotted arrow
(subscribe).

4.3.6.RELEASE

Spring Integration

17

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 will do some
mapping between the Message and whatever object or resource is received-from or sent-to the other
system (File, HTTP Request, JMS Message, etc). Depending on the transport, the Channel Adapter
may also populate or extract Message header values. Spring Integration provides a number of Channel
Adapters, and they will be described in upcoming chapters.

Figure 3.5. An inbound "Channel Adapter" endpoint connects a source system to a MessageChannel.
Note
Message sources can be Pollable (e.g. POP3) or Message-Driven (e.g. IMAP Idle); in this
diagram, this is depicted by the "clock" symbol and the solid arrow (poll) and the dotted arrow
(message-driven).

Figure 3.6. An outbound "Channel Adapter" endpoint connects a MessageChannel to a target system.
Note
As discussed in Message Channel above, channels can be Pollable or Subscribable; in this
diagram, this is depicted by the "clock" symbol and the solid arrow (poll) and the dotted arrow
(subscribe).

3.5 Configuration and @EnableIntegration
Throughout this document you will 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 that are used to support the runtime environment (task scheduler, implicit
channel creator, etc).

4.3.6.RELEASE

Spring Integration

18

Spring Integration Reference Manual

Important
Starting with version 4.0, the @EnableIntegration annotation has been introduced, to allow
the registration of Spring Integration infrastructure beans (see JavaDocs). This annotation is
required when only Java & Annotation configuration is used, e.g. with Spring Boot and/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 2 or more child contexts that use Spring Integration. It enables these
common components to be declared once only, in the parent context.
The @EnableIntegration annotation registers many infrastructure components with the application
context:
• Registers some built-in beans, e.g. errorChannel and its LoggingHandler, taskScheduler for
pollers, jsonPath SpEL-function etc.;
• Adds several BeanFactoryPostProcessor s to enhance the BeanFactory for global and default
integration environment;
• Adds several BeanPostProcessor s to enhance and/or convert and wrap particular beans for
integration purposes;
• Adds annotations processors to parse Messaging Annotations and registers components for them
with the application context.
The @IntegrationComponentScan annotation has also been introduced to permit classpath
scanning. This annotation plays a similar role as the standard Spring Framework @ComponentScan
annotation, but it is restricted just to Spring Integration specific components and annotations, which
aren’t reachable by the standard Spring Framework component scan mechanism. For example the
section called “@MessagingGateway Annotation”.
The
@EnablePublisher
annotation
has
been
introduced
to
register
a
PublisherAnnotationBeanPostProcessor bean and configure the default-publisherchannel for those @Publisher annotations which are provided without a channel attribute. If more
than one @EnablePublisher annotation is found, they must all have the same value for the default
channel. See the section called “Annotation-driven approach via @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 be a ChannelInterceptor.
The @IntegrationConverter annotation has been introduced to mark 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”). @IntegrationConverter annotations
can be placed at the class level (with a @Component stereotype annotation), or on @Bean methods
within @Configuration classes.

4.3.6.RELEASE

Spring Integration

19

Spring Integration Reference Manual

Also see Section F.6, “Annotation Support” for more information about Messaging Annotations.

3.6 Programming Considerations
It is generally recommended that you use plain old java objects (POJOs) whenever possible and only
expose the framework in your code when absolutely necessary.
If you do expose the framework to your classes, there are some considerations that need to be taken
into account, especially during application startup; some of these are listed here.
• If your component is ApplicationContextAware, you should generally not "use" the
ApplicationContext in the setApplicationContext() method; just 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 will likely 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.

3.7 Programming Tips and Tricks
With XML configuration and Spring Integration Namespace support, the XML Parsers hide how target
beans are built and wired together. For Java & Annotation Configuration, it is important to understand
the Framework API for the target end-user applications.
The first class citizens for EIP implementation are Message, Channel and Endpoint (see Section 3.3,
“Main Components” above). Their implementations (contracts) are:
• org.springframework.messaging.Message - see Section 5.1, “Message”;
• org.springframework.messaging.MessageChannel - see Section 4.1, “Message Channels”;
• org.springframework.integration.endpoint.AbstractEndpoint - see Section 4.2,
“Poller”.
The first two are simple enough to understand how to implement, configure and use, respectively; the
last one deserves more review.
The AbstractEndpoint is widely used throughout the Framework for different component
implementations; its main implementations are:
• EventDrivenConsumer, when we subscribe to a SubscribableChannel to listen for messages;
• PollingConsumer, when we poll for messages from a PollableChannel.
Using Messaging Annotations and/or Java DSL, you shouldn’t worry about these components, because
the Framework produces them automatically via appropriate annotations and BeanPostProcessor s.
When building components manually, the ConsumerEndpointFactoryBean should be used to help
to determine the target AbstractEndpoint implementation based on the provided inputChannel
property.
On the other hand, the ConsumerEndpointFactoryBean exhibits an another first
class citizens in the Framework - org.springframework.messaging.MessageHandler.

4.3.6.RELEASE

Spring Integration

20

Spring Integration Reference Manual

The goal of the implementation of this class is to handle the message
consumed by the endpoint from the channel. All EIP components in Spring
Integration are MessageHandler implementations, e.g. AggregatingMessageHandler,
MessageTransformingHandler, AbstractMessageSplitter etc.; as well as the target
protocol outbound adapters are implementations, too, e.g. FileWritingMessageHandler,
HttpRequestExecutingMessageHandler, AbstractMqttMessageHandler etc. When you
develop Spring Integration applications with Java & Annotation Configuration, you should take a look
into the Spring Integration module to find an appropriate MessageHandler implementation to be used
for the @ServiceActivator configuration. For example to send an XMPP message (see Chapter 36,
XMPP Support) we should configure something like this:
@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;
}

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 to the
polling and listening behavior. The listening components are pretty simple and typically
requires only one target class implementation to be ready to produce messages.
Listening components can be one-way MessageProducerSupport implementations, e.g.
AbstractMqttMessageDrivenChannelAdapter and ImapIdleChannelAdapter; and requestreply - MessagingGatewaySupport implementations, e.g. AmqpInboundGateway and
AbstractWebServiceInboundGateway.
Polling inbound endpoints are for those protocols which don’t provide a listener API or aren’t intended
for such a behavior. For example any File based protocol, as an FTP, any data bases (RDBMS or
NoSQL) etc.
These inbound endpoints consist with two components: the poller configuration, to initiate the
polling task periodically, and message source class to read data from the target protocol and
produce a message for the downstream integration flow. The first class, for poller configuration,
is SourcePollingChannelAdapter. It is one more AbstractEndpoint implementation, but
especially for the polling purpose for initiating an integration flow. Typically, with the Messaging
Annotations or Java DSL, you shouldn’t worry about this class, the Framework produces a bean for it,
based on the @InboundChannelAdapter configuration or Java DSL particular Builder.
The message source components are more important for the target application development
and they all implement the MessageSource interface, e.g. MongoDbMessageSource and
AbstractTwitterMessageSource. With that in mind, our config for reading data from an RDBMS
table with JDBC may look like:
@Bean
@InboundChannelAdapter(value = "fooChannel", poller = @Poller(fixedDelay="5000"))
public MessageSource storedProc(DataSource dataSource) {
return new JdbcPollingChannelAdapter(dataSource, "SELECT * FROM foo where status = 0");
}

4.3.6.RELEASE

Spring Integration

21

Spring Integration Reference Manual

All the required inbound and outbound classes for the target protocols you can find in the
particular Spring Integration module, in most cases in the respective package. For example springintegration-websocket adapters are:
• o.s.i.websocket.inbound.WebSocketInboundChannelAdapter
implements
MessageProducerSupport implementation to listen 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 already, starting with version 4.3, we provide
in the XSD elements definitions the description with the pointer which target classes are used to produce
beans for the adapter or gateway, for example:



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



4.3.6.RELEASE

Spring Integration

22

Part IV. Core Messaging
This section covers all aspects of the core messaging API in Spring Integration. Here you will learn about
Messages, Message Channels, and Message Endpoints. Many of the Enterprise Integration Patterns
are covered here as well, such as Filters, Routers, Transformers, Service-Activators, Splitters, and
Aggregators. The section also contains material about System Management, including the Control Bus
and Message History support.

Spring Integration Reference Manual

4. Messaging Channels
4.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 will be true if the message is sent successfully. If the send
call times out or is interrupted, then it will return false.
PollableChannel
Since Message Channels may or may not buffer Messages (as discussed in the overview), there are
two sub-interfaces defining the buffering (pollable) and non-buffering (subscribable) channel behavior.
Here is the definition of PollableChannel.
public interface PollableChannel extends MessageChannel {
Message receive();
Message receive(long timeout);
}

Similar to the send methods, when receiving a message, the return value will be null in the case of a
timeout or interrupt.
SubscribableChannel
The SubscribableChannel base interface is implemented by channels that send Messages directly
to their subscribed MessageHandler s. Therefore, they do not provide receive methods for polling, but
instead define methods for managing those subscribers:
public interface SubscribableChannel extends MessageChannel {
boolean subscribe(MessageHandler handler);
boolean unsubscribe(MessageHandler handler);
}

Message Channel Implementations
Spring Integration provides several different Message Channel implementations. Each is briefly
described in the sections below.

4.3.6.RELEASE

Spring Integration

24

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 be a MessageHandler itself, and the subscriber’s
handleMessage(Message) method will be 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 a TaskExecutor is used, 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:
public QueueChannel(int capacity)

A channel that has not reached its capacity limit will store messages in its internal queue, and the
send() method will return immediately even if no receiver is ready to handle the message. If the queue
has reached capacity, then the sender will block until room is available. Or, if using the send call that
accepts a timeout, it will block until either room is available or the timeout period elapses, whichever
occurs first. Likewise, a receive call will return immediately if a message is available on 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()
will 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's constructor.

4.3.6.RELEASE

Spring Integration

25

Spring Integration Reference Manual

RendezvousChannel
The RendezvousChannel enables a "direct-handoff" scenario where a sender will block until another
party invokes the channel’s receive() method or vice-versa. 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
are operating in different threads but simply dropping the message in a queue asynchronously is not
appropriate. In other words, with a RendezvousChannel at least 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 allows you to take advantage of any JMS provider’s
implementation for message persistence, and it will be discussed in Chapter 20, JMS Support.
However, when buffering in a queue is not necessary, the simplest approach is to rely upon the
DirectChannel discussed next.
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
above. 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 will only send 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 is subscribed to a DirectChannel, then sending a Message to that channel will trigger
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, then the outcome of the
handler’s invocation (e.g. updating a database record) will play a role in determining the ultimate result
of that transaction (commit or rollback).

4.3.6.RELEASE

Spring Integration

26

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 and
then to consider which of those need to provide buffering or to throttle input, and then 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. Below you will
see how each of these 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 via load-balancer or loadbalancer-ref attributes (mutually exclusive). The load balancing strategy is used by the Message
Dispatcher to help determine how Messages are distributed amongst Message Handlers in the case
that there are multiple Message Handlers subscribed to the same channel. As a convenience the
load-balancer attribute exposes enumeration of values pointing to pre-existing implementations of
LoadBalancingStrategy. The "round-robin" (load-balances across the handlers in rotation) and
"none" (for the cases where one wants to explicitely 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 using load-balancerref attribute which should point to a bean that implements LoadBalancingStrategy.





Note that load-balancer or load-balancer-ref attributes are mutually exclusive.
The load-balancing also works in combination with a boolean failover property. If the "failover" value
is true (the default), then the dispatcher will fall 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 are subscribed.
If a certain situation requires that the dispatcher always try to invoke the first handler, then fallback
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 loadbalancing is enabled. Without load-balancing, however, the invocation of handlers will always begin 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 will determine that order.
Note
Keep in mind that load-balancing and failover only apply 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 in the "input-channel" attribute.
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

4.3.6.RELEASE

Spring Integration

27

Spring Integration Reference Manual

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 will not block,
but it also means that the handler invocation may not occur in the sender’s thread. It therefore does not
support transactions spanning the sender and receiving handler.
Tip
Note that there are occasions where the sender may block. For example, when using
a TaskExecutor with a rejection-policy that throttles back on the client (such as the
ThreadPoolExecutor.CallerRunsPolicy), the sender’s thread will execute the method
directly anytime 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, that obviously cannot be relied
upon for transactions.
Scoped Channel
Spring Integration 1.0 provided a ThreadLocalChannel implementation, but that has been removed
as of 2.0. Now, there is a more general way for handling the same requirement by simply adding a
"scope" attribute to a channel. The value of the attribute can be any name of a Scope that is 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. Here’s an example of a ThreadLocal-based
scope being applied to a channel, including the registration of the Scope itself.











The channel above also delegates to a queue internally, but the channel is bound to the current thread,
so the contents of the queue are as well. That way the thread that sends to the channel will later be able to
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 DirectChannels 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 it.
Now, since any channel can be scoped, you can define your own scopes in addition to Thread Local.

Channel Interceptors
One of the advantages of a messaging architecture is the ability to provide common behavior and
capture meaningful information about the messages passing through the system in a non-invasive way.
Since the Message s are being sent to and received from MessageChannels, those channels provide
an opportunity for intercepting the send and receive operations. The ChannelInterceptor strategy
interface provides methods for each of those operations:

4.3.6.RELEASE

Spring Integration

28

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 calling:
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 will be sent directly to
one or more subscribers depending on the type of channel (e.g. a PublishSubscribeChannel
sends to all of its subscribers). Therefore, the preReceive(..), postReceive(..) and
afterReceiveCompletion(..) interceptor methods are only invoked 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, a
ChannelInterceptorAdapter class is also available for sub-classing. It provides no-op methods
(the void method is empty, the Message returning methods return the Message as-is, and the boolean
method returns true). Therefore, it is often easiest to extend that class and just implement the
method(s) that you need as in the following example.
public class CountingChannelInterceptor extends ChannelInterceptorAdapter {
private final AtomicInteger sendCount = new AtomicInteger();
@Override
public Message preSend(Message message, MessageChannel channel) {
sendCount.incrementAndGet();
return message;
}
}

Tip
The order of invocation for the interceptor methods depends on the type of channel. As described
above, the queue-based channels are the only ones where the receive method is intercepted in

4.3.6.RELEASE

Spring Integration

29

Spring Integration Reference Manual

the first place. Additionally, the relationship between send and receive interception depends on
the timing of separate sender and receiver threads. For example, if a receiver is already blocked
while waiting for a message the order could be: preSend, preReceive, postReceive, postSend.
However, if a receiver polls after the sender has placed a message on the channel and already
returned, the order would be: preSend, postSend, (some-time-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!). Obviously, the type of queue also plays a
role (e.g. rendezvous vs. priority). The bottom line is that you cannot rely on the order beyond the
fact that preSend will precede postSend and preReceive will precede 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()/receive() calls, regardless of any exception that is raised, thus allowing for resource
cleanup. Note, the Channel invokes these methods on the ChannelInterceptor List in the reverse order
of the initial preSend()/preReceive() calls.

MessagingTemplate
As you will see 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, sometimes it is 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/reply scenarios. For example, it is possible to send a request and
wait for a reply.
MessagingTemplate template = new MessagingTemplate();
Message reply = template.sendAndReceive(someChannel, new GenericMessage("test"));

In that 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.
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 allows you to invoke simple interfaces with payload and/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:


4.3.6.RELEASE

Spring Integration

30

Spring Integration Reference Manual

The default channel type is Point to Point. To create a Publish Subscribe channel, use the  element:


When using the  element without any sub-elements, it will create 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”). Examples of
each are shown below.
DirectChannel Configuration
As mentioned above, DirectChannel is the default type.


A default channel will have a round-robin load-balancer and will also have failover enabled (See the
discussion in the section called “DirectChannel” for more detail). To disable one or both of these, add
a  sub-element and configure the attributes:







Datatype Channel Configuration
There are times when a consumer can only process a particular type of payload and you need to
therefore ensure the payload type of input Messages. Of course the first thing that comes to mind is
Message Filter. However all that Message Filter will 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/conversion
to the required data-type. This of course would work, but a simpler way of accomplishing 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 only accepts messages containing a certain payload type, provide
the fully-qualified class name in the channel element’s datatype attribute:


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


So the numberChannel above will only accept 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, but if you do have an

4.3.6.RELEASE

Spring Integration

31

Spring Integration Reference Manual

"integrationConversionService" bean defined, it will be used in an attempt to convert the Message’s
payload to the acceptable type.
You can even register custom converters. For example, let’s say you are sending a Message with a
String payload to the numberChannel we configured above.
MessageChannel inChannel = context.getBean("numberChannel", MessageChannel.class);
inChannel.send(new GenericMessage("5"));

Typically this would be a perfectly legal operation, however since we are using Datatype Channel the
result of such operation would generate an exception:
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]
…

And rightfully so since we are requiring the payload type to be a Number while sending a String. So we
need something to convert String to a Number. All we need to do is implement a Converter.
public static class StringToIntegerConverter implements Converter {
public Integer convert(String source) {
return Integer.parseInt(source);
}
}

Then, register it as a Converter with the Integration Conversion Service:



When the converter element is parsed, it will create the "integrationConversionService" bean on-demand
if one is not already defined. With that Converter in place, the send operation would now be successful
since the Datatype Channel will use that Converter to convert the String payload to an Integer.
Note
For more information regarding Payload Type Conversion, please read 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, which provides the converter with access to the message headers (for
example if the conversion might need information from the headers, such as content-type). The
method can return just 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,
declare
a

of
type
MessageConverter
with
an
id
"datatypeChannelMessageConverter" and that converter will be used by all channels with a
datatype.
QueueChannel Configuration
To create a QueueChannel, use the  sub-element. You may specify the channel’s capacity:

4.3.6.RELEASE

Spring Integration

32

Spring Integration Reference Manual





Note
If you do not provide a value for the capacity attribute on this  sub-element, the resulting
queue will be unbounded. To avoid issues such as OutOfMemoryErrors, it is highly recommended
to 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 9.4, “Message Store”.
Important
The capacity attribute is not allowed when the message-store attribute is used.
When a QueueChannel receives a Message, it will add it to the Message Store, and 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 and can therefore lead to the
lost message scenario mentioned above. 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 shown in the next example.








The Spring Integration JDBC module also provides schema DDL for a number of popular databases.
These schemas are located in the org.springframework.integration.jdbc.store.channel package of that
module (spring-integration-jdbc).
Important
One important feature is that with any transactional persistent store (e.g.,
JdbcChannelMessageStore), as long as the poller has a transaction configured, a Message
removed from the store will only be permanently removed if the transaction completes
successfully, otherwise the transaction will roll back and the Message will not be lost.
Many other implementations of the Message Store will be available as the growing number of Spring
projects related to "NoSQL" data stores provide the underlying support. Of course, you can always

4.3.6.RELEASE

Spring Integration

33

Spring Integration Reference Manual

provide your own implementation of the MessageGroupStore interface if you cannot find one that meets
your particular needs.
Since version 4.0, it is recommended that QueueChannel s are configured to use a
ChannelMessageStore if possible. These are generally optimized for this use, when compared with
a general message store. If the ChannelMessageStore is a ChannelPriorityMessageStore the
messages will be received in FIFO within priority order. The notion of priority is determined by the
message store implementation. For example 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 QueueChannel(new MessageGroupQueue(mongoDbChannelMessageStore, "priorityQueue"));
}

Note
Pay attention to the MessageGroupQueue class. That is a BlockingQueue implementation to
utilize the MessageGroupStore operations.
The same with Java DSL may look like:
@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. This attribute implies the reference to any
java.util.Queue implementation. An implementation is provided by the Project Reactor and its
reactor.queue.PersistentQueue implementation for the IndexedChronicle:
@Bean
public QueueChannel reactorQueue() {
return new QueueChannel(new PersistentQueueSpec>()
.codec(new JavaSerializationCodec>())
.basePath(System.getProperty("java.io.tmpdir") + "/reactor-queue")
.get());
}

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 simply publishes in the sender’s thread):


If you are providing a Resequencer or Aggregator downstream from a PublishSubscribeChannel,
then you can set the apply-sequence property on the channel to true. That will indicate that the channel

4.3.6.RELEASE

Spring Integration

34

Spring Integration Reference Manual

should set the sequence-size and sequence-number Message headers as well as the correlation id prior
to passing the Messages along. For example, if there are 5 subscribers, the sequence-size would be
set to 5, and the Messages would have sequence-number header values ranging from 1 to 5.


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, the channel creates new Message
instances with the same payload reference but different header values when the flag is set to
true.
ExecutorChannel
To create an ExecutorChannel, add the  sub-element along with a task-executor
attribute. Its value can reference any TaskExecutor within the context. For example, this enables
configuration of a thread-pool for dispatching messages to subscribed handlers. As mentioned above,
this does break the "single-threaded" execution context between sender and receiver so that any active
transaction context will not be shared by the invocation of the handler (i.e. the handler may throw an
Exception, but the send invocation has already returned successfully).




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




PriorityChannel Configuration
To create a PriorityChannel, use the  sub-element:




By default, the channel will consult the priority header of the message. However, a custom
Comparator reference may be provided instead. 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:




4.3.6.RELEASE

Spring Integration

35

Spring Integration Reference Manual

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 and, in this case, the namespace
parser will declare a QueueChannel instead of a PriorityChannel. Implementations of the
PriorityCapableChannelMessageStore are currently provided for Redis, JDBC and MongoDB.
See the section called “QueueChannel Configuration” and Section 9.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 above, and its queue does not accept
any capacity value since it is a 0-capacity direct handoff queue.




Scoped Channel Configuration
Any channel can be configured with a "scope" attribute.


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






In general, it is a good idea to define 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.
Look at the example below:




or



4.3.6.RELEASE

Spring Integration

36

Spring Integration Reference Manual

Each  element allows you to define a global interceptor which will be
applied on all channels that match any patterns defined via the pattern attribute. In the above case
the global interceptor will be applied on the foo channel and all other channels that begin with bar or
input. The order attribute allows you to manage where this interceptor will be injected if there are multiple
interceptors on a given channel. For example, channel inputChannel could have individual interceptors
configured locally (see below):






A reasonable question is how will a global interceptor be injected in relation to other interceptors
configured locally or through other global interceptor definitions? The current implementation provides a
very simple mechanism for defining the order of interceptor execution. A positive number in the order
attribute will ensure interceptor injection after any existing interceptors and a negative number will ensure
that the interceptor is injected before existing interceptors. This means that in the above example, the
global interceptor will be 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 the order attribute. 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).
Wire Tap
As mentioned above, Spring Integration provides a simple Wire Tap interceptor out of the box. You can
configure a Wire Tap on any channel within an  element. This 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 payload and/or headers variables. Alternatively, to simply log the full
Message toString() result, provide a value of "true" for the log-full-message attribute. That is
false by default so that only the payload is logged. Setting that to true enables logging of
all headers in addition to the payload. The expression option does provide the most flexibility,
however (e.g. expression="payload.user.name").
A little more on Wire Tap
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. Wire-tap as

4.3.6.RELEASE

Spring Integration

37

Spring Integration Reference Manual

a component is not invoked asynchronously be default. Instead, Spring Integration focuses on a single
unified approach to configuring asynchronous behavior: the Message Channel. What makes certain
parts of the message flow sync or async 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 3 tasks:
• intercept a message flow by tapping into a channel (e.g., channelA)
• grab each message
• send the message to another channel (e.g., channelB)
It is essentially a variation of the Bridge, 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 simply depends on the type of
Message Channel that channelB is. And, now you know that we have: Direct Channel, Pollable Channel,
and Executor Channel as options. The last two do break the thread boundary making communication
via such channels asynchronous simply 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 sync or async. It is consistent with other
components within the framework (e.g., Message Publisher) and actually brings a level of consistency
and simplicity by sparing you from worrying in advance (other than writing thread safe code) whether
a particular piece of code should be implemented as sync or async. The actual wiring of two pieces of
code (component A and component B) via Message Channel is what makes their collaboration sync or
async. You may even want to change from sync to async in the future and Message Channel is what’s
going to allow 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 async
by default, one should keep in mind 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. Nonetheless, another reason that we do not enforce asynchronous behavior by default is that
you might not want to break a transactional boundary. Perhaps you are using the Wire Tap 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-andforget" 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 WireTap) references a channel itself. 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 will ask the
interceptor if it’s OK to intercept each channel that is a candidate based on the pattern. You can
also add runtime protection in the interceptor methods that ensures that the channel is not one
that is referenced by the interceptor. The WireTap uses both of these techniques.

4.3.6.RELEASE

Spring Integration

38

Spring Integration Reference Manual

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.
This late-binding approach also allows simplification of typical wire-tapping patterns with Java DSL
configuration:
@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, 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 will be 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”. Simply 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 with the channel-interceptor


Tip
A global wire tap provides a convenient way to configure a single channel wire tap externally
without modifying the existing channel configuration. Simply set the pattern attribute to the
target channel name. For example, This technique may be used to configure a test case to verify
messages on a channel.

Special Channels
If namespace support is enabled, there are two special channels defined within the application context
by default: errorChannel and nullChannel. The nullChannel acts like /dev/null, simply logging
any Message sent to it at DEBUG level and returning immediately. Any time you face channel
resolution errors for a reply that you don’t care about, you can set the affected component’s output-

4.3.6.RELEASE

Spring Integration

39

Spring Integration Reference Manual

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 F.4, “Error Handling”.

4.2 Poller
Polling Consumer
When Message Endpoints (Channel Adapters) are connected to channels and instantiated, they
produce one of the following 2 instances:
• PollingConsumer
• EventDrivenConsumer
The actual implementation depends on which type of channel these Endpoints are
connected to. A channel adapter connected to a channel that implements the
org.springframework.messaging.SubscribableChannel interface will produce an instance of
EventDrivenConsumer. On the other hand, a channel adapter connected to a channel that
implements the org.springframework.messaging.PollableChannel interface (e.g. a QueueChannel) will
produce an instance of PollingConsumer.
Polling Consumers allow Spring Integration components to actively poll for Messages, rather than to
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 at:
http://www.enterpriseintegrationpatterns.com/PollingConsumer.html

Pollable Message Source
Furthermore, in Spring Integration a second variation of the Polling Consumer pattern exists.
When Inbound Channel Adapters are being 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 15.4, “FTP Inbound Channel Adapter” is configured
with a poller to retrieve messages periodically. So, when components are configured with Pollers, the
resulting instances are of one of the following types:
• PollingConsumer
• SourcePollingChannelAdapter
This means, Pollers are used in both inbound and outbound messaging scenarios. Here are some usecases that illustrate the scenarios in which Pollers are used:
• Polling certain external systems such as FTP Servers, Databases, Web Services
• Polling internal (pollable) Message Channels
• Polling internal services (E.g. repeatedly execute methods on a Java class)

4.3.6.RELEASE

Spring Integration

40

Spring Integration Reference Manual

Note
AOP Advice classes can be applied to pollers, in an advice-chain. An example being
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 the message to be processed properly. To use this advice, you have to
provide it with an implementation of a PollSkipStrategy. Startng with version 4.2.5, a
SimplePollSkipStrategy is provided. 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 regarding Polling Consumers and how they
fit into the concept of message channels - Section 4.1, “Message Channels” and channel adapters
- Section 4.3, “Channel Adapter”. For more in-depth information regarding Messaging Endpoints in
general and Polling Consumers in particular, please seeSection 8.1, “Message Endpoints”.

Conditional Pollers for Message Sources
Background
Advice objects, in an advice-chain on a poller, advise the whole polling task (message retrieval
and processing). These "around advice" methods do not have access to any context for the poll, just
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 above. 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?
"Smart" Polling
Version 4.2 introduced the AbstractMessageSourceAdvice. Any Advice objects in the advicechain that subclass this class, are applied to just the receive operation. Such classes implement the
following methods:
beforeReceive(MessageSource source)

This method is called before the MessageSource.receive() method. It enables you to examine
and or reconfigure the source at this time. Returning false cancels this poll (similar to the
PollSkipAdvice mentioned above).
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!
Advice Chain Ordering
It is important to 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, say Advice objects a, b, c, d, where b and d are

4.3.6.RELEASE

Spring Integration

41

Spring Integration Reference Manual

AbstractMessageSourceAdvice, they will be applied in the order a, c, b, d. Also, if a
MessageSource is already a Proxy, the AbstractMessageSourceAdvice will be invoked
after any existing Advice objects. If you wish to change the order, you should 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
This advice modifies the trigger based on the receive() result. This will only work if the advice
is called on the poller thread. It will 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 s are immutable so 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 's nextExecutionTime method is invoked,
it will delegate to the secondary trigger, if present; otherwise the primary trigger.
The poller must also have a reference to the same CompoundTrigger.
The following shows the configuration for the hourly cron expression with fall-back to every minute…















 





4.3.6.RELEASE

Spring Integration

42

Spring Integration Reference Manual

Important: Async Handoff
This advice modifies the trigger based on the receive() result. This will only work if the advice
is called on the poller thread. It will 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.

4.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 out of the box to support
various transports, such as JMS, File, HTTP, Web Services, Mail, and more. Those will be discussed
in upcoming chapters of this reference guide. 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
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 it to a Message. When the adapter’s
subscription is activated, a poller will attempt to receive messages from the source. The poller will be
scheduled with the TaskScheduler according to the provided configuration. To configure the polling
interval or cron expression for an individual channel-adapter, provide a poller element with one of the
scheduling attributes, such as fixed-rate or cron.







Also see 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 “Namespace Support” for more detail.
Important: Poller Configuration
Some
inbound-channel-adapter
types
are
backed
by
a
SourcePollingChannelAdapter which means they contain Poller configuration which will
poll the MessageSource (invoke a custom method which produces the value that becomes a
Message payload) based on the configuration specified in the Poller.
For example:



4.3.6.RELEASE

Spring Integration

43

Spring Integration Reference Manual

In the the first configuration the polling task will be invoked once per poll and during such task
(poll) the method (which results in the production of the Message) will be invoked once based on
the max-messages-per-poll attribute value. In the second configuration the polling task will
be invoked 10 times per poll or until it returns null thus possibly producing 10 Messages per poll
while each poll happens at 1 second intervals. However what if the configuration looks like this:


Note there is no max-messages-per-poll specified. As you’ll learn later the identical poller
configuration in the PollingConsumer (e.g., service-activator, filter, router etc.) would have a
default value of -1 for max-messages-per-poll which means "execute poling task non-stop
unless polling method returns null (e.g., no more Messages in the QueueChannel)" and then sleep
for 1 second.
However in the SourcePollingChannelAdapter it is a bit different. The default value for maxmessages-per-poll will be set to 1 by default unless you explicitly set it to a negative value
(e.g., -1). It is done so to make sure that poller can react to a LifeCycle events (e.g., start/stop) and
prevent it from potentially spinning in the infinite loop if the implementation of the custom method
of the MessageSource has a potential to never return null and happened to be non-interruptible.
However if you are sure that your method can return null and you need the behavior where you
want to poll for as many sources as available per each poll, then you should explicitly set maxmessages-per-poll to a negative value.


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.



If the channel being adapted is a PollableChannel, provide a poller sub-element:





Using a "ref" attribute is generally recommended if the POJO consumer implementation can be reused
in other  definitions. However if the consumer implementation is only
referenced by a single definition of the , you can define it as inner
bean:




4.3.6.RELEASE

Spring Integration

44

Spring Integration Reference Manual

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
will result in an Exception being thrown.
Any Channel Adapter can be created without a "channel" reference in which case it will implicitly
create an instance of DirectChannel. The created channel’s name will match the "id" attribute of
the  or  element. Therefore, if the
"channel" is not provided, the "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 via 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 
will generate a message anytime 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 



Navigation menu