访问在pom文件中定义的maven属性

93

在普通的Maven项目和Maven插件项目中,我如何访问在pom文件中定义的Maven属性?


1
你对什么样的信息感兴趣?如果只是版本或类似的东西,那最好还是将其记录在清单中并从那里读取。参考链接:https://dev59.com/eHE85IYBdhLWcg3wkkY8#2713013 - Joachim Sauer
1
有很多关于这个问题的Stack Overflow帖子:http://stackoverflow.com/search?q=read+pom+in+java,至少在发帖之前先看一下。SO编辑助手应该会显示它们。Google也是如此。 - Jean-Rémy Revy
谢谢大家。我现在意识到这是非常糟糕的做法。我会尝试其他方法。 - SparedWhisle
可能是 Get MavenProject from just the POM.xml - pom parser? 的重复问题。 - oers
7个回答

89
使用properties-maven-plugin在编译时将特定的properties写入文件,然后在运行时读取该文件。在您的pom.xml中实现:
<properties>
     <name>${project.name}</name>
     <version>${project.version}</version>
     <foo>bar</foo>
</properties>

<build>
    <plugins>
        <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}/my.properties</outputFile>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

然后在 .java 文件中:

java.io.InputStream is = this.getClass().getResourceAsStream("my.properties");
java.util.Properties p = new Properties();
p.load(is);
String name = p.getProperty("name");
String version = p.getProperty("version");
String foo = p.getProperty("foo");

那个方法虽然可行,但导致Eclipse陷入了无限构建/部署到Tomcat循环(构建->生成my.properties->资源更改->构建),所以我不得不将阶段更改为compile。不确定这是否是正确的解决方案。 - Nikita Bosik
@atoregozh建议使用Guava资源来加载属性文件。好的。但为了保持这个示例具有标准API,已经撤销了更改。 - Leif Gruenwoldt
3
现在有一个稳定的 1.0.0 版本可用。 - Pieter De Bie

27

10
只有在使用Maven运行生成的构建文件时,才能使此方法生效,可以尝试使用maven-exec-plugin插件。如果只是使用Maven编译代码,则无法实现此方法。 - David Pashley
@DavidPashley,没错。在仅编译的情况下,我猜测变量需要从编译器插件中设置。 - Santosh

7

6
Maven已经有一个解决方案来实现你想要的功能: 从POM.xml中获取MavenProject - pom解析器? 顺便说一句:这是谷歌搜索的第一个结果 ;)
Model model = null;
FileReader reader = null;
MavenXpp3Reader mavenreader = new MavenXpp3Reader();

try {
     reader = new FileReader(pomfile); // <-- pomfile is your pom.xml
     model = mavenreader.read(reader);
     model.setPomFile(pomfile);
}catch(Exception ex){
     // do something better here
     ex.printStackTrace()
}

MavenProject project = new MavenProject(model);
project.getProperties() // <-- thats what you need

1
这里不鼓励单链接回答(主要是因为当链接资源消失时,它们可能变得无用)。您至少应该在此处总结链接帖子中的信息。 - Joachim Sauer
3
这真是一种非常糟糕的做法,只需使用Maven资源插件即可! - Mark Bakker
1
如果他想从Java代码访问属性,为什么这会是不好的做法? - SWoeste
2
但前提是你认为他想要/可以更改他的pom文件。我同意你的观点,直接将属性放在pom文件中而不是外部文件中可能会有问题。当然,可以使用Java属性类读取该文件。但如果情况相反呢?那么Maven模型是解决问题的最佳方案...但在David Dai告诉我们他想要做什么之前,我们都只是在猜测。 - SWoeste
1
我的理解也是我们有一个mvn pom文件(包含属性)和一个Java应用程序(从中我们想要读取该pom文件的详细信息),而不需要实际运行maven。 - Andreas Dolk
显示剩余3条评论

6

Leif Gruenwoldt回答更新:

使用以下内容很重要:

this.getClass().getClassLoader().getResourceAsStream("maven.properties");

而不仅仅是

 this.getClass().getResourceAsStream("maven.properties");

特别是,如果你将你的maven.properties文件正确地写到project.build.outputDirectory中:
<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}/maven.properties</outputFile>
         </configuration>
      </execution>
   </executions>
</plugin>

这里的解释是正确的


我尝试了你的代码,它在路径“classes”下生成了属性,但是当我尝试检索时,它返回null。 - Robs

0
我使用 spring-boot-maven-plugin 中的 build-info 目标:
在我的 pom.xml 文件中:
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
    ...
      <execution>
        <id>build-info</id>
        <goals>
          <goal>build-info</goal>
        </goals>
      </execution>
    </executions>
    <configuration>
    ...
    </configuration>
</plugin>

在我的代码中:

@Autowired
BuildProperties buildProperties;

...

@GetMapping
public Map<String, String> getVersion() {
    return Map.of(
            "build.name", buildProperties.getName(), 
            "build.version", buildProperties.getVersion(), 
            "build.date", buildProperties.getTime().toString());
}

关于此插件目标的更多信息可以在此处找到:https://docs.spring.io/spring-boot/docs/current/maven-plugin/reference/htmlsingle/#goals-build-info


-7
您可以使用JDOM(http://www.jdom.org/)解析pom文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接