IntelliJ IDEA 匯入maven專案並將它及依賴打成jar包

shuaishuai3409發表於2017-01-13

IDEA匯入MAVEN專案:

IntelliJ IDEA14之後的版本,沒有import project選項,需要在File-New-Project form existing sources,然後基本就都知道咋弄了,然後勾上Import maven projects automatically選項,接下來要把SDK配置好,即找到jdk1.8的位置,最後確認。然後系統會自動下載依賴包,在依賴包下載完之前,整個專案結構是不會顯示出來的,所以即使沒有看到專案目錄也不要著急,等到下載完後,就可以用了。

當有properties檔案時,剛剛匯入後,專案可能找不到它,這時需要右鍵resource資料夾,然後選擇mark directory as–Resources root,這樣就可以成功找到配置檔案了。


IDEA將maven專案打成jar包:
首先要在pom裡<dependencies><repositories>間增加<bulid>屬性,build配置資訊如下。

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            <overWriteReleases>false</overWriteReleases>
                            <overWriteSnapshots>false</overWriteSnapshots>
                            <overWriteIfNewer>true</overWriteIfNewer>
                            <excludeScope>provided</excludeScope>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

這是打maven的jar包必不可少的操作。

然後File-Project Structure-Artifacts-JAR-From modules with dependencies…-
在Main Class視窗找到主類名,如果有多個主類(多個包存在),沒關係,隨便選擇一個就好,然後就一直OK下去。

接下來要Build-Build Artifacts-Action-Build/Rebuild/Clean,第一次要選擇Build,這樣就會在專案的根目錄下生成jar包,然後就可以在控制檯執行了。

對於這種含有多個包的類,執行時-jar的命令不好用。建議使用,jar -cp命令:
java -cp jar名.jar 包名.類名 [引數列表]

相關文章