0

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

任何人都可以帮忙!

4

1 回答 1

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

我希望它有帮助。

于 2017-11-18T09:04:30.917 回答