Ant:指定外部依赖项时的ClassNotFoundException

时间:2014-10-01 16:02:38

标签: java ant jar classpath

我的项目布局:

.
├── bin
│   ├── build
│   │   └── hello.jar
│   │── classes
│       └── helloworld
│           └── Main.class
├── build.xml
├── lib
│   └── postgresql.jar
└── src
    └── helloworld
        └── Main.java

的build.xml

<project>
<property name="class_dir" value="bin/classes"/>
<property name="src_dir" value="src"/>
<property name="build_dir" value="bin/build"/>
<property name="jar_name" value="hello.jar"/>
<property name="lib_dir" value="lib"/>

<target name="clean">
    <delete dir="${class_dir}"/>
    <delete dir="${build_dir}"/>
</target>

<target name="compile">
    <mkdir dir="${class_dir}"/>
    <javac includeantruntime="false" srcdir="${src_dir}" destdir="${class_dir}"/>
</target>

<target name="jar">
    <mkdir dir="${build_dir}"/>
    <jar destfile="${build_dir}/${jar_name}" basedir="${class_dir}">
        <manifest>
            <attribute name="Main-Class" value="helloworld.Main"/>
        </manifest>
    </jar>
</target>

<target name="run" >
    <java jar="${build_dir}/${jar_name}" fork="true" failonerror="true">
        <classpath>
            <pathelement location="${lib_dir}/postgresql.jar"/>
        </classpath>
    </java>
</target>

执行ant run时的错误:

run:
 [java] java.lang.ClassNotFoundException: org.postgresql.Driver
 [java]     at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
 [java]     at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
 [java]     at java.security.AccessController.doPrivileged(Native Method)
 [java]     at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
 [java]     at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
 [java]     at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
 [java]     at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
 [java]     at java.lang.Class.forName0(Native Method)
 [java]     at java.lang.Class.forName(Class.java:259)
 [java]     at helloworld.Main.main(Unknown Source)
 [java] Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost:5430/hello_world
 [java]     at java.sql.DriverManager.getConnection(DriverManager.java:689)
 [java]     at java.sql.DriverManager.getConnection(DriverManager.java:247)
 [java]     at helloworld.Main.main(Unknown Source)

甚至可以在执行jar文件时指定这样的类路径吗? (我让类路径回显,看起来很好。)

编辑:

根据http://www.coderanch.com/t/108841/tools/Ant-Compile-time-runtime-classpath我想要实现的目标是不可能的。

1 个答案:

答案 0 :(得分:0)

为什么不尝试构建类路径,然后通过引用将其传递给java执行?在你的&#39; run&#39;里面做这样的事情。目标:

<path id="runtime.classpath">
  <fileset dir="${lib_dir}">
    <include name="*.jar"/>
  </fileset>
  <fileset dir="${build_dir}">
    <include name="*.jar"/>
  </fileset>
</path>
<pathconvert property="classpathForPrinting" refid="runtime.classpath"/>
<echo>Classpath is ${classpathForPrinting}</echo>
<java fork="true" failonerror="true" classname="helloworld.Main">
    <classpath refid="runtime.classpath"/>
</java>