Pages

Friday, 22 March 2013

Create Custom Transformer in mule 3.3 using Annotation

Creating Custom Transformers in mule 3.3 is a lot easier using annotation rather than extending AbstractMessageTransformer.
Let's take an example as to how to do it .
Suppose we want to read json from an input file and want to convert it in java object.
Although mule do it automatically as it has built in support for Jackson , but sometimes you want to have your own ObjectMapper and other things like this.Then you can use your own transformer.You can create any kind of transformer as long as return type and source type of transformer are not ambiguous with other transfomers.
here is our flow :
First of all create a Transformer class like this along with all the annotations. In this transformer input type is InputStream and output is our JSonBean Object.

and this is our Component which takes its parameter as Converted java object not json.
Do not forget to use @Payload annotation , because from this , mule will identify that it needs to apply transfomer to convert
incoming inputstream in payload to JsonBean type.

Declare your custom transformer bean in to xml file , otherwise mule won't be able to find this transformer.
I tried using auto-transfomer tag also but it was not working.
There is no need to fit your transformer in mule flow . As mule will automatically detect and apply appropriate transformer based
on input and output type of message payload .
If you try to do this you will get error like this :
Cannot convert value of type [X] to required type [Y] for property 'messageProcessors[0]': no matching editors or conversion strategy found .
If you really need to fit the transformer in flow , you should use AbstractMessageTransformer as it is the Type of org.mule.api.processor.MessageProcessor which is necessary for calling transformer explicitly.
Post and comment if you have any questions !!