Java -如何列出依赖项

kwvwclae  于 2023-04-04  发布在  Java
关注(0)|答案(2)|浏览(151)

我希望我的Java程序在任何事情之前记录依赖项。我知道mvn dependency:tree命令,但创建的Jar文件将不会在安装了Maven的计算机上执行。
在程序执行过程中,我们如何获得依赖项列表?

y1aodyip

y1aodyip1#

您可以编写自己的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
9ceoxa92

9ceoxa922#

类示例
{
File pomfile = new File(“./pom.xml”);
int getchar = new int getchar();
Model model =reader.read(new FileReader(pomfile));
String getString();
for(Dependency dependency:依赖关系)
{

System.out.println("----------------------------------");

System.out.println("Group Id: "+dependency.getGroupId());

System.out.println("Artifact Id: "+dependency.getArtifactId());

System.out.println("Version: "+dependency.getVersion());

}
}
所需依赖性

Artifact ID : maven-model
 version :  4.0.0-alpha-5

相关问题