Transformer
Introduction Message Transformers play a very important role in enabling the loose-coupling of Message Producers and Message Consumers. Rather than requiring every Message-producing component to know what type is expected by the next consumer, Transformers can be added between those components. Generic transformers, such as one that converts a String to an XML Document, are also highly reusable. For some systems, it may be best to provide a Canonical Data Model, but Spring Integration's general philosophy is not to require any particular format. Rather, for maximum flexibility, Spring Integration aims to provide the simplest possible model for extension. As with the other endpoint types, the use of declarative configuration in XML and/or Annotations enables simple POJOs to be adapted for the role of Message Transformers. These configuration options will be described below. For the same reason of maximizing flexibility, Spring does not require XML-based Message payloads. Nevertheless, the framework does provide some convenient Transformers for dealing with XML-based payloads if that is indeed the right choice for your application. For more information on those transformers, see .
Configuring Transformer
Configuring Transformer with XML The <transformer> element is used to create a Message-transforming endpoint. In addition to "input-channel" and "output-channel" attributes, it requires a "ref". The "ref" may either point to an Object that contains the @Transformer annotation on a single method (see below) or it may be combined with an explicit method name value provided via the "method" attribute. ]]> Using a "ref" attribute is generally recommended if the custom transformer handler implementation can be reused in other <transformer> definitions. However if the custom transformer handler implementation should be scoped to a single definition of the <transformer>, you can define an inner bean definition: ]]> Using both the "ref" attribute and an inner handler definition in the same <transformer> configuration is not allowed, as it creates an ambiguous condition and will result in an Exception being thrown. The method that is used for transformation may expect either the Message type or the payload type of inbound Messages. It may also accept Message header values either individually or as a full map by using the @Header and @Headers parameter annotations respectively. The return value of the method can be any type. If the return value is itself a Message, that will be passed along to the transformer's output channel. As of Spring Integration 2.0, a Message Transformer's transformation method can no longer return null. Returning null will result in an exception since a Message Transformer should always be expected to transform each source Message into a valid target Message. In other words, a Message Transformer should not be used as a Message Filter since there is a dedicated <filter> option for that. However, if you do need this type of behavior (where a component might return NULL and that should not be considered an error), a service-activator could be used. Its requires-reply value is FALSE by default, but that can be set to TRUE in order to have Exceptions thrown for NULL return values as with the transformer. Transformers and Spring Expression Language (SpEL) Just like Routers, Aggregators and other components, as of Spring Integration 2.0 Transformers can also benefit from SpEL support (http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/expressions.html) whenever transformation logic is relatively simple. ]]> In the above configuration we are achieving a simple transformation of the payload with a simple SpEL expression and without writing a custom transformer. Our payload (assuming String) will be upper-cased and concatenated with the current timestamp with some simple formatting. Common Transformers There are also a few Transformer implementations available out of the box. Because, it is fairly common to use the toString() representation of an Object, Spring Integration provides an ObjectToStringTransformer whose output is a Message with a String payload. That String is the result of invoking the toString() operation on the inbound Message's payload. ]]> A potential example for this would be sending some arbitrary object to the 'outbound-channel-adapter' in the file namespace. Whereas that Channel Adapter only supports String, byte-array, or java.io.File payloads by default, adding this transformer immediately before the adapter will handle the necessary conversion. Of course, that works fine as long as the result of the toString() call is what you want to be written to the File. Otherwise, you can just provide a custom POJO-based Transformer via the generic 'transformer' element shown previously. When debugging, this transformer is not typically necessary since the 'logging-channel-adapter' is capable of logging the Message payload. Refer to for more detail. The object-to-string-transformer is very simple; it invokes toString() on the inbound payload. There are two exceptions to this (since 3.0): if the payload is a char[], it invokes new String(payload); if the payload is a byte[], it invokes new String(payload, charset), where charset is "UTF-8" by default. The charset can be modified by supplying the charset attribute on the transformer. For more sophistication (such as selection of the charset dynamically, at runtime), you can use a SpEL expression-based transformer instead; for example: ]]> If you need to serialize an Object to a byte array or deserialize a byte array back into an Object, Spring Integration provides symmetrical serialization transformers. These will use standard Java serialization by default, but you can provide an implementation of Spring 3.0's Serializer or Deserializer strategies via the 'serializer' and 'deserializer' attributes, respectively. ]]> Object-to-Map Transformer Spring Integration also provides Object-to-Map and Map-to-Object transformers which utilize the Spring Expression Language (SpEL) to serialize and de-serialize the object graphs. The object hierarchy is introspected to the most primitive types (String, int, etc.). The path to this type is described via SpEL, which becomes the key in the transformed Map. The primitive type becomes the value. For example: nickNames;    // setters and getters are omitted }]]> ... will be transformed to a Map which looks like this: {person.name=George, person.child.name=Jenna, person.child.nickNames[0]=Bimbo . . . etc} The SpEL-based Map allows you to describe the object structure without sharing the actual types allowing you to restore/rebuild the object graph into a differently typed Object graph as long as you maintain the structure. For example: The above structure could be easily restored back to the following Object graph via the Map-to-Object transformer: nickNames;    // setters and getters are omitted }]]> To configure these transformers, Spring Integration provides namespace support Object-to-Map: ]]> Map-to-Object ]]> or ]]> NOTE: 'ref' and 'type' attributes are mutually exclusive. You can only use one. Also, if using the 'ref' attribute, you must point to a 'prototype' scoped bean, otherwise a BeanCreationException will be thrown.  JSON Transformers Object to JSON and JSON to Object transformers are provided. ]]> ]]> These use a vanilla Jackson ObjectMapper by default. If you wish to customize the ObjectMapper (for example, to configure the 'ALLOW_COMMENTS' feature when parsing JSON), you can supply a reference to your custom ObjectMapper bean using the object-mapper attribute. ]]> Beginning with version 3.0, the object-mapper attribute references an instance of a new strategy interface JsonObjectMapper. This abstraction allows multiple implementations of json mappers to be used. Implementations that wrap Jackson 1.x and Jackson 2 are provided, with the version being detected on the classpath. These classes are JacksonJsonObjectMapper and Jackson2JsonObjectMapper. For backward compatibility, a simple Jackson 1.x ObjectMapper can be provided instead of a JsonObjectMapper. This will be removed in a future release. You may wish to consider using a FactoryBean or simple factory method to create the JsonObjectMapper with the required characteristics. ]]> Beginning with version 2.2, the object-to-json-transformer sets the content-type header to application/json, by default, if the input message does not already have that header present. It you wish to set the content type header to some other value, or explicitly overwrite any existing header with some value (including application/json), use the content-type attribute. If you wish to suppress the setting of the header, set the content-type attribute to an empty string (""). This will result in a message with no content-type header, unless such a header was present on the input message. The behavior of adding the default header has a side affect - causing applications with the following sequence to fail: ->object-to-json-transformer->amqp-outbound-adapter----> ---->amqp-inbound-adapter->json-to-object-transformer-> This is because the default SimpleMessageConverter used by the inbound adapter doesn't recognize this content type and the adapter emits a message with a byte[] payload instead of String, which was the case with earlier versions. If you are using this pattern, there are a number of ways to configure the environment so that JSON conversion will be performed correctly. One solution is to set the content type to a text type, so the inbound converter will convert the JSON to String. This solution requires a change to just the outbound application. ]]> The second solution is to eliminate the json transformers altogether and use an org.springframework.amqp.support.converter.JsonMessageConverter on both the outbound and inbound adapters. This configures the adapters to perform the JSON conversion and the transformers are not necessary. The converter on the outbound adapter adds type information to the message properties; the inbound converter uses this type information for the conversion. The converter is provided to the adapters using the message-converter attribute. This solution requires a change to both the inbound and outbound applications. The third solution is to eliminate the json-to-object-transformer in just the inbound application and use an org.springframework.amqp.support.converter.JsonMessageConverter on the inbound adapter. The converter is provided to the adapter using the message-converter attribute. However, because there will be no type information in the message properties, this also requires adding the defaultType to the converter, using the same type as currently configured on the json-to-object-transformer. This solution requires a change to just the inbound application. The configuration below shows how to configure the message converter; it requires spring-amqp 1.1.3 or above. ]]>
Configuring a Transformer with Annotations The @Transformer annotation can also be added to methods that expect either the Message type or the message payload type. The return value will be handled in the exact same way as described above in the section describing the <transformer> element. @Transformer Order generateOrder(String productId) { return new Order(productId); } Transformer methods may also accept the @Header and @Headers annotations that is documented in @Transformer Order generateOrder(String productId, @Header("customerName") String customer) { return new Order(productId, customer); }
Header Filter Some times your transformation use case might be as simple as removing a few headers. For such a use case, Spring Integration provides a Header Filter which allows you to specify certain header names that should be removed from the output Message (e.g. for security reasons or a value that was only needed temporarily). Basically the Header Filter is the opposite of the Header Enricher. The latter is discussed in ]]> As you can see, configuration of a Header Filter is quite simple. It is a typical endpoint with input/output channels and a header-names attribute. That attribute accepts the names of the header(s) (delimited by commas if there are multiple) that need to be removed. So, in the above example the headers named 'lastName' and 'state' will not be present on the outbound Message.