最近一個項目中,使用號稱下一代構建工具的Gradle構建項目。
使用中發現一個問題,Gradle從中央庫下載的jar文件在系統的其它目錄,使用gradle eclipse添加Eclipse支持時,jar文件是以外部依賴的形式導入的。Eclipse將web項目發布到Tomcat時,是不會自動發布這些依賴的。
可以通過Eclipse在項目上右擊 - Propertics - Deployment Assembly,添加“Java Build Path Entries”,添加所有依賴的jar包,就可以在發布時自動發布外部依賴的jar包。
但是手動添加,是不符合自動化構建的要求的,打開.classpath文件,發現gradle自動生成的文件含有類似如下的代碼
<classpathentry
sourcepath="C:/Documents and Settings/XXX/.gradle/caches/artifacts-24/filestore/commons-collections/commons-collections/3.2/source/73d0340eaecbb0ec9d3e0ace90547ef08cbfaf27/commons-collections-3.2-sources.jar"
kind="lib"
path="C:/Documents and Settings/XXX/.gradle/caches/artifacts-24/filestore/commons-collections/commons-collections/3.2/jar/f951934aa5ae5a88d7e6dfaa6d32307d834a88be/commons-collections-3.2.jar"
exported="true" />
在Eclipse中設置好Deployment Assembly后,代碼變為這樣
<classpathentry sourcepath="C:/Documents and Settings/XXX/.gradle/caches/artifacts-24/filestore/commons-collections/commons-collections/3.2/source/73d0340eaecbb0ec9d3e0ace90547ef08cbfaf27/commons-collections-3.2-sources.jar" kind="lib" path="C:/Documents and Settings/XXX/.gradle/caches/artifacts-24/filestore/commons-collections/commons-collections/3.2/jar/f951934aa5ae5a88d7e6dfaa6d32307d834a88be/commons-collections-3.2.jar" exported="true"> <attributes> <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib" /> </attributes> </classpathentry>
這樣就簡單了,我們讓gradle自動添加Deployment Assembly
在gradle.build中添加下面的代碼
// 生成Eclipse支持時,自動生成Deployment Assembly eclipse.classpath.file.withXml { def node = it.asNode(); for (Node n : node.children()) { if ("lib".equals(n.attribute("kind"))) { def node_attributes = new Node(n, "attributes"); def map = new HashMap(); map.put("name", "org.eclipse.jst.component.dependency"); map.put("value", "/WEB-INF/lib"); def node_attribute = new Node(node_attributes, "attribute", map); } } }
保存以后重新運行gradle eclipse,回到Eclipse刷新項目,現在發布項目,就能自動將所有外部依賴jar包發布到Tomcat下