2017-08-31 102 views
0

讀取與動態檔案外部屬性會想到用Spring我如何使用Spring引導

class MyPropotypeBean { 

    /* We can not for static file name like 
    * @ConfigurationProperties(prefix = "abcd", locations = "file:conf/a2z.properties") 
    */ 
    public MyPropotypeBean(String propFileLocation) { 
     Properties prop = new Properties(); 
     InputStream input = null; 

     try { 
       input = new FileInputStream(propFileLocation); 
       prop.load(input); 
       gMapReportUrl = prop.getProperty("gMapReportUrl"); 
     } catch (IOException ex) { 
       ex.printStackTrace(); 
     } finally { 
       ... 
     } 

    } 
} 

我想propFileLocation動態插入類似以下內容的執行類似於下面的代碼的東西。

@ConfigurationProperties(prefix = "abcd", locations = "file:conf/" + propFileLocation + ".properties") 

我知道我們無法使用註釋來實現。我如何務實地做到這一點?

+0

也許有不同的靜態屬性文件中的動態文件列表? – tima

+0

使用環境Luke(環境變量或某些屬性) – 2017-08-31 16:50:51

+0

文件列表是動態的,每個原型bean必須根據屬性文件具有不同的值。環境變量可以包含我們需要創建相同數量的原型bean的多個prop文件名。 –

回答

0

您可以使用彈簧ResourceBundleMessageSource。它有助於加載外部屬性。看看here

@Value("${file.directory}") 
private String propFileLocation; 
//getters and setters 
@Bean 
public MessageSource messageSource() { 
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); 
    messageSource.setBasenames("file:conf/"+propFileLocation); 
    messageSource.setDefaultEncoding("UTF-8"); 
    return messageSource; 
} 
+0

謝謝你的回覆,但這不是我想要的。我想通過動態注入屬性文件來創建prototype bean。在我的情況下,您的解決方案更好的方法將是以下 '@Bean @Resource public Properties config(String propFileLocation)throws IOException返回PropertiesLoaderUtils.loadProperties(new ClassPathResource(propFileLocation)); }' –