Andre Coetzee Andre Coetzee - 2 months ago 21
Java Question

Mule Properties in a java component

In my Mule project, I have a property file that contains my http address for instance

server.address = http://localhost:8080/test/

and then in my flow i will reference it as
${server.address}
, but how do i reference that property in a java component class?

For instance:

public String address = ${server.address}

Answer

You can load that property or any other property, loading the properties file. (although it could create some performance issues, loading the properties file every time the flow is executed).

public Properties loadProperties(String name) {
    if(properties == null){
        return loadProperties(name, Thread.currentThread().getContextClassLoader());
    } else {
        return properties;
    }
}

And then:

Properties props = loadProperties("application.properties");
String url = props.getProperty("server.address");

Making some changes to @Matt answer

    import org.apache.log4j.Logger;
    import org.mule.api.MuleEventContext;
    import org.mule.api.lifecycle.Callable;   

    public class MyClass implements Callable {
       private static Logger logger = Logger.getLogger(MyClass.class);
       private String server;
       private Properties properties;

       public MyClass() {  }

       @Override
       public Object onCall(MuleEventContext eventContext) throws Exception {
           properties = loadProperties("application.properties");
           server = properties.getProperty("server.address");
           logger.info("Server is " + server);
           return null;
       }

       public Properties loadProperties(String name) {
            if(properties == null){
                return loadProperties(name, Thread.currentThread().getContextClassLoader());
            } else {
               return properties;
            }
        }
   }
Comments