<?xml version="1.0" encoding="UTF-8"?>
<appendix xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="configuration"
    xmlns:xlink="http://www.w3.org/1999/xlink">
  <title>Configuration</title>
  <section id="configuration-introduction">
    <title>Introduction</title>
    <para>
      Spring Integration offers a number of configuration options. Which option you choose depends upon your particular
      needs and at what level you prefer to work. As with the Spring framework in general, it is also possible to mix
      and match the various techniques according to the particular problem at hand. For example, you may choose the
      XSD-based namespace for the majority of configuration combined with a handful of objects that are configured with
      annotations. As much as possible, the two provide consistent naming. XML elements defined by the XSD schema will
      match the names of annotations, and the attributes of those XML elements will match the names of annotation
      properties. Direct usage of the API is of course always an option, but we expect that most users will choose one
      of the higher-level options, or a combination of the namespace-based and annotation-driven configuration.
    </para>
  </section>

  <section id="configuration-namespace">
    <title>Namespace Support</title>
    <para>
      Spring Integration components can be configured with XML elements that map directly to the terminology and
      concepts of enterprise integration. In many cases, the element names match those of the
      <ulink url="http://www.eaipatterns.com">Enterprise Integration Patterns</ulink>.
    </para>
    <para>
      To enable Spring Integration's core namespace support within your Spring configuration files, add the following
      namespace reference and schema mapping in your top-level 'beans' element:
      <programlisting language="xml"><![CDATA[<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       ]]><emphasis>xmlns:int="http://www.springframework.org/schema/integration"</emphasis><![CDATA[
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           ]]><emphasis>http://www.springframework.org/schema/integration
           http://www.springframework.org/schema/integration/spring-integration.xsd"</emphasis>&gt;</programlisting>
    </para>
    <para>
      You can choose any name after "xmlns:"; <emphasis>int</emphasis> is used here for clarity, but you might
      prefer a shorter abbreviation. Of course if you are using an XML-editor or IDE support, then the availability of
      auto-completion may convince you to keep the longer name for clarity. Alternatively, you can create configuration
      files that use the Spring Integration schema as the primary namespace:
      <programlisting language="xml"><emphasis>&lt;beans:beans xmlns="http://www.springframework.org/schema/integration"</emphasis><![CDATA[
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       ]]><emphasis>xmlns:beans="http://www.springframework.org/schema/beans"</emphasis><![CDATA[
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/integration
           http://www.springframework.org/schema/integration/spring-integration.xsd">]]></programlisting>
    </para>
    <para>
      When using this alternative, no prefix is necessary for the Spring Integration elements. On the other hand, if
      you want to define a generic Spring "bean" within the same configuration file, then a prefix would be required
      for the bean element (&lt;beans:bean ... /&gt;). Since it is generally a good idea to modularize the
      configuration files themselves based on responsibility and/or architectural layer, you may find it appropriate to
      use the latter approach in the integration-focused configuration files, since generic beans are seldom necessary
      within those same files. For purposes of this documentation, we will assume the "integration" namespace is
      primary.
    </para>
    <para>
      Many other namespaces are provided within the Spring Integration distribution. In fact, each adapter type (JMS,
      File, etc.) that provides namespace support defines its elements within a separate schema. In order to use these
      elements, simply add the necessary namespaces with an "xmlns" entry and the corresponding "schemaLocation" mapping.
      For example, the following root element shows several of these namespace declarations:
      <programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:int="http://www.springframework.org/schema/integration"
    xmlns:int-file="http://www.springframework.org/schema/integration/file"
    xmlns:int-jms="http://www.springframework.org/schema/integration/jms"
    xmlns:int-mail="http://www.springframework.org/schema/integration/mail"
    xmlns:int-rmi="http://www.springframework.org/schema/integration/rmi"
    xmlns:int-ws="http://www.springframework.org/schema/integration/ws"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/integration
            http://www.springframework.org/schema/integration/spring-integration.xsd
            http://www.springframework.org/schema/integration/file
            http://www.springframework.org/schema/integration/file/spring-integration-file.xsd
            http://www.springframework.org/schema/integration/jms
            http://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd
            http://www.springframework.org/schema/integration/mail
            http://www.springframework.org/schema/integration/mail/spring-integration-mail.xsd
            http://www.springframework.org/schema/integration/rmi
            http://www.springframework.org/schema/integration/rmi/spring-integration-rmi.xsd
            http://www.springframework.org/schema/integration/ws
            http://www.springframework.org/schema/integration/ws/spring-integration-ws.xsd">
 ...
</beans>]]></programlisting>
      The reference manual provides specific examples of the various elements in their corresponding chapters. Here, the
      main thing to recognize is the consistency of the naming for each namespace URI and schema location.
    </para>
  </section>

  <section id="namespace-taskscheduler">
    <title>Configuring the Task Scheduler</title>
    <para>
   
      In Spring Integration, the ApplicationContext plays the central role of a Message Bus, and there are only a
      couple configuration options to consider. First, you may want to control the central TaskScheduler instance.
      You can do so by providing a single bean with the name "taskScheduler". This is also defined as a constant:
      <programlisting><![CDATA[ IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME ]]></programlisting>
      By default Spring Integration relies on an instance of ThreadPoolTaskScheduler as described in the <ulink url="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html">Task Execution and Scheduling</ulink>
      section of the Spring Framework reference manual. That default TaskScheduler will startup automatically with a
      pool of 10 threads. If you provide your own TaskScheduler instance instead, you can set the 'autoStartup' property
      to <emphasis>false</emphasis>, and/or you can provide your own pool size value.
    </para>
    <para>
      When Polling Consumers provide an explicit task-executor reference in their configuration, the invocation of
      the handler methods will happen within that executor's thread pool and not the main scheduler pool. However,
      when no task-executor is provided for an endpoint's poller, it will be invoked by one of the main scheduler's
      threads.
      <note>
         An endpoint is a <emphasis>Polling Consumer</emphasis> if its input channel is one of the queue-based
         (i.e. pollable) channels. On the other hand, <emphasis>Event Driven Consumers</emphasis> are those whose
         input channels have dispatchers instead of queues (i.e. they are subscribable). Such endpoints have no
         poller configuration since their handlers will be invoked directly.
      </note>
      <para>
        The next section will describe what happens if Exceptions occur within the asynchronous invocations.
      </para>
    </para>
  </section>

  <section id="namespace-errorhandler">
    <title>Error Handling</title>
    <para>
      As described in the overview at the very beginning of this manual, one of the main motivations behind a
      Message-oriented framework like Spring Integration is to promote loose-coupling between components. The
      Message Channel plays an important role in that producers and consumers do not have to know about each
      other. However, the advantages also have some drawbacks. Some things become more complicated in a very
      loosely coupled environment, and one example is error handling.
    </para>
    <para>
      When sending a Message to a channel, the component that ultimately handles that Message may or may not
      be operating within the same thread as the sender. If using a simple default DirectChannel (with the
      &lt;channel&gt; element that has no &lt;queue&gt; sub-element and no 'task-executor' attribute), the
      Message-handling will occur in the same thread as the Message-sending. In that case, if an Exception
      is thrown, it can be caught by the sender (or it may propagate past the sender if it is an uncaught
      RuntimeException). So far, everything is fine. This is the same behavior as an Exception-throwing
      operation in a normal call stack. However, when adding the asynchronous aspect, things become much
      more complicated. For instance, if the 'channel' element <emphasis>does</emphasis> provide a 'queue'
      sub-element, then the component that handles the Message <emphasis>will</emphasis> be operating in a
      different thread than the sender. The sender may have dropped the Message into the channel and moved
      on to other things. There is no way for the Exception to be thrown directly back to that sender using
      standard Exception throwing techniques. Instead, to handle errors for asynchronous processes requires
      an asynchronous error-handling mechanism as well.
    </para>
    <para>
      Spring Integration supports error handling for its components by publishing errors to a Message Channel.
      Specifically, the Exception will become the payload of a Spring Integration Message. That Message will
      then be sent to a Message Channel that is resolved in a way that is similar to the 'replyChannel'
      resolution. First, if the request Message being handled at the time the Exception occurred contains
      an 'errorChannel' header (the header name is defined in the constant: MessageHeaders.ERROR_CHANNEL),
      the ErrorMessage will be sent to that channel. Otherwise, the error handler will send to a "global"
      channel whose bean name is "errorChannel" (this is also defined as a constant:
      IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME).
    </para>
    <para>
      Whenever relying on Spring Integration's XML namespace support, a default "errorChannel" bean will be
      created behind the scenes. However, you can just as easily define your own if you want to control the
      settings.
      <programlisting language="xml"><![CDATA[ <int:channel id="errorChannel">
     <int:queue capacity="500"/>
 </int:channel>]]></programlisting>
      <note>
        The default "errorChannel" is a PublishSubscribeChannel.
      </note>
    </para>
    <para>
      The most important thing to understand here is that the messaging-based error handling will only apply
      to Exceptions that are thrown by a Spring Integration task that is executing within a TaskExecutor.
      This does <emphasis>not</emphasis> apply to Exceptions thrown by a handler that is operating within
      the same thread as the sender (e.g. through a DirectChannel as described above).
    </para>
    <note>
      When Exceptions occur in a scheduled poller task's execution, those exceptions will be wrapped in
      <classname>ErrorMessages</classname> and sent to the 'errorChannel' as well.
    </note>
    <para>
      To enable global error handling, simply register a handler on that channel. For example, you can configure
      Spring Integration's <classname>ErrorMessageExceptionTypeRouter</classname> as the handler of an endpoint
      that is subscribed to the 'errorChannel'. That router can then spread the error messages across multiple
      channels based on <classname>Exception</classname> type.
    </para>
  </section>

  <section id="annotations">
    <title>Annotation Support</title>
    <para>
      In addition to the XML namespace support for configuring Message Endpoints, 
      it is also possible to use annotations. First, Spring Integration provides 
      the class-level <interfacename>@MessageEndpoint</interfacename> as a 
      <emphasis>stereotype</emphasis> annotation, meaning that it is itself 
      annotated with Spring's <interfacename>@Component</interfacename> annotation 
      and is therefore recognized automatically as a bean definition when using 
      Spring component-scanning.
    </para>
    <para>
      Even more important are the various method-level annotations that indicate 
      the annotated method is capable of handling a message. The following example 
      demonstrates both:
      <programlisting language="java">@MessageEndpoint
