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

时间:2017-11-17 22:56:19

标签: spring-boot classpath inputstream classloader property-files

我有一个弹簧启动JAR MyMain.jar,它在BOOT-INF / lib中有依赖的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运行时,它不会打印任何内容。

org.springframework.boot.loader.jar.ZipInflaterInputStream@214c265e

readLine()在命令行运行期间给出null。

有人可以帮忙!

1 个答案:

答案 0 :(得分:0)

或者,这对我有用。

在app项目中创建此类

@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")

我希望它有所帮助。

相关问题