1. 概述

在本篇短小精悍的教程中,我们将探讨如何在Java应用中读取 pom.xml 中定义的变量。

这种需求在实际开发中并不少见,比如你想把项目版本号、构建时间或环境配置从Maven传递到代码里,而不是硬编码。✅
直接在Java里读 pom.xml 不现实,但我们可以借助Maven插件,在构建阶段把属性导出成一个 .properties 文件,运行时再加载它——简单粗暴,但有效。

2. 插件配置

我们使用 Maven Properties Plugin 来完成这个任务。

该插件会在 generate-resources 阶段执行,自动将 pom.xml 中的 <properties> 写入指定的 .properties 文件,输出到编译目录(通常是 target/classes),这样它就能被类加载器读到了。

添加插件依赖

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

⚠️ 注意:outputFile 路径必须指向 outputDirectory(即 classes 目录),否则运行时无法通过类路径加载。

定义 Maven 属性

接下来,在 pom.xml<properties> 中定义你需要的变量。你甚至可以使用Maven内置的占位符,比如 ${project.name}${project.version}${maven.build.timestamp} 等。

<properties> 
    <name>${project.name}</name> 
    <my.awesome.property>property-from-pom</my.awesome.property> 
    <build.version>${project.version}</build.version>
    <build.time>${maven.build.timestamp}</build.time>
</properties>

构建后,插件会生成如下内容的文件:

#Generated by Maven
#Thu Oct 10 12:34:56 CST 2024
name=My Awesome Project
my.awesome.property=property-from-pom
build.version=1.0.0-SNAPSHOT
build.time=2024-10-10 12:34:56

这些值在运行时就可用了。

3. 在Java中读取属性

现在我们只需要一个简单的工具类,从类路径加载这个 .properties 文件即可。

创建 PropertiesReader 工具类

public class PropertiesReader {
    private Properties properties;

    public PropertiesReader(String propertyFileName) throws IOException {
        InputStream is = getClass().getClassLoader()
            .getResourceAsStream(propertyFileName);
        if (is == null) {
            throw new FileNotFoundException("Property file '" + propertyFileName + "' not found on classpath");
        }
        this.properties = new Properties();
        this.properties.load(is);
    }

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

✅ 小贴士:

  • 使用 ClassLoader.getResourceAsStream 而不是 FileInputStream,确保从 classpath 加载。
  • 建议加上空指针判断,避免文件缺失时静默失败——踩坑无数。

使用示例

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

// 读取项目版本
String version = reader.getProperty("build.version");
System.out.println("当前版本: " + version); // 输出: 1.0.0-SNAPSHOT

你也可以封装成单例或静态工具,避免重复加载:

public class BuildInfo {
    private static final PropertiesReader READER = new PropertiesReader("properties-from-pom.properties");

    public static String version() {
        return READER.getProperty("build.version");
    }

    public static String buildTime() {
        return READER.getProperty("build.time");
    }
}

4. 总结

通过 Maven Properties Plugin,我们可以轻松地将 pom.xml 中的属性导出为 .properties 文件,并在Java运行时读取。这套方案:

  • ✅ 简单可靠,适合大多数项目
  • ✅ 支持Maven内置变量(如版本、时间戳)
  • ✅ 无需额外依赖,仅需一个轻量插件
  • ❌ 不适用于需要动态修改属性的场景(毕竟是构建时写死的)

所有示例代码已上传至 GitHub:https://github.com/baeldung/tutorials/tree/master/maven-modules/maven-properties


原始标题:Accessing Maven Properties in Java | Baeldung