0

我有一個spring引導JAR MyMain.jar,它具有BOOT-INF/lib內部的依賴jar。Springboot無法訪問依賴jar的類路徑中的資源

我想訪問BOOT-INF/lib/MyDep.jar/abcd.properties中的屬性文件。

我試過下面的代碼。

InputStream in = new ClassPathResource("abcd.properties").getInputStream(); 
System.out.println("InputStream : "+in); 
String line; 
BufferedReader br = new BufferedReader(new InputStreamReader(in));   
while ((line = br.readLine()) != null) { 
    System.out.println(line); 
} 

這在我的Eclipse IDE中完美運行。但是當我在jar命令行上運行它時,它不會打印任何內容。

[email protected]65e

的readLine()給出的命令行運行期間空。

任何人都可以請幫忙!

+0

我發現有點難以遵循你正在嘗試做的事情,但它聽起來像應該起作用。也許你可以分享一個能夠再現問題的小樣本項目? –

+0

@AndyWilkinson - 基本上來自一個父jar文件類,我試圖讀取一個屬性文件內的依賴jar的類路徑。我將創建一個示例項目來共享 – RedGuts

回答

0

或者,它適用於我。

在應用項目

@Configuration 
@ComponentScan("yourpackage") 
public class AppConfig { 
    @Configuration 
    @PropertySource("common.properties") 
    static class default{} 
} 

如果你想讀通過不同的配置文件(-Dspring.profiles.active)

@Configuration 
@ComponentScan("yourpackage") 
public class AppConfig { 
    @Profile("alpha") 
    @Configuration 
    @PropertySource("common-alpha.properties") 
    static class Alpha{} 

    @Profile("staging") 
    @Configuration 
    @PropertySource("common-staging.properties") 
    static class Staging{} 

    @Profile("production") 
    @Configuration 
    @PropertySource("common-production.properties") 
    static class Production{} 
} 

你可以使用Spring配置文件創建此類@Autowired註釋如下,但要確保你用@Component或類似的註解你的類。

@Autowired 
Environment env; 

在你的屬性文件

env.getProperty("property") 

我希望它可以幫助你可以得到的財產。

+0

我可以試一試,但我想將屬性源作爲參數參數,而不是硬編碼的靜態文件 – RedGuts

+0

@PropertySource(「$ {propertiesArgument} .properties」),並且您只傳遞-DpropertiesArgument在應用程序啓動期間提供的命令行參數。 –