Springboot无法访问依赖jar的类路径中的资源

问题描述:

我有一个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

或者,它适用于我。

在应用项目

@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在应用程序启动期间提供的命令行参数。 –