Java - 如何列出依赖项

时间:2018-01-09 11:34:46

标签: java spring maven

我希望我的Java程序能够在任何事情之前记录依赖项。我知道mvn dependency:tree命令,但创建的Jar文件不会在使用Maven的计算机上执行。

如何在程序执行期间获取依赖项列表?

1 个答案:

答案 0 :(得分:0)

您可以自己编写parser,以便定义自定义格式。

一个非常基本的(仅使用jdk内置库)可能如下所示:

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
// other imports...

public static void printPomDependencies() throws IOException, SAXException, ParserConfigurationException {
    // pom relative to your project directory
    final File pomFile = new File("./pom.xml");

    DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = dBuilder.parse(pomFile);
    doc.getDocumentElement().normalize();
    final NodeList dependencyNodes = doc.getElementsByTagName("dependency");

    for (int i = 0; i < dependencyNodes.getLength(); i++) {
        final Node n = dependencyNodes.item(i);

        final NodeList list = n.getChildNodes();

        System.out.println("----------------------------------");
        for (int j = 0; j < list.getLength(); j++) {
            final Node n2 = list.item(j);
            // do not print empty text nodes or others...
            if (n2.getNodeType() != Node.ELEMENT_NODE) continue;


            System.out.println(n2.getNodeName() + ":" + n2.getTextContent());

        }
    }
} 

例如,此解析器打印以下输出:

----------------------------------
groupId:io.spring.platform
artifactId:platform-bom
version:Brussels-SR6
type:pom
scope:import
----------------------------------
groupId:org.springframework.boot
artifactId:spring-boot-starter-web
----------------------------------
groupId:org.springframework
artifactId:spring-context
version:5.0.2.RELEASE
----------------------------------
groupId:org.springframework.data
artifactId:spring-data-jpa
version:2.0.2.RELEASE