Was this page helpful?

Maven

    Maven 專欄

    使用 Project 資料夾內的 jars

    有時候並不是所有的函式庫都有上傳到 Maven Central Repository,解決辦法除了架設私服之外,還可以在 pom.xml 中指定使用資料夾內的 jar 檔

    <dependency>
        <groupId>org.jgap</groupId>
        <artifactId>JGAP</artifactId>
        <version>3.4.4</version>
        <scope>system</scope>
        <systemPath>${basedir}/lib/jgap-3.4.4.jar</systemPath>
    </dependency>

    ${basedir} 就是 Project 的根目錄

    把dependency打包進一個 jar 檔

    跟 Fat Jar 功能一樣,只要使用 Assembly plugin 就可以完成這項工作,另外也可指定 main class 打包成單一可執行的 jar 檔,只要在 pom.xml 裡面設定 Assembly plugin 的參數就可以了。

    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
            <archive>
                <!--指定 Main Class -->
                <manifest>
                    <mainClass>somepackage.Main</mainClass>
                </manifest>
            </archive>
            <descriptorRefs>
                <!-- 打包需要的 jar -->
                <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
    </plugin>

    設定完成後使用 mvn assembly:assembly 就可以打包出含有依賴又可以執行的 jar 檔

    另外如果 dependency 的 scope 設定為 system 會無法打包,基本上應該有解法,但是我沒找到,所以如果 dependency 不是來自 Central Repository 的話,還是安裝進 Local Repository 會比較簡單。

    參考資料

     

    排除 dependency 中的某個 dependency

    有時 dependency 內還包有其他的 dependency,有時會引用 groupId 跟 artifactId 不同,但事實上是同樣的函式庫,所以要手動排除 dependency 內的 dependency。

    <dependency>
      <groupId>jaxen</groupId>
      <artifactId>jaxen</artifactId>
      <version>1.1.1</version>
        <exclusions>         <exclusion>             <groupId>xerces</groupId>             <artifactId>xmlParserAPIs</artifactId>         </exclusion>     </exclusions>
    </dependency>
    

    像是這個例子,jaxen 本來就有引用了 xml-apis 但,jaxen 內的 xom 又引用了 xmlParserAPIs,但是實際上 xml-apis 跟 xmlParserAPIs 是一樣的東西,所以有時就需要手動排除,至於要排除那一個最好看 dependency  graph 來決定,盡量選依賴較少的 dependency。

    取用不同 JDK 版本的 dependency

    有時候有些 dependency 會有分給 JDK5 or JDK6,像是直接加上 json-lib 在 Maven 會出現 Missing artifact net.sf.json-lib:json-lib:jar:2.3:compile 的錯誤,那是因為  json-lib 有分成 JDK3 跟 JDK5 的版本,要解決這個問題就只要加上 classifier 來指定要用那一個版本的 json-lib。

    <dependency>
        <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.3</version>
        <classifier>jdk15</classifier>
    </dependency>

     

     

     

     


     

    Was this page helpful?
    標籤 (Edit tags)
    • No tags
    blog comments powered by Disqus
    Powered by MindTouch Core