public class FooService {

    @ServiceActivator
    public void processMessage(Message message) {
        ...
    }
}</programlisting>
    </para>
    <para>
      Exactly what it means for the method to "handle" the Message depends on the 
      particular annotation. The following annotations are available in Spring Integration: 
      <itemizedlist>
        <listitem>@Aggregator</listitem>
        <listitem>@ChannelAdapter</listitem>
        <listitem>@Filter</listitem>
		<listitem>@Router</listitem>
		<listitem>@ServiceActivator</listitem>
		<listitem>@Splitter</listitem>
		<listitem>@Transformer</listitem>
      </itemizedlist>
    </para>
    <para>The behavior of each is described in its own chapter or section within
      this reference.</para>
    <note>
      If you are using XML configuration in combination with annotations, the 
      <interfacename>@MessageEndpoint</interfacename> annotation is not required. 
      If you want to configure a POJO reference from  the "ref" attribute of a 
      &lt;service-activator/&gt; element, it is  sufficient to provide the 
      method-level annotations. In that case, the annotation prevents ambiguity 
      even when no "method" attribute exists on the &lt;service-activator/&gt; element.
    </note>
    <para>
      In most cases, the annotated handler method should not require the 
      <classname>Message</classname> type as its parameter. Instead, the method 
      parameter type can match the message's payload type.
      <programlisting language="java">public class FooService {

    @ServiceActivator
    public void bar(<emphasis>Foo foo</emphasis>) {
        ...
    }

}</programlisting>
    </para>
    <para>
      When the method parameter should be mapped from a value in the <classname>MessageHeaders</classname>, another
      option is to use the parameter-level <interfacename>@Header</interfacename> annotation. In general, methods
      annotated with the Spring Integration annotations can either accept the <classname>Message</classname> itself, the
      message payload, or a header value (with @Header) as the parameter. In fact, the method can accept a combination,
      such as:
      <programlisting language="java">public class FooService {

    @ServiceActivator
    public void bar(String payload, @Header("x") int valueX, @Header("y") int valueY) {
        ...
    }

}</programlisting>
      There is also a @Headers annotation that provides all of the Message headers as a Map:
      <programlisting language="java">public class FooService {

    @ServiceActivator
    public void bar(String payload, @Headers Map&lt;String, Object&gt; headerMap) {
        ...
    }

}</programlisting>
    </para>
    <para>
    <note>
    The value of the annotation can also be a SpEL expression (e.g., 'payload.getCustomerId()') which is quite useful when
    the name of the header has to be dynamically computed. It also provides an optional 'required' property which
    specifies whether the attribute value must be available within the header. The default value for 'required' is <code>true</code>.
    </note>
    </para>
    <para>
      For several of these annotations, when a Message-handling method returns a non-null value, the endpoint will
      attempt to send a reply. This is consistent across both configuration options (namespace and annotations) in
      that such an endpoint's output channel will be used if available, and the REPLY_CHANNEL message header value
      will be used as a fallback.
    </para>
    <tip>
      The combination of output channels on endpoints and the reply channel message header enables a pipeline approach
      where multiple components have an output channel, and the final component simply allows the reply message to be
      forwarded to the reply channel as specified in the original request message. In other words, the final component
      depends on the information provided by the original sender and can dynamically support any number of clients as a
      result. This is an example of <ulink url="http://eaipatterns.com/ReturnAddress.html">Return Address</ulink>.
  </tip>
    <para>
      In addition to the examples shown here, these annotations also support inputChannel and outputChannel properties.
      <programlisting language="java">public class FooService {

    @ServiceActivator(inputChannel="input", outputChannel="output")
    public void bar(String payload, @Headers Map&lt;String, Object&gt; headerMap) {
        ...
    }

}</programlisting>
      That provides a pure annotation-driven alternative to the XML configuration. However, it is generally recommended
      to use XML for the endpoints, since it is easier to keep track of the overall configuration in a single, external
      location (and besides the namespace-based XML configuration is not very verbose). If you do prefer to provide
      channels with the annotations however, you just need to enable a SI Annotations BeanPostProcessor. The following element should
      be added: <programlisting language="xml"><![CDATA[ <int:annotation-config/> ]]></programlisting>
      <note>
        When configuring the "inputChannel" and "outputChannel" with annotations, the "inputChannel"
        <emphasis>must</emphasis> be a reference to a <interfacename>SubscribableChannel</interfacename> instance.
        Otherwise, it would be necessary to also provide the full poller configuration via annotations, and those
        settings (e.g. the trigger for scheduling the poller) should be externalized rather than hard-coded within
        an annotation. If the input channel that you want to receive Messages from is indeed a
        <interfacename>PollableChannel</interfacename> instance, one option to consider is the Messaging Bridge.
        Spring Integration's "bridge" element can be used to connect a PollableChannel directly to a
        SubscribableChannel. Then, the polling metadata is externally configured, but the annotation option is
        still available. For more detail see <xref linkend="bridge"/>.
      </note>
    </para>
  </section>

  <section id="message-mapping-rules">
    <title>Message Mapping rules and conventions</title>
    <para>Spring Integration implements a flexible facility to map Messages to Methods and their arguments without
    providing extra configuration by relying on some default rules as well as defining certain conventions.
  </para>
  <section id="sample-scenarios">
      <title>Simple Scenarios</title>

      <para>
      <emphasis>Single un-annotated parameter (object or primitive) which is not a Map/Properties with non-void return type;</emphasis>
      </para>
      <programlisting language="java">public String foo(Object o);</programlisting>
      <para>Details:</para>
      <para>Input parameter is Message Payload. If parameter type is not compatible with Message Payload an
      attempt will be made to convert it using Conversion Service provided by Spring 3.0. The return value
      will be incorporated as a Payload of the returned Message</para>

      <para>
      <emphasis>Single un-annotated parameter (object or primitive) which is not a Map/Properties with Message return type;</emphasis>
      </para>
      <programlisting language="java">public Message  foo(Object o);</programlisting>
      <para>Details:</para>
      <para>Input parameter is Message Payload. If parameter type is not compatible with Message Payload an attempt
      will be made to convert it using Conversion Service provided by Spring 3.0. The return value is a newly constructed
      Message that will be sent to the next destination.</para>

      <para>
      <emphasis>Single parameter which is a Message or its subclass with arbitrary object/primitive return type;  </emphasis>
      </para>
      <programlisting language="java">public int foo(Message  msg);</programlisting>
      <para>Details:</para>
      <para>Input parameter is Message itself. The return value will become a payload of the
      Message that will be sent to the next destination.</para>

      <para>
      <emphasis>Single parameter which is a Message or its subclass with Message or its subclass as a return type;</emphasis>
      </para>
      <programlisting language="java">public Message foo(Message msg);</programlisting>
      <para>Details:</para>
      <para>Input parameter is Message itself. The return value is a newly constructed Message that will be sent to the next destination.</para>

      <para>
      <emphasis>Single parameter which is of type Map or Properties with Message as a return type;</emphasis>
      </para>
      <programlisting language="java">public Message foo(Map m);</programlisting>
      <para>Details:</para>
      <para>This one is a bit interesting. Although at first it might seem like an easy mapping straight to Message Headers,
      the preference is always given to a Message Payload. This means that if Message Payload is of type Map, this input argument will
      represent Message Payload. However if Message Payload is not of type Map, then no conversion via Conversion Service will be
      attempted and the input argument will be mapped to Message Headers.</para>

      <para>
      <emphasis>Two parameters where one of them is arbitrary non-Map/Properties type object/primitive and another is Map/Properties type object (regardless of the return)</emphasis>
      </para>
      <programlisting language="java">public Message foo(Map h, &lt;T&gt; t);</programlisting>
      <para>Details:</para>
      <para>This combination contains two input parameters where one of them is of type Map. Naturally the non-Map parameters (regardless of the order) will
      be mapped to a Message Payload and the Map/Properties (regardless of the order) will be mapped to  Message Headers giving you a nice POJO way
      of interacting with Message structure.</para>

      <para>
      <emphasis>No parameters (regardless of the return)</emphasis>
      </para>
      <programlisting language="java">public String foo();</programlisting>
      <para>Details:</para>
      <para>This Message Handler method will be invoked based on the Message sent to the input channel this handler is hooked up to,
      however no Message data will be mapped, thus making Message act as event/trigger to invoke such handlerThe output will be
      mapped according to the rules above</para>

      <para>
      <emphasis>No parameters, void return</emphasis>
      </para>
      <programlisting language="java">public void foo();</programlisting>
      <para>Details:</para>
      <para>Same as above, but no output </para>

      <para>
      <emphasis>Annotation based mappings</emphasis>
      </para>
      <para>Annotation based mapping is the safest and least ambiguous approach to map Messages to Methods. There wil be many pointers to annotation
      based mapping throughout this manual, however here are couple of examples:
      </para>

      <programlisting language="java">public String foo(@Payload String s, @Header("foo") String b) </programlisting>
      <para>Very simple and explicit way of mapping Messages to method. As you'll see later on, without an annotation this signature
      would result in an ambiguous condition. However by explicitly mapping the first argument to a Message Payload and the second argument to
      a value of the 'foo' Message Header, we have avoided any ambiguity.</para>

      <programlisting language="java">public String foo(@Payload String s, @RequestParam("foo") String b) </programlisting>
      <para>Looks almost identical to the previous example, however @RequestMapping or any other non-Spring Integration mapping annotation
      is irrelevant and therefore will be ignored leaving the second parameter unmapped. Although the second parameter could
      easily be mapped to a Payload, there can only be one Payload. Therefore this method mapping is ambiguous.</para>

      <programlisting language="java">public String foo(String s, @Header("foo") String b) </programlisting>
      <para>The same as above. The only difference is that the first argument will be mapped to the Message Payload implicitly.</para>

      <programlisting language="java">public String foo(@Headers Map m, @Header("foo")Map f, @Header("bar") String bar)</programlisting>
      <para>Yet another signature that would definitely be treated as ambiguous without annotations because it has more than 2 arguments.
      Furthermore, two of them are Maps. However, with annotation-based mapping, the ambiguity is easily avoided. In this example
      the first argument is mapped to all the Message Headers, while the second and third argument map to the values of Message Headers
      'foo' and 'bar'. The payload is not being mapped to any argument.</para>
  </section>

  <section id="complex-scenarios">
      <title>Complex Scenarios</title>

      <para><emphasis>Multiple parameters:</emphasis> </para>
      <para>Multiple parameters could create a lot of ambiguity with regards to determining the appropriate mappings. The general advice is to annotate your method parameters with @Payload and/or @Header/@Headers
