【问题标题】:Maven Loading file from dependency jar src/main/resourcesMaven 从依赖项 jar src/main/resources 加载文件
【发布时间】:2015-05-07 16:15:27
【问题描述】:

我有一个 Spring Web 应用程序,它是作为 maven 工件 A.war 创建的。它具有与工件 B.jar 的 Maven 依赖项。 工件 B 的 src/main/resources 有一个文件 test.txt。我想从工件 A.war 中读取文件 test.txt。 当我分解 B.jar 时,我看到 test.txt 位于 jar 的根目录中。 B.jar 最终在爆炸的 A.war 的 WEB-INF/lib 中 在 A 中,我尝试使用 文件 f = new ClassPathResource("test.txt").getFile();

我收到 java.io.FileNotFoundException:类路径资源 [test.txt] 无法解析为绝对文件路径,因为它不在文件系统中:jar:B.jar!/test.txt。 我也试过 文件 f = new File(getClass().getResource("test.txt").toURI());

有人可以帮忙吗?

【问题讨论】:

标签: spring maven


【解决方案1】:

我终于通过遵循中提到的替代路径让它工作了 link

基本上在Artifact A的pom文件中,我使用了maven依赖插件和unpack target。使用它,我解压缩了工件 B 并将 test.txt 复制到项目 A 的 target/classes 目录中。

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>unpack</id>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>unpack</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>com.me</groupId>
                                <artifactId>artifactB</artifactId>
                                <version>1.0-SNAPSHOT</version>
                                <outputDirectory>${basedir}/target/classes</outputDirectory>
                                <includes>*.txt,*.xml</includes>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

在构建工件 A 时,会创建 war 文件 A.war,并且 test.txt 出现在分解后的 war 文件的 WEB-INF/classes 目录中,因此它位于类路径中。

【讨论】:

    【解决方案2】:

    您必须为类路径资源构建自己的类加载器才能从 jar 中读取文件。

    我在我的博文中解释过 (https://skmit.wordpress.com/2012/02/29/read-classpath-resource-from-jar-files-with-spring/)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-11
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 2011-05-21
      • 2015-02-26
      相关资源
      最近更新 更多