有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVA当maven打包为pom时,getResource(“/filename”)返回null

我有一个带有子模块的Maven项目,使用Java11在IntelliJ中开发

除非是pom。xml文件包含<packaging>pom</packaging>,有一个警告

'packaging' with value 'jar' is invalid. Aggregator projects require 'pom' as packaging.

但是当packaging设置为“pom”时,我需要的资源文件无法加载;返回空值,并引发异常。从main()方法:

    URL resource = getClass().getResource("/fx/gui.fxml");
    Objects.requireNonNull(resource);

另一方面,有时子模块找不到,除非我要求pom打包。然后我要做的是:请求pom打包,启动程序并看着它失败,从pom中删除pom打包语句。xml,重新开始,程序就会工作

我的资源文件位于标准位置src/main/resources/fx/gui.fxml。pom文件中也给出了该位置:

<build>
    <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
    <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
    <resources>
        <resource>
            <directory>${project.basedir}/src/main/resources</directory>
        </resource>
    </resources>
</build>

请帮我了解发生了什么事。我需要pom包装吗?如何装载资源


共 (2) 个答案

  1. # 1 楼答案

    看起来你的源代码在你的父母pom中

    父pom(带有子模块)必须打包为pom,并且不能有java源代码。见this question

    您应该将代码移动到新的子模块中

  2. # 2 楼答案

    包含源代码的项目或模块必须按照您的要求打包为jar/war。它不能包装成pom。通常,当您有多模块项目结构时,pom打包与父模块一起使用,子模块将打包为jar/war。因此,在您的情况下,如果您有多模块项目结构,那么父包将是“pom”,并且所有子模块(包含源代码)都必须有jar/war。注意:您的父模块不应该有源代码,如果是,请将源代码移动到子模块。多模块项目结构基本上用于存在公共依赖项的地方,并且工件可以在多个子模块中使用,这样就可以消除重复。 如下图所示

    parent 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>
    
        <groupId>org.abc.test</groupId>
        <artifactId>testartifact</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <packaging>pom</packaging>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
         <modules>
            <module>rest-services</module>
         </modules>
    
    </project>
    
    Submodule pom.xml
    
    <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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <parent>
            <groupId>org.abc.test</groupId>
            <artifactId>testartifact</artifactId>
            <version>1.0.0-SNAPSHOT</version>
        </parent>
    
        <artifactId>rest-services</artifactId>
        <name>rest-services</name>
     
        <dependencies>
            <dependency>
            </dependency>
        </dependencies>
    
     </project>