Below are some of the examples of ambiguous conditions which result in an Exception being raised.
      </para>
      <programlisting language="java">public String foo(String s, int i)</programlisting>
      <para> - the two parameters are equal in weight, therefore there is no way to determine which one is a payload.</para>

      <programlisting language="java">public String foo(String s, Map m, String b) </programlisting>
      <para> - almost the same as above. Although the Map could be easily mapped to Message Headers, there is no way to determine what to do with the two Strings.</para>

      <programlisting language="java">public String foo(Map m, Map f)</programlisting>
      <para> - although one might argue that one Map could be mapped to Message Payload and another one to Message Headers, it would be unreasonable to rely on the order (e.g., first is Payload, second Headers)</para>

      <para>
        <tip>Basically any method signature with more than one method argument which is not (Map, &lt;T&gt;), and those parameters are not annotated, will result in an ambiguous condition thus triggering an Exception.</tip>
      </para>
      <para>
      <emphasis>Multiple methods:</emphasis>
      </para>
      <para>Message Handlers with multiple methods are mapped based on the same rules that are described above, however some scenarios might still look confusing.</para>

      <para><emphasis>Multiple methods (same or different name) with legal (mappable) signatures:</emphasis> </para>

      <programlisting language="java">public class Foo {
  public String foo(String str, Map m);

  public String foo(Map m);
}</programlisting>
      <para>As you can see, the Message could be mapped to either method. The first method would be invoked where Message Payload
      could be mapped to 'str'  and Message Headers could be mapped to 'm'. The second method could easily also be a candidate where
      only Message Headers are mapped to 'm'. To make meters worse both methods have the same name which at first might look very
      ambiguous considering the following configuration:</para>
      <programlisting language="xml"><![CDATA[<int:service-activator input-channel="input" output-channel="output" method="foo">
  <bean class="org.bar.Foo"/>
</int:service-activator>]]></programlisting>
      <para>At this point it would be important to understand Spring Integration mapping Conventions where at the very core,
      mappings are based on Payload first and everything else next. In other words the method whose argument could be mapped
      to a Payload will take precedence over all other methods.</para>

      <para>On the other hand let's look at slightly different example:</para>
      <programlisting language="java">public class Foo {
  public String foo(String str, Map m);

  public String foo(String str);
}</programlisting>

      <para>If you look at it you can probably see a truly ambiguous condition. In this example since both methods have signatures that
      could be mapped to a Message Payload. They also have the same name. Such handler methods will trigger an Exception.
However if the method names were different you could influence the mapping with a 'method' attribute (see below):</para>
      <programlisting language="java">public class Foo {
  public String foo(String str, Map m);

  public String bar(String str);
}</programlisting>
      <programlisting language="xml"><![CDATA[<int:service-activator input-channel="input" output-channel="output" method="bar">
  <bean class="org.bar.Foo"/>
</int:service-activator>]]></programlisting>

      <para>Now there is no ambiguity since the configuration explicitly maps to the 'bar' method which has no name conflicts.</para>
  </section>
  </section>

</appendix>
