我正在尝试将多模块项目构建过程从Ant转换为Gradle。 我们有一个通用模块,每个其他模块都使用它。在通用模块中,我需要这些依赖项才能编译它(通过gradle build)
dependencies {
api 'com.google.guava:guava:18.0'
api 'org.json:json:20131018'
implementation 'org.apache.httpcomponents:httpclient:4.5.5'
implementation 'org.jruby:jruby-complete:1.5.1'
implementation 'org.python:jython:2.2.1'
implementation 'com.google.code.gson:gson:2.6.2'
}
某些模块应包含结果jar文件中运行时所需的所有依赖项。因此,我也将模块依赖项的代码添加到jar文件中。如下所示:
dependencies {
compile project(':core:common')
compile project(':core:installer')
}
jar {
from sourceSets.main.output
from project(':core:common').sourceSets.main.output
from project(':core:installer').sourceSets.main.output
}
问题是我想要将外部库添加到jar文件中,以便我有一个complete jar文件。可以通过在jar上面添加一行来添加外部库,如下所示:
jar {
from sourceSets.main.output
from project(':core:common').sourceSets.main.output
from project(':core:installer').sourceSets.main.output
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}
但是我会有一个包含普通模块中所有依赖项的大型jar文件,而在我的特定jar文件中不需要其中一些。我想要的是为jar文件添加特定的外部库,例如我想添加' org.json:json:20131018'和' org.apache.httpcomponents:httpclient:4.5.5'到库并忽略其余的依赖项。我无法找到解决方案。
答案 0 :(得分:0)
I solved this by adding the code below to jar:
jar {
from sourceSets.main.output
from project(':core:common').sourceSets.main.output
from project(':core:installer').sourceSets.main.output
def libraries =['httpclient-4.5.5.jar','json-20131018.jar']
from configurations.runtimeClasspath.
findAll { libraries.contains(it.name)}.
collect { zipTree(it) }
}
But I think that still Gradle should offer a better solution to include or exclude external libraries to jar file.
I updated solution above little bit which I think it is a better way to do this because we don't need specify jar files. We can define a configuration like this:
configurations {
runtimeLibraries
}
dependencies {
compile project(':core:common')
compile project(':core:installer')
runtimeLibraries 'org.apache.httpcomponents:httpclient:4.5.5', 'org.json:json:20131018'
}
Then we can update Jar task as below:
jar {
from sourceSets.main.output
from project(':core:common').sourceSets.main.output
from project(':core:installer').sourceSets.main.output
from configurations.runtimeLibraries.collect { zipTree(it) }
}
One diffference in result of those two methods is that with defining configuration gradle will recognize needed dependency and will add them to jar as well. For example if you are using commons-net:commons-net:1.4.1 as part of runtimeLibraries in created jar files you can find org.apache.oro packages which is used by commons-net