如何从pom.xml获取属性值?

问题描述:

我在pom.xml中添加了一个节点:

I have added a node in my pom.xml:

<properties>
        <getdownload-webapp.version>1.5</getdownload-webapp.version>
</properties>

我怎么能在代码中得到这个1.5值?

how could I get this 1.5 value in code?

String version = System.getProperty("getdownload-webapp.version"); // output version = null

这段代码在运行时为我提供了空值(

This code gave me null while running(

ps:此项目中没有settings.xml

ps: there is no settings.xml in this project

所以您拥有这样的属性.

So you have a property like this.

<properties>
    <getdownload-webapp.version>1.5</getdownload-webapp.version>
</properties>


在您的Maven项目中创建文件,如下所示.


Create a file as follows in your Maven project.

  src/main/resources/project.properties

或仅用于测试的情况如下.

Or as follows if it is for tests only.

  src/test/resources/project.properties

将此行添加到新文件中.请注意,您不应以"properties"作为前缀(例如,不要写"properties.getdownload-webapp.version").

Add this line inside the new file. Please note that you should not prefix with "properties" (e.g. don't write "properties.getdownload-webapp.version").

  version=${getdownload-webapp.version}


请注意,您还可以在文件中添加这样的标志.


Note that you can also add flags like this to the file.

  debug=false


如果尚未完成,则必须为项目启用Maven筛选.该功能将在项目文件中查找占位符,以将其替换为pom中的值.为了继续,您需要在pom.xml文件的< build> 标记内添加这些行.这是使用src/main的方法:


If not already done, you have to enable Maven filtering for your project. It is the feature that will look for placeholders inside the files of your project to be replaced by values from the pom. In order to proceed, you need add these lines inside the <build> tag of your pom.xml file. This is how to do with src/main:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
    ...

这是src/test的操作方法:

And here is how to do for src/test:

<build>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
            <filtering>true</filtering>
        </testResource>
    </testResources>
    ...


最后,在您的源代码( MyClassName.java )中,添加一个类似

  Properties props = new Properties();
  props.load(MyClassName.class.getClassLoader().getResourceAsStream("project.properties"));
  String version = props.getProperty("version");

您可以在 project.properties 文件中添加任意数量的变量,并使用此方法加载每个变量.

You can add as many variables as you want to the project.properties file and load each one using this method.