在Java属性中的Mule属性占位符访问

时间:2016-01-21 12:33:12

标签: java mule

我在mule中部署到多个环境时有不同的属性文件。在我的src / main / resources中,我有local.propertiestest.properties个文件。我还有一个全局属性占位符,我在mule-app.properties中引用,如https://docs.mulesoft.com/mule-user-guide/v/3.6/deploying-to-multiple-environments中所述,仅更改依赖于我使用的服务器的占位符环境变量。

例如,我可以拥有local.properties文件:

username=John
password=local

test.properties我会:

username=Christi
password=test

在我的app-mule.properties中我会指出:

mule.env=local or mule.env=test

所以实际上这很好用。但是当我必须在例如Config.java之类的java类中访问这些属性时,它不起作用。我想得到这个例子中的属性:

public class Config {

static Properties prop = new Properties();

static {
    // load a properties file
    try {
        InputStream input = Config.class.getClassLoader().getResourceAsStream("mule-app.properties");

        prop.load(input);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
public static final String USERNAME = prop.getProperty("username");
public static final String PASSWORD = prop.getProperty("password");
}}

如果我直接在mule-app.properties文件中定义所有属性,而不是引用特定的属性文件,则此java类可以正常工作。所以我的问题是,如何通过访问mule-app.properties中的引用来获取此java代码来访问本地和测试属性文件中定义的属性?

修改 我的解决方案有效,由@bigdestroyer建议:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class Config {

static Properties prop = new Properties();

static {
    // load a properties file
    try {
        InputStream input = Config.class.getClassLoader().getResourceAsStream("mule-app.properties");
        prop.load(input);
        String type = prop.getProperty("mule.env");
        input = Config.class.getClassLoader().getResourceAsStream(type + ".properties");            
        prop.load(input);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
public static final String USERNAME = prop.getProperty("username");
public static final String PASSWORD = prop.getProperty("password");
}}

1 个答案:

答案 0 :(得分:1)

如果我不误解你,你可以这样做:

public class Config {

static Properties prop = new Properties();

static {
    // load a properties file
    try {
        InputStream input = Config.class.getClassLoader().getResourceAsStream("mule-app.properties");
        InputStream input = 
        prop.load(input);

        String type = prop.getProperty("mule.env"); //<-- here you get local or test

        input = getClass().getClassLoader().getResourceAsStream(type + ".properties"); // here you get the file 

        prop.load(input);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
public static final String USERNAME = prop.getProperty("username");
public static final String PASSWORD = prop.getProperty("password");
}}

首先,你得到文件&#34; typ&#34; localtest,然后加载正确的文件。

注意:我&#34; m&#34;回收&#34; inputprop变量,我猜没有问题。试试吧。

我希望它有所帮助。

相关问题