網頁

2019/2/10

使用SpringBoot打造記帳簿專案(二十一)打包Spring Boot專案為可執行的jar檔

本篇說明如何將專案打包成可執行的jar檔。

使用SpringBoot打造記帳簿專案(二十)MyBatis測試中完成了MyBatis的設定及測試。

因為要打包成可執行的jar檔,所以pom.xml<packaging>要設成jar

將Spring Boot打包成可執行jar需要spring-boot-maven-plugin,這在之前的文章中就已經設定好了,但還要設定執行mvn package的goal為repackage,其作用為將原本的jar重新打包成可執行的jar(executable jar)

<build>
    ...
    <plugins>
        ...
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
            <!-- 執行package時改執行repackage goal -->
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        ...
    </plugins>
    ...
</build>

完成上面配置後,當執行mvn package進行打包時,會產生一個可執行jar與原本的jar。


另外要設定Maven resource的來源。Maven預設會讀取src/main/resources下的靜態資源,但因為在之前用MyBatis Generator產生MyBatis的XML Mapper時,是放在src/main/java下的idv.matt.mapper中,雖然在Eclipse編譯時會讀取並輸出至classes目錄,但Maven編譯時並不會,詳情請參考Maven test Mybatis Binding Invalid bound statement錯誤

<build>
...
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>idv/matt/mapper/*.xml</include>
            </includes>
        </resource>
    </resources>
...
</build>

pom.xml最終修改如下。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.0.BUILD-SNAPSHOT</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>idv.matt</groupId>
    <artifactId>moneynote</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging><!-- 改成jar -->
    <name>moneynote</name>
    <description>moneynote</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- log4j2 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <!-- 設定repackage goal -->
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <!-- 設定resources -->
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>idv/matt/mapper/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
    
    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>

</project>

修改完存檔後若出現Project configuration is not up-to-date with pom.xml. Run project configuration update錯誤,則在專案上點滑鼠右鍵 -> Maven -> Update Project... > 點選OK來更新Maven專案(Maven Update)。

又因為將pom.xml<packaging>設為jar,所以執行Maven Update後可能出現Classpath entry org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER will not be exported or published. Runtime ClassNotFoundExceptions may result警告


完成以上設定後就可以開始進行打包了,在專案上點選滑鼠右鍵 -> Run As -> Run Configurations -> 在Maven Build上點滑鼠右鍵 -> New Configuration新增專案的Maven執行設定。

[Name]欄位輸入要執行的Maven動作名稱;
[Base dirctory]欄位確認為${project_loc:moneynote}
[Goal]欄位輸入要執行的指令參數,輸入clean package -Dmaven.test.skip=true,意思是「清除之前建置的檔案,執行打包,並略過test (及test-compile)」;
[Profile]欄位清空;
其餘欄位保持預設。


輸入完以上後,點選Apply,然後點選RunMaven就會開始將專案打包成可執行的jar。


輸入-Dmaven.test.skip=true參數來略過test的原因是,在之前的使用SpringBoot打造記帳簿專案(二十)MyBatis測試寫了一支idv.matt.dao.MemberMapperTest測試MyBatis Mapper存取資料庫的測試程式,若不略過test則打包時會執行此測試步驟,若資料庫無法連線或是測試邏輯不通過就會Build Fail導致無法完成打包。

但是-Dmaven.test.skip=true除了略過測試test的執行,也略過了測試程式編譯test-compile,因此若建置或打包過程中有輸入-Dmaven.test.skip=true參數,之後要在Eclipse中執行測試程式時,要執行clean compile test-compile重新編譯程式。

或是參數改用clean package -DskipTests,這樣打包時也不會執行test,但仍會執行執行測試程式的編譯test-compile

或者直接把idv.matt.dao.MemberMapperTest先刪除,然後直接執行clean package


打包結束後重新整理專案目錄,在專案根目錄下的target資料夾中可以看到moneynote-0.0.1-SNAPSHOT.jar,此即為spring-boot-maven-plugin重新打包的可執行jar檔;另外一個moneynote-0.0.1-SNAPSHOT.jar.original則為原本的jar檔。



接著開啟命令提示字元介面並移動到專案的target目錄

然後輸入下面指令執行:

java -jar moneynote-0.0.1-SNAPSHOT.jar

執行訊息如下:

D:\moneynote\workspace\moneynote\target>java -jar moneynote-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v2.2.0.BUILD-SNAPSHOT)

[2019-02-11 01:36:01,941][INFO][idv.matt.application.MoneynoteApplication:50] - Starting MoneynoteAp
plication v0.0.1-SNAPSHOT on matt-PC with PID 4684 (D:\moneynote\workspace\moneynote\target\moneynot
e-0.0.1-SNAPSHOT.jar started by matt in D:\moneynote\workspace\moneynote\target)
[2019-02-11 01:36:01,955][INFO][idv.matt.application.MoneynoteApplication:675] - No active profile s
et, falling back to default profiles: default
[2019-02-11 01:36:06,721][INFO][org.springframework.boot.web.embedded.tomcat.TomcatWebServer:90] - T
omcat initialized with port(s): 8080 (http)
[2019-02-11 01:36:06,769][INFO][org.apache.coyote.http11.Http11NioProtocol:173] - Initializing Proto
colHandler ["http-nio-8080"]
[2019-02-11 01:36:06,816][INFO][org.apache.catalina.core.StandardService:173] - Starting service [To
mcat]
[2019-02-11 01:36:06,821][INFO][org.apache.catalina.core.StandardEngine:173] - Starting Servlet engi
ne: [Apache Tomcat/9.0.14]
[2019-02-11 01:36:06,884][INFO][org.apache.catalina.core.AprLifecycleListener:173] - The APR based A
pache Tomcat Native library which allows optimal performance in production environments was not foun
d on the java.library.path: [D:\Applications\Java\jdk.1.8.0_171\bin;C:\Windows\Sun\Java\bin;.......]
[2019-02-11 01:36:07,156][INFO][org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/moneyn
ote]:173] - Initializing Spring embedded WebApplicationContext
[2019-02-11 01:36:07,157][INFO][org.springframework.web.context.ContextLoader:296] - Root WebApplica
tionContext: initialization completed in 5059 ms
[2019-02-11 01:36:09,173][INFO][org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor:171
] - Initializing ExecutorService 'applicationTaskExecutor'
[2019-02-11 01:36:09,571][INFO][org.springframework.boot.autoconfigure.web.servlet.WelcomePageHandle
rMapping:56] - Adding welcome page: class path resource [static/index.html]
[2019-02-11 01:36:10,155][INFO][org.apache.coyote.http11.Http11NioProtocol:173] - Starting ProtocolH
andler ["http-nio-8080"]
[2019-02-11 01:36:10,251][INFO][org.springframework.boot.web.embedded.tomcat.TomcatWebServer:204] -
Tomcat started on port(s): 8080 (http) with context path '/moneynote'
[2019-02-11 01:36:10,289][INFO][idv.matt.application.MoneynoteApplication:59] - Started MoneynoteApp
lication in 8.989 seconds (JVM running for 10.566)

等訊息停止後,開啟瀏覽器輸入http://localhost:8080/moneynote/hello,正確的話會返回hello moneynote的訊息畫面。


如要停止執行Spring Boot jar則直接在命令提示字元按Ctrl + C跳離。


接著請參考使用SpringBoot打造記帳簿專案(二十二)修改Spring Boot版本


參考:

沒有留言:

張貼留言