使用 Gradle 创建模块化 SpringBoot 应用程序

问题描述

我正在尝试使用一个 Java 模块设置一个简单的应用程序。有父应用程序和一个名为“功能”的模块。

尽管 IDE 自动完成工作正常,但我在构建过程中不断收到此错误

错误:找不到模块:spring.web

我目前的设置是:

  • Java 12
  • SpringBoot 2.5.0-快照
  • Gradle 6.8.3

我已经使用“gradle modules”完成了十几个其他应用程序,并且我使用的是相同的目录结构:

enter image description here

build.gradle 是这样的:

plugins {
    id 'org.springframework.boot' version '2.5.0-SNAPSHOT'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.mrv'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_11

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

java {
    modularity.inferModulePath = true
}

allprojects {
    apply plugin: 'java'
    apply plugin: 'org.springframework.boot'
    apply plugin: 'io.spring.dependency-management'

    repositories {
        mavenCentral()
        maven { url 'https://repo.spring.io/milestone' }
        maven { url 'https://repo.spring.io/snapshot' }
    }

    dependencies {
        implementation 'org.springframework.boot:spring-boot-starter-web'
    }
}

dependencies {
    implementation project(':feature')
}

功能module-info.java(出现问题的地方)是这样的:

module com.mrv.modules.feature {
    requires spring.web;
}

我以一些 Maven 项目和 Gradle documentation 为基础。我还尝试将我的主类 ModulesApplication 放在它自己的模块中,结果相同。

我错过了什么吗?

解决方法

几个小时后,我找到了解决方案,它非常简单:将 modularity.inferModulePath = true 应用于所有项目:

plugins {
    id 'org.springframework.boot' version '2.5.0-SNAPSHOT'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.mrv'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_11

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

allprojects {
    apply plugin: 'java'
    apply plugin: 'org.springframework.boot'
    apply plugin: 'io.spring.dependency-management'

    repositories {
        mavenCentral()
        maven { url 'https://repo.spring.io/milestone' }
        maven { url 'https://repo.spring.io/snapshot' }
    }

    dependencies {
        implementation 'org.springframework.boot:spring-boot-starter-web'
    }
    
    /* >>>> MOVED HERE <<<<*/
    java {
        modularity.inferModulePath = true
    }

}

dependencies {
    implementation project(':feature')
}

这是一个 sample project,我将来用作参考。