2016-01-21 77 views
1

當我部署到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"); 
}} 

回答

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

首先,獲取文件「typ」localtest,然後加載正確的文件。

注意:我正在「回收」inputprop變量,我猜這是沒有問題的。只是測試它。

我希望它有幫助。

+0

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