在我的 Mule 项目中,我有一个包含我的http地址的属性文件
server.address = http://localhost:8080/test/
然后在我的流程中我将它引用为${server.address}
,但我如何在java组件类中引用该属性?
例如:
public String address = ${server.address}
答案 0 :(得分:4)
您可以将java类中的属性设置为Spring属性。对于单个对象,将在启动流时设置该属性。
<flow name="propertyprojectFlow1" doc:name="propertyprojectFlow1">
<http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8581" path="echoServer" doc:name="HTTP"/>
<component doc:name="Java">
<singleton-object class="MyClass">
<property key="server" value="${server.address}"/>
</singleton-object>
</component>
</flow>
该类需要为该属性设置一个setter。
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;
public MyClass() {
}
@Override
public Object onCall(MuleEventContext eventContext) throws Exception {
logger.info("Server is " + server);
return null;
}
public void setServer(String server) {
logger.info("Setting server to " + server);
this.server = server;
}
}
答案 1 :(得分:3)
属性文件中的属性名称:
your.property.name.in.properties.file=testing
Java组件:
import org.mule.api.MuleEventContext;
import org.mule.api.lifecycle.Callable;
import org.springframework.beans.factory.annotation.Value;
public class PropertyTest implements Callable {
@Value("${your.property.name.in.properties.file}")
private String yourPropertyNameInPropertiesFile;
@Override
public Object onCall(MuleEventContext eventContext) throws Exception {
System.out.println("yourPropertyNameInPropertiesFile"+yourPropertyNameInPropertiesFile);
// TODO Auto-generated method stub
return null;
}
}
答案 2 :(得分:1)
您可以加载该属性或任何其他属性,加载属性文件。 (虽然它可能会产生一些性能问题,但每次执行流时都会加载属性文件)。
public Properties loadProperties(String name) {
if(properties == null){
return loadProperties(name, Thread.currentThread().getContextClassLoader());
} else {
return properties;
}
}
然后:
Properties props = loadProperties("application.properties");
String url = props.getProperty("server.address");
对@Matt回复进行一些更改
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;
}
}
}