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

问题描述:

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

因此,例如在local.properties文件,我可以有:

username=John 
password=local 

test.properties我会:

username=Christi 
password=test 

,并在我的app-mule.properties我想指出:

mule.env=local or mule.env=test 

所以实际上这工作正常。但是当我必须访问java类中的这些属性时,例如Config.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"); 
}} 

这个Java类工作正常,如果我直接在mule-app.properties文件中定义的所有属性,而不是引用特定的属性文件。所以我的问题是,我怎么才能得到这个java代码来访问本地和测试属性文件中定义的属性,只需访问mule-app.properties中的引用?

编辑: 我的解决方案,它的工作原理,通过@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"); 
}} 

如果我没有误会你,你能做到这样:

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"); 
}} 

首先,获取文件“typ”localtest,然后加载正确的文件。

注意:我正在“回收”inputprop变量,我猜这是没有问题的。只是测试它。

我希望它有帮助。

+0

感谢@bigdestroyer,它的工作原理! :d – TheLearner