简体   繁体   English

如何使用Gradle从已编译的类创建其他jar工件?

[英]How do you create additional jar artifacts from compiled classes using Gradle?

I can't tell if this is a bug with Gradle 1.0m7, or if we are just doing this wrong. 我不知道这是Gradle 1.0m7的错误,还是我们只是做错了。

We have some classes that get compiled as apart of a project, that we want to individually jar into it's own artifact. 我们有一些类被编译为项目的一部分,我们希望将它们单独地放入它自己的工件中。 These are for example standalone domain model objects, that we want to share with another project. 这些是例如我们想要与另一个项目共享的独立域模型对象。

I'd prefer not to go the multi-project build route, so how do we tell Gradle to create another jar for these? 我不想去多项目构建路线,那么我们如何告诉Gradle为这些创建另一个jar?

Currently we are doing this: 目前我们这样做:

task modelJar(type: Jar) {
    classifier = 'model'
    from fileTree(dir: sourceSets.main.classesDir).matching { include 'com/foo/bar/model/**' }
}

artifacts {
    archives modeljar
}

The issue here, is the modeljar task runs before the classes are compiled. 这里的问题是modeljar任务编译类之前运行。 At first we didn't realise this and thought this was working. 起初我们没有意识到这一点,并认为这是有效的。 Turns out, the artifact was picking up classes from the previous run, not the current run. 事实证明,工件正在从上一次运行中获取类,而不是当前运行。 Doing clean before the build results in a jar with no classes in it, and reveals the problem. 在构建之前执行clean会导致jar中没有类,并显示问题。

I was looking at custom configuration, but it seems pretty complex and I didn't want to overly complicate the build file. 我在看自定义配置,但它似乎相当复杂,我不想过度复杂的构建文件。

Appreciate any advice. 感谢任何建议。

Thanks. 谢谢。

the most convenient way to do this is 最方便的方法是

task modelJar(type: Jar) {
    classifier = 'model'
    from sourceSets.main.output
    include 'com/foo/bar/model/**'
}

Some background: sourceSets.main.output is a buildable filecollection. 一些背景知识:sourceSets.main.output是一个可构建的文件集合。 This means that if a task works with this file collection, gradle knows that this file collection must be created before another task can use it. 这意味着如果任务使用此文件集合,则gradle知道必须先创建此文件集合,然后其他任务才能使用它。 in this particular case, sourcesets.main.classes is wired to the classes task of the java plugin. 在这种特殊情况下,sourcesets.main.classes连接到java插件的classes任务。 Therefore you your modelJar task does not need to depend on the classes task explicitly. 因此,您的modelJar任务不需要明确依赖于类任务。

How about making modelJar task depend on classes (built-in) task? 如何使modelJar任务依赖于classes (内置)任务? This should make sure compilation is done before modelJar task. 这应该确保在modelJar任务之前完成编译。

task modelJar(dependsOn: classes, type: Jar){
  ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM