Search code examples
javawsdlmulepayloadmule-flow

add a java class as a bean in MULE


In MULE 3.3.0 CE, I wrote a simple java class with constructor and two methods, I copied them at below:

 public class Book {
        private String title;

        public Book(String theTitle) {
            // TODO Auto-generated constructor stub
            title = theTitle;
        }

        public String getTitle(){
            return title;
        }

        public String displayAuthorName(String authorName) {
            return authorName;
        }
    }

Now I want to add my java class, as a bean in my .mflow(Configuration XML) and then pass payload to the java class method.

How can I do this issue?


Solution

  • In order to get this done, you need to:

    1. Define your component as a spring bean.
    2. Define the entry point of your component.
    3. Use your component within a flow.

    Here is an example:

    package com.mypackage.test;
    
    import org.mule.api.annotations.param.Payload;
    
        public class MyComponent {
    
        private String myProperty;
    
        public String getMyProperty() {
            return myProperty;
        }
    
        public void setMyProperty(String myProperty) {
            this.myProperty = myProperty;
        }
    
        public String doProcess(@Payload String payload) {
            //do something interesting
            return "You said: " + payload;
        }
    
    }
    

    A way to define the entry point is by using the @Payload annotation.

    And then a sample flow:

    <spring:bean id="myBean" class="com.mypackage.test.MyComponent">
        <spring:property name="myProperty" value="Some Value" />
    </spring:bean>
    
    <flow name="componentFlow">
        <http:inbound-endpoint address="http://localhost:8082/test" />
        <component>
            <spring-object bean="myBean" />
        </component>
        <set-property propertyName="Content-Type" value="text/plain" doc:name="Property" />
    </flow>