












在 Java 代码中使用 pom.xml 中 profile 级别的 <properties>,最常见和推荐的方式是通过 Maven Resource Filtering。这个过程涉及到以下步骤:
在 pom.xml 中定义 profile 和 properties:
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<db.url>jdbc:mysql://localhost:3306/mydb_dev</db.url>
<server.address>localhost</server.address>
</properties>
</profile>
<profile>
<id>prod</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
<db.url>jdbc:mysql://prod-db:3306/mydb_prod</db.url>
<server.address>prod-server</server.address>
</properties>
</profile>
</profiles>
在 src/main/resources 中创建一个.properties 文件:
database.url=${db.url}
server.address=${server.address}
在 pom.xml 中配置资源过滤:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
在 Java 代码中加载和使用属性:
使用 Properties 类:
import java.io.InputStream; import java.util.Properties; //... Properties props = new Properties(); InputStream inputStream = getClass().getClassLoader().getResourceAsStream("application.properties"); props.load(inputStream); String databaseUrl = props.getProperty("database.url"); String serverAddress = props.getProperty("server.address");
使用 Spring 的 @Value 注解:
import org.springframework.beans.factory.annotation.Value; //... @Value("${database.url}") private String databaseUrl; @Value("${server.address}") private String serverAddress;
当你在开发环境中运行 Maven 构建时,dev profile 是默认激活的,所以 application.properties 文件中会被替换为 dev profile 中的属性值。如果你想在构建时使用 prod profile,可以在命令行中添加 -Pprod 参数,例如:mvn package -Pprod。
这样,application.properties 文件中就会被替换为 prod profile 中的属性值。无论你在哪个环境中构建和运行应用,Java 代码中使用的属性值都会根据当前激活的 profile 自动更新。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。