简体   繁体   English

如何从Maven项目中的外部jar读取属性文件

[英]How to read properties file from external jar in maven project

I am new to maven and Java .我是mavenJava新手。 I am working on a large codebase which uses the Spring web framework.我正在开发一个使用 Spring Web 框架的大型代码库。 I may be missing fundamentals but I have done my best to go over all the basics of the project implementation.我可能缺少基础知识,但我已尽力了解项目实施的所有基础知识。
For the feature I am building,I have properties files that I had earlier saved in src/main/resources in my maven project and was reading from my class named ReaderClass with this statement对于我正在构建的功能,我有一些属性文件,我之前在我的 maven 项目的 src/main/resources 中保存了这些文件,并且正在使用此语句从名为ReaderClass类中读取

ReaderClass.class.getResourceasStream("xyz.properties");

Now I have externalized these files into a separate project and have built a jar out of it.现在我已经将这些文件具体化到一个单独的项目中,并用它构建了一个 jar。 This jar only has the properties files under a folder named resource.这个jar只有一个名为resource的文件夹下的属性文件。
I have added this jar file as an dependency in the IntelliJ IDE and would like to read the properties files from this jar.我已将此 jar 文件添加为 IntelliJ IDE 中的依赖项,并希望从此 jar 中读取属性文件。 Had it been a .class file I would use an import statement in ReaderClass but how would I read properties files?如果它是一个 .class 文件,我会在ReaderClass使用 import 语句,但我将如何读取属性文件?

ADDITIONAL INFORMATION附加信息

Also, I am not sure if this is a problem but IntelliJ doesn't actually show the jar in the External Libraries Tab but does show my jar in the dependencies tab of the Modules Section in Project Structure.此外,我不确定这是否是一个问题,但 IntelliJ 实际上并未在“外部库”选项卡中显示 jar,而是在“项目结构”的“模块”部分的依赖项选项卡中显示我的 jar。 I wanted to make sure this wouldn't affect the solution.我想确保这不会影响解决方案。

If you are using Spring, try如果您使用的是 Spring,请尝试

@Value("${property.name}")
private String property;

to read properties from resources folder.从资源文件夹中读取属性。

There are numerous ways to do this.有很多方法可以做到这一点。

Assuming your xyz.properties file looks like this:假设您的xyz.properties文件如下所示:

a=b
y=z
mykey=myvalue

Using java.util.ResourceBundle使用 java.util.ResourceBundle

If you don't need to pass around the read data as a Properties object, this is the easiest way.如果您不需要将读取的数据作为Properties对象传递,这是最简单的方法。

ResourceBundle rb = ResourceBundle.getBundle("xyz");
System.out.println("a=" + rb.getString("a"));

Using java.util.Properties使用 java.util.Properties

A bit more work and some boiler-plate, but accomplishes the same thing.更多的工作和一些样板,但完成同样的事情。

Properties p = new Properties();
try (InputStream is = getClass().getClassLoader().getResourceAsStream("xyz.properties")) {
   p.load(is);
}
catch (IOException e) {
   // Handle as appropriately.
}
System.out.println("mykey=" + p.getProperty("mykey"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM