繁体   English   中英

如何在maven war项目中获取pom文件的路径

[英]How to get the path of the pom file in a maven war project

嗨,有没有办法在 Maven 项目中获取 pom 文件的路径。 我需要读取 pom 文件并使用它来获取一些信息,例如版本、依赖项列表等。

 MavenXpp3Reader reader = new MavenXpp3Reader();
          Model model = reader.read(MainTest.class.getResourceAsStream( "how to get this path"+"/pom.xml"));
          for(Dependency d : model.getDependencies())
          {
              System.out.println(d.getArtifactId());
          }

一种解决方案是将有效的 pom 复制到 META-INF 文件夹。 检查这个链接在 META-INF 目录中添加有效的 pom.xml

您可以按照上面的建议将 pom 添加到 META-INF 文件夹。 您还可以使用默认情况下 Jar 和相关 Maven 存档插件放在 META-INF 中的 pom.properties 文件。 无论哪种情况,只要 jar 位于类路径中,您就可以将其作为资源访问。 我所拥有的唯一示例是用 Groovy 编写的:

def static String getMavenVersion(Class mainClass) {
    //
    // If this doesn't work, the likely reason is that we're running in development, so start with a
    // reasonable default
    //
    def String result = "Lastest Development"

    //
    // Get our package - one up in the tree is the path to the properties file we want.
    //
    def String packagePath = mainClass.package.name
    def int index = packagePath.lastIndexOf(".")
    def String groupId = packagePath.substring(0, index)
    def String artifact = packagePath.substring(index + 1)


    //
    // Get the version from the property file
    //
    Protect.resource
    {
        InputStream input = MiscUtils.class.getResourceAsStream("/META-INF/maven/${groupId}/${artifact}/pom.properties")
        input
    }
    { InputStream input ->
        if (input != null) {
            def Properties mavenProps = new Properties()
            mavenProps.load(input)
            result = mavenProps.getAt("version")
        }
    }

    result
}
example; 
 ı_____project files(pom.xml in this files) 
  I_____src 
   I____main 
    ı____java 
      ı___com 
       ı___file 
        ı___file2 
         ı___ my class

your be if class hierarchy;

 ....../pom.xml 
or
 ./../../../../../pom.xml

在maven项目中,项目目录下有pom.xml。
System.getProperty("user.dir")给出项目目录。
尝试 - Model model = reader.read(MainTest.class.getResourceAsStream( System.getProperty("user.dir")+"/pom.xml"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM