java程序调用一堆第三方库是很常见的事情,例子程序中就调用了网上常见库jdom读取xml文件.
package com.sitinspring;

import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;


public class Inlet
{

public static void main(String[] arg)
{

try
{
SAXBuilder builder=new SAXBuilder ();
InputStream is =Inlet.class.getResourceAsStream( "/testfile.xml" );
Document doc=builder.build(is);

Element root=doc.getRootElement();
List ls=root.getChildren();


for(Iterator it=ls.iterator();it.hasNext();)
{
Element elm=(Element )it.next();
System.out.println(elm.getName());
}
}

catch(Exception ex)
{
ex.printStackTrace();
}
}
}
如何让Maven工程也能找到Jdom库呢,很简单,添加一个dependency节点就能做到,详情请见下列代码的jdom处.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sitinspring</groupId>
<artifactId>Maevn3ndPart</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Maevn3ndPart</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
然后执行Mvn compile就可以看见,Maven从网上下载了jdom库到本地的repository目录,请看下图.

将dependency节点和repository中jdom路径对比就可以知道,dependency节点中groupId对应路径中第一层目录,artifactId对应第二层,version对应第三层,而scope用于编译则是compile.这些发现我们以后还将用到.
本文例程:
http://www.blogjava.net/Files/sitinspring/Maevn3ndPart20070621133225.zip 附录:
Dependency Scope
在POM 4中,<dependency>中还引入了<scope>,它主要管理依赖的部署。目前<scope>可以使用5个值:
- compile,缺省值,适用于所有阶段,会随着项目一起发布。
- provided,类似compile,期望JDK、容器或使用者会提供这个依赖。如servlet.jar。
- runtime,只在运行时使用,如JDBC驱动,适用运行和测试阶段。
- test,只在测试时使用,用于编译和运行测试代码。不会随项目发布。
- system,类似provided,需要显式提供包含依赖的jar,Maven不会在Repository中查找它。