Java-如何列出依赖项 [英] Java - How to list the dependencies
本文介绍了Java-如何列出依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望我的Java程序先记录依赖项.我知道mvn dependency:tree
命令,但是创建的Jar文件将不会在具有Maven的计算机上执行.
I want my Java program to log the dependencies before anything. I am aware of the mvn dependency:tree
command, but the Jar file created will not be executed on a computer with Maven.
在程序执行过程中如何获取依赖项列表?
How could we get the dependencies list during the execution of the program ?
推荐答案
您可以编写自己的parser
,因此可以定义自定义格式.
You could just write your own parser
, so you can define your custom formatting.
一个非常基本的(仅使用jdk内置库)可能看起来像这样:
A very basic one (using only jdk built-in libraries) might look like this:
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());
}
}
}
例如,此解析器将输出以下输出:
For instance this parser prints the following output:
----------------------------------
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
这篇关于Java-如何列出依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文