首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Eclipse 導出 Spring 擴展項目為 JAR 後依賴報錯:正確打包與發布流程

     編輯:程式設計綜合問答

問題根因

Eclipse「Export → JAR file」默認不包含依賴庫,且 Spring 配置文件(META-INF/spring.factories、applicationContext.xml)若未放入 JAR 根目錄,類路徑掃描失敗,導致 Bean 找不到。

正確方案:Maven/Gradle 打包

<!-- 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。

發布到私有 Maven 倉庫(推薦)

mvn deploy  # 需配置 distributionManagement

下游項目直接添加坐標依賴,自動傳遞傳遞依賴,無需手動複製 JAR。

若必須手動複製

  1. 將 your-module.jar 複製到下游項目 lib/ 目錄。
  2. 將 target/lib/*.jar 也一同複製(或配置 Maven 系統作用域依賴)。
  3. 確保 Spring 配置文件在 JAR 的 META-INF/ 或 classpath*:/spring/** 下。

Eclipse 專屬替代:Fat JAR (Shade Plugin)

<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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved