且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用maven生成包含所有依赖项的xml文件

更新时间:2023-09-17 20:52:16

我真的不知道JBoss以及是否有另一个这样做的方法,但你可以用GMaven完成它:

I don't really know about JBoss and whether there's another way to do this, but you can do it quite simply with GMaven:

<plugin>
    <groupId>org.codehaus.gmaven</groupId>
    <artifactId>gmaven-plugin</artifactId>
    <version>1.3</version>
    <configuration>
        <source>
            def sw = new StringWriter()
            def xml = new groovy.xml.MarkupBuilder(sw)
            xml.module(xmlns:'urn:jboss:module:1.0', name:'ats.platform') {
              resources {
                project.runtimeClasspathElements.each {
                  def path = it.find(".*?([\\w\\.-]*\\.jar)") { it[1] }
                  !path?:'resource-root'(path:path)
                }
              }
            }
            println sw
        </source>
    </configuration>
</plugin>

有几点需要注意:


  1. 该脚本将XML吐出到stdout,但您显然可以将其写入文件或其他任何内容。

  2. runtimeClasspathElements 包含jar的绝对路径,这就是我用正则表达式解析它的原因。如果您需要的不仅仅是jar文件名,可以调整正则表达式以包含更多路径,或者只是添加一个字符串。

  1. That script spits the XML out to stdout, but you can obviously write it to a file or whatever very easily.
  2. The runtimeClasspathElements contain absolute paths to the jar, which is why I parse it with a regex. You can adjust the regex to include more of the path or just prepend a string if you need more than just the jar file name.

我发布了工作示例在github上(它只是一个POM),我将上面的插件配置绑定到初始化构建阶段。如果你有git,你可以自己克隆并运行它:

I've posted a working example on github (it's just a POM) where I've bound the above plugin configuration to the initialize build phase. If you have git, you can clone and run it yourself with:

git clone git://github.com/zzantozz/testbed tmp
cd tmp
mvn -q initialize -pl ***/7755255-gmaven-to-build-xml-from-classpath

在示例项目中,我添加了jdom 1.0和dom4j 1.6.1作为依赖项,这是它创建的输出:

In the sample project, I added jdom 1.0 and dom4j 1.6.1 as dependencies, and here's the output it created:

<module xmlns='urn:jboss:module:1.0' name='ats.platform'>
  <resources>
    <resource-root path='jdom-1.0.jar' />
    <resource-root path='dom4j-1.6.1.jar' />
    <resource-root path='xml-apis-1.0.b2.jar' />
    <resource-root path='aspectjrt-1.6.11.jar' />
  </resources>
</module>

注意:我不是一个时髦的专家,所以可能有一种更加时髦的方式,但你可以看到它是多么容易。

Note: I'm not a groovy expert, so there may be a groovier way to do it, but you can see how easy it is even so.