Accessing Maven Properties in Java – 在Java中访问Maven属性

最后修改: 2020年 7月 22日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this short tutorial, we’ll take a look at how to use variables defined inside Maven’s pom.xml from a Java application.

在这个简短的教程中,我们将看看如何从Java应用中使用Maven的pom.xml内定义的变量。

2. Plugin Configuration

2.插件配置

Throughout this example, we’ll use the Maven Properties Plugin.

在本例中,我们将使用Maven Properties Plugin

This plugin will bind to the generate-resources phase and create a file containing the variables defined in our pom.xml during compilation. We can then read that file at runtime to get the values.

该插件将与generate-resources阶段绑定,并在编译过程中创建一个包含我们的pom.xml中定义的变量的文件。然后我们可以在运行时读取该文件以获得数值。

Let’s start by including the plugin in our project:

让我们首先在我们的项目中包括该插件。

<plugin>
    <groupId>org.codehaus.mojo</groupId> 
    <artifactId>properties-maven-plugin</artifactId> 
    <version>1.0.0</version> 
    <executions> 
        <execution> 
            <phase>generate-resources</phase> 
            <goals> 
                <goal>write-project-properties</goal> 
            </goals> 
            <configuration> 
                <outputFile>${project.build.outputDirectory}/properties-from-pom.properties</outputFile> 
            </configuration> 
        </execution> 
    </executions> 
</plugin>

Next, we’ll continue by providing a value to our variable. Furthermore, since we’re defining them inside the pom.xml, we can use Maven placeholders as well:

接下来,我们将继续为我们的变量提供一个值。此外,由于我们在pom.xml内定义它们,我们也可以使用Maven占位符

<properties> 
    <name>${project.name}</name> 
    <my.awesome.property>property-from-pom</my.awesome.property> 
</properties>

3. Reading Properties

3.阅读属性

Now it’s time to access our property from the configuration. Let’s create a simple utility class to read the properties from a file on the classpath:

现在是时候从配置中访问我们的属性了。让我们创建一个简单的实用类,从classpath上的文件中读取属性。

public class PropertiesReader {
    private Properties properties;

    public PropertiesReader(String propertyFileName) throws IOException {
        InputStream is = getClass().getClassLoader()
            .getResourceAsStream(propertyFileName);
        this.properties = new Properties();
        this.properties.load(is);
    }

    public String getProperty(String propertyName) {
        return this.properties.getProperty(propertyName);
    }
}

Next, we simply write a small test case that reads our values:

接下来,我们简单地写一个小测试用例,读取我们的值。

PropertiesReader reader = new PropertiesReader("properties-from-pom.properties"); 
String property = reader.getProperty("my.awesome.property");
Assert.assertEquals("property-from-pom", property);

4. Conclusion

4.结论

In this article, we went through the process of reading values defined in the pom.xml using the Maven Properties Plugin.

在本文中,我们通过使用Maven属性插件读取pom.xml中定义的值。

As always, all the code is available over on GitHub.

一如既往,所有的代码都可以在GitHub上获得