You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中从Maven读取系统属性?Tomcat项目多环境配置

我来帮你搞定这个需求!要实现从pom.xml传递环境变量到Java代码,同时在打包时指定环境,咱们可以分这几步来做:

1. 在pom.xml中配置环境Profiles和属性

首先你需要在pom里定义不同环境的Profile,每个Profile对应专属的环境属性值,比如开发、测试、生产环境:

<profiles>
    <profile>
        <id>dev</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <env>development</env>
            <db.url>jdbc:mysql://localhost:3306/dev_db</db.url>
            <!-- 可添加其他环境专属属性,比如redis地址、接口域名等 -->
        </properties>
    </profile>
    <profile>
        <id>test</id>
        <properties>
            <env>testing</env>
            <db.url>jdbc:mysql://test-server:3306/test_db</db.url>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <env>production</env>
            <db.url>jdbc:mysql://prod-server:3306/prod_db</db.url>
        </properties>
    </profile>
</profiles>
2. 开启资源过滤,让Maven替换属性文件占位符

接下来要配置Maven的资源过滤功能,这样打包时它会自动把属性文件里的占位符替换成对应Profile的属性值。在pom的<build>节点下添加:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <includes>
                <include>application.properties</include> <!-- 你的属性文件路径,可按需调整 -->
            </includes>
        </resource>
    </resources>
    <!-- 保留你原有的build配置,比如plugins等 -->
</build>

然后在src/main/resources下创建application.properties文件,用占位符对应pom里的属性:

current.env=${env}
database.url=${db.url}
3. 在Java代码中读取属性文件

现在可以写一个工具类来读取这个属性文件,获取环境变量:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class EnvPropertyReader {
    private static final Properties PROPERTIES = new Properties();

    static {
        try (InputStream inputStream = EnvPropertyReader.class.getClassLoader().getResourceAsStream("application.properties")) {
            if (inputStream == null) {
                System.err.println("无法找到application.properties文件");
                return;
            }
            PROPERTIES.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getCurrentEnv() {
        return PROPERTIES.getProperty("current.env");
    }

    public static String getDatabaseUrl() {
        return PROPERTIES.getProperty("database.url");
    }
}

之后在业务代码里直接调用EnvPropertyReader.getCurrentEnv()就能拿到当前环境的标识了。

4. 打包时指定环境Profile

执行打包命令时,用-P参数指定对应的环境Profile即可:

  • 开发环境打包:mvn clean install -Pdev
  • 测试环境打包:mvn clean install -Ptest
  • 生产环境打包:mvn clean install -Pprod

如果需要临时自定义属性,也可以直接在命令行传递参数覆盖Profile配置,比如:

mvn clean install -Denv=custom_env -Ddb.url=jdbc:mysql://custom-server:3306/custom_db

内容的提问来源于stack exchange,提问作者Devendra Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:16:14