[英]Spring boot reading properties file returns null
Hello I have the following project structure. 您好,我有以下项目结构。
I want to store my properties file outside my jar , so that if I change any property it will be reflected automatically. 我想将我的属性文件存储在jar之外,这样,如果我更改任何属性,它将自动反映出来。 My property file contains ip of the other servers, which might change, so that's why I want to keep my properties file outside my jar.
我的属性文件包含其他服务器的ip,它可能会更改,因此这就是为什么要将属性文件保留在jar之外的原因。
My resources
folder contains all my properties file including application.propeties. 我的
resources
文件夹包含我的所有属性文件,包括application.propeties。
I am using following snippet to read from my properties file. 我正在使用以下代码片段读取我的属性文件。
server_1 = new Properties(); server_1 = new Properties();
server_1.load(PropertyReader.class.getClassLoader().getResourceAsStream("resources/server_1.properties"));
server_2 = new Properties();
server_2.load(PropertyReader.class.getClassLoader().getResourceAsStream("resources/server_2.properties"));
I have also tried 我也尝试过
server_2.load(PropertyReader.class.getClassLoader().getResourceAsStream("server_2.properties"));
server_2.load(PropertyReader.class.getClassLoader().getResourceAsStream("/server_2.properties"));
But it gives me following error : 但这给了我以下错误:
Caused by: java.lang.NullPointerException: null
I have gone through the this link so that's why I have created resources
folder at src
level still I am not able to understand this behaviour. 我已经通过了此链接,所以这就是为什么我无法在
src
级别创建resources
文件夹的原因。
Thank you 谢谢
To continue from my comment, If this a jar where you are separating resources outside the jar/bundle, you need the resources folder in the classpath of the jar. 继续我的评论,如果这是一个jar,您在其中将jar / bundle之外的资源分开,则需要jar的classpath中的resources文件夹。
For an executable jar in my project, I added a classpath entry(relative to the jar's location) in my jar's manifest entry via maven-jar plugin: 对于项目中的可执行jar,我通过maven-jar插件在jar的清单条目中添加了一个类路径条目(相对于jar的位置):
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>....</mainClass>
</manifest>
<manifestEntries>
<Class-Path>../resources/</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
Check the MANIFEST.MF file for the added entry. 检查MANIFEST.MF文件中添加的条目。 Then you can use in your code directly(without resources folder) :
然后,您可以直接在代码中使用(没有资源文件夹):
PropertyReader.class.getClassLoader().getResourceAsStream("server_1.properties");
For your unit tests, you can directly provide in src/resources. 对于单元测试,您可以直接在src / resources中提供。
UPDATE: 更新:
Just noticed that you mentioned it's a spring boot application. 只是注意到您提到它是一个Spring Boot应用程序。 Refer to this one.
请参考这一章。 Use profiles to mention location of resources folder.
使用配置文件提及资源文件夹的位置。 This way it's neater.
这样更整洁。
Spring Boot Reading Properties Files Based on classpath arg Spring Boot基于类路径arg读取属性文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.