如何将Maven settings中server_two的账号密码注入POM文件?
Maven配置:如何从settings.xml的server节点注入用户名和密码到POM?
背景信息
用户提供的settings.xml内容如下:
<profiles> <profile> <id>artifactory</id> </profile> <properties> <TestProperty>test_property</TestProperty> </properties> </profiles> <activeProfiles> <!--make the profile active all the time --> <activeProfile>artifactory</activeProfile> </activeProfiles> <servers> <server> <id>server_one</id> <username>user_one</username> <password>pw_one</password> </server> <server> <id>server_two</id> <username>pw_two</username> <password>pw_two</password> </server> </servers>
用户已能通过${TestProperty}注入profile中的属性,但不知道如何将server_two的用户名和密码注入到POM文件中。
解决方法
Maven本身不支持直接在POM中引用settings.xml里<servers>节点的用户名和密码——这部分属于安全敏感配置,设计上就是避免被POM直接读取的。要实现相关需求,有以下几种可行方式:
1. 将服务器凭证转为profile属性
把server_two的用户名和密码放到settings的profile属性中,就能像${TestProperty}一样在POM中直接引用:
修改settings.xml的profile部分:
<profiles> <profile> <id>artifactory</id> <properties> <server_two.username>pw_two</server_two.username> <server_two.password>pw_two</server_two.password> </properties> </profile> </profiles>
之后在POM中直接用${server_two.username}和${server_two.password}调用即可。
2. 使用Maven插件读取服务器配置
如果不想把凭证放到属性里,可以用maven-help-plugin的evaluate目标读取服务器信息,这种方式更适合脚本或CI场景:
# 读取server_two的用户名 mvn help:evaluate -Dexpression=settings.servers.server[id='server_two'].username -q -DforceStdout # 读取server_two的密码 mvn help:evaluate -Dexpression=settings.servers.server[id='server_two'].password -q -DforceStdout
3. 关联server ID到仓库配置
如果你的需求是在POM的仓库/部署仓库中使用这些凭证,只需要让仓库的id和settings里server的id一致即可,Maven会自动匹配对应的用户名和密码,无需手动注入:
比如在POM中配置仓库:
<repositories> <repository> <id>server_two</id> <url>https://your-repo-url.com</url> </repository> </repositories>
Maven访问该仓库时,会自动调用settings里id为server_two的凭证。
内容的提问来源于stack exchange,提问作者Eric Bosch
相关产品推荐
相关产品推荐

