构建使用旧版库的 Java 模块示例
版本 8.13
您可以在支持 Gradle 的 IDE中打开此示例。 |
此示例展示了如何利用工件转换通过向相应的 Jars 添加额外信息,将传统的 Java 库转换为 Java 模块。为此,在 buildSrc
文件夹中定义了一个名为 extra-java-module-info
的插件。此插件可以复制到另一个项目中,并根据需要进行调整,以解决希望将每个依赖项都视为 Java 模块的用例。
该示例定义了一个应用程序,该应用程序依赖于 Maven Central 中的库,其中一些库不是模块。它使用 commons-cli
(非模块)来解析命令行参数,命令行参数可以包含 JSON 字符串,并使用 gson
(一个适当的模块)来解析 JSON 字符串。它还使用了 commons-lang3
(一个自动模块)和 commons-beanutils
(非模块),后者引入了一些额外的依赖项,这些依赖项也不是模块。
通过配置我们自己的 extra-java-module-info
插件,我们添加信息以将旧版库转换为模块。
application/build.gradle.kts
extraJavaModuleInfo {
// This does not have to be a complete description (e.g. here 'org.apache.commons.collections' does not export anything here).
// It only needs to be good enough to work in the context of this application we are building.
module("commons-beanutils-1.9.4.jar", "org.apache.commons.beanutils", "1.9.4") {
exports("org.apache.commons.beanutils")
requires("org.apache.commons.logging")
requires("java.sql")
requires("java.desktop")
}
module("commons-cli-1.4.jar", "org.apache.commons.cli", "3.2.2") {
exports("org.apache.commons.cli")
}
module("commons-collections-3.2.2.jar", "org.apache.commons.collections", "3.2.2")
automaticModule("commons-logging-1.2.jar", "org.apache.commons.logging")
}
application/build.gradle
extraJavaModuleInfo {
// This does not have to be a complete description (e.g. here 'org.apache.commons.collections' does not export anything here).
// It only needs to be good enough to work in the context of this application we are building.
module('commons-beanutils-1.9.4.jar', 'org.apache.commons.beanutils', '1.9.4') {
exports('org.apache.commons.beanutils')
requires('org.apache.commons.logging')
requires('java.sql')
requires('java.desktop')
}
module('commons-cli-1.4.jar', 'org.apache.commons.cli', '3.2.2') {
exports('org.apache.commons.cli')
}
module('commons-collections-3.2.2.jar', 'org.apache.commons.collections', '3.2.2')
automaticModule('commons-logging-1.2.jar', 'org.apache.commons.logging')
}
您可以像这样运行示例应用程序
run --args='-json {"message":"Hello","receivers":["Lisa","John"]} -debug'