Eclipse「Export → JAR file」默認不包含依賴庫,且 Spring 配置文件(META-INF/spring.factories、applicationContext.xml)若未放入 JAR 根目錄,類路徑掃描失敗,導致 Bean 找不到。
<!-- pom.xml -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
</archive>
</configuration>
</plugin>
<!-- 關鍵:複製依賴到 target/lib -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals><goal>copy-dependencies</goal></goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
執行 mvn clean package 產出 target/your-module.jar 與 target/lib/*.jar。
mvn deploy # 需配置 distributionManagement
下游項目直接添加坐標依賴,自動傳遞傳遞依賴,無需手動複製 JAR。
your-module.jar 複製到下游項目 lib/ 目錄。target/lib/*.jar 也一同複製(或配置 Maven 系統作用域依賴)。META-INF/ 或 classpath*:/spring/** 下。<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals><goal>shade</goal></goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.example.Main</mainClass>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.factories</resource>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
產出單一可執行/可依賴的 *-shaded.jar,包含所有依賴類並合併 spring.factories。