首页 > 解决方案 > GetResource 方法在 java 11 中不起作用

问题描述

这是我的项目结构: 在此处输入图像描述

这是我的模块信息:

open module org.client.main {
    exports org.apj.client.app;
    requires javafx.controls;
    requires javafx.base;
    requires javafx.fxml;
    requires spring.context;
    requires spring.web;
    requires java.sql;
    requires spring.beans;
    requires spring.core;
}

这是我的父 gradle 构建文件:

subprojects {
    afterEvaluate {
        repositories {
            jcenter()
        }

        compileJava {
            doFirst {
                options.compilerArgs = [
                        '--module-path', classpath.asPath,
                ]
                classpath = files()
            }
        }

        compileTestJava {
            inputs.property("moduleName", moduleName)
            doFirst {
                options.compilerArgs = [
                        '--module-path', classpath.asPath,
                        '--add-modules', 'junit',
                        '--add-reads', "$moduleName=junit",
                        '--patch-module', "$moduleName=" + files(sourceSets.test.java.srcDirs).asPath,
                ]
                classpath = files()
            }
        }

        test {
            inputs.property("moduleName", moduleName)
            doFirst {
                jvmArgs = [
                        '--module-path', classpath.asPath,
                        '--add-modules', 'ALL-MODULE-PATH',
                        '--add-reads', "$moduleName=junit",
                        '--patch-module', "$moduleName=" + files(sourceSets.test.java.outputDir).asPath,
                ]
                classpath = files()
            }
        }
    }
}

这是我的客户端模块构建文件:

plugins {
    id 'java'
}

group 'APJ'
version '1.0-SNAPSHOT'

sourceCompatibility = 11

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'org.springframework', name: 'spring-webmvc', version: '5.1.4.RELEASE'
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

ext.moduleName = 'org.client.main'

我正在尝试为 FXMLLoader 获取资源,但我根本无法让它工作。我已经挣扎了2个小时,现在我真的很绝望。我已经尝试过所有可能的文件名组合、每个可能的位置,但它仍然返回 null。

我也试过ClassLoader.getSystemClassLoader().getResource("/login.fxml") getClass().getResource("/login.fxml") 但它也不起作用。

有人可以帮我弄这个吗 ?我会很感激。

标签: javajavafxresources

解决方案


我注意到 Java 11 有 2 个选项可以使 getResource 工作:

  1. 使用插件'org.openjfx.javafxplugin' version '0.0.7'
  2. 在上面 Slaw 提供的链接中使用“--patch-module”:资源文件在构建 Java 9 模块的 Gradle 项目中位于何处?

    run {
    doFirst {
        jvmArgs = [
                '--module-path', classpath.asPath,
                '--patch-module', "$moduleName=" + files(sourceSets.main.output.resourcesDir).asPath,
                '--module', mainClassName
        ]       
    }
    }
    

推荐阅读