我们现在java项目用的build工具是ant, 虽然也知道还有一个maven, 而且现在用的人越来越多, 但是偷懒不愿去深入看。
不过maven中的dependency功能还是很好,一直希望ant也有这么个功能就好了。
今天,无意中去Apache Ant的主页, 结果就看到了Ivy2。
Ivy以前也听说过,不过一直没有尝试去用. 今天看到了就小试了一下。
Ivy的安装
Ivy的安装很容易, 下载之后只要将Ivy的jar文件放到Ant的lib目录就可以了。
http://ant.apache.org/ivy/history/latest-milestone/install.html
当然, 如果你用的是ant1.5, 那么安装就稍微麻烦一点。
Ivy 小试
Ivy的src目录下有一些example:
apache-ivy-2.0.0-beta1\src\example\hello-ivy
命令行下进入上述目录, 然后ant
执行结束, 就可以发现多了lib和build的目录以及里面的内容。
打开ivy.xml, 可以看到两个个dependency的定义。<ivy-module version="2.0">
<info organisation="org.apache" module="hello-ivy"/>
<dependencies>
<dependency org="commons-lang" name="commons-lang" rev="2.0"/>
<dependency org="commons-cli" name="commons-cli" rev="1.0"/>
</dependencies>
</ivy-module>
到lib目录下看, 有三个jar文件
commons-cli-1.0.jar
commons-lang-2.0.jar
commons-logging-1.0.jar
这些就是从repository复制/下载下来的jar文件。
以后就不用手工去copy那么多的jar了,而且还不知道是否真的用到,管理起来也太麻烦。
这下好了, 有了Ivy看来可以稍微轻松一点了, 唯一要投资的就是Ivy的学习时间。
Ivy Dependency
关于dependency,从英文文档翻译一下, 简单来说:
Ivy默认使用maven 2的repository。要设置dependency中的属性值,需要知道library的确切信息。
mvnrepository.com上可以找到library以及他们的详细信息。一旦你找到了你需要的类库, 就可以找到这些类库在Maven2的POM文件中dependency的信息。
把Maven2的dependency转换为Ivy的dependency,你只要把groupId作为organization, 把artifactId作为module name, version作为revision。
http://ant.apache.org/ivy/history/latest-milestone/tutorial/start.html
Section: The build.xml file
Tutorials: http://ant.apache.org/ivy/history/latest-milestone/tutorial.html
Ant tasks: http://ant.apache.org/ivy/history/latest-milestone/ant.html
Ant build.xml
要查看ant build文件中的所有target, 只要在命令行下输入"ant -P" 就可以了。
下面是hello-ivy的build.xml片段: <project xmlns:ivy="antlib:org.apache.ivy.ant" name="hello-ivy" default="run">
...
<!-- =================================
target: resolve
================================= -->
<target name="resolve" description="--> retrieve dependencies with ivy">
<ivy:retrieve />
</target>
</project>可以看到,revole和retrieve dependency很简单,只要你正确安装Ivy,然后在build.xml中定义一个namespace, 所有Ivy ant task就全部可用了。xmlns:ivy="antlib:org.apache.ivy.ant"如果没有任何设置, Ivy会从maven2 的repository获取文件. resove task 在maven 2 repository中找到了 commons-lang 和 commons-cli, 并且获知 commons-cli依赖于 commons-logging, 所以也会主动把common-logging下载下来。
Ivy默认会先把相应的文件放到它的cache中 (默认是user home/.ivy2/cache目录)。
最后,resolve task会将相关的jar文件都copy到项目的library目录 (默认是lib目录, 不过你可以很方便的修改, 只要设置retrieve task的属性)。