如何使用JavaExec任务将Java代码嵌入Gradle构建 [英] How to embed Java code into Gradle build using JavaExec task

查看:727
本文介绍了如何使用JavaExec任务将Java代码嵌入Gradle构建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Gradle驱动的项目,我想向其中添加一个简单的Java任务.这个任务是非常特定于项目的,如果可以得到帮助,我不想将其开发为单独的插件.所以问题是我可以在用于项目的同一build.gradle中定义此类自定义任务吗?还是不可避免地需要将其打包为一个单独的项目(插件)并安装到本地存储库中?

I have a Gradle-driven project to which I want to add a simple Java task. This task is very specific to the project and if it can be helped I don't want to develop it as a separate plugin. So the question is can I define such custom task within the same build.gradle I'm using for my project? Or is it inevitable that I need to package it as a separate project (plugin) and install to the local repo?

另外,可能很重要的一点是,原始项目与Java不相关(无需构建其他Java代码)

Also it's probably important to note that the original project is not Java related (no other Java code needs to be build)

P.S.根据以下评论:

P.S. Based on comments below:

我想将src/main/java/SomeUsefulStuff.java添加到现有项目中,并编译该文件并将其用作自定义任务.我确实知道,每次运行构建时都需要对其进行编译,但是要再次编译-代码将很小.但是它将具有一些外部依赖项,例如Commons IO

I would like to add src/main/java/SomeUsefulStuff.java to the existing project and have that file compiled and used as a custom task. I do understand that it needs to be compiled each time I run the build but again - the code will be small. However it will have some external dependencies such as Commons IO

推荐答案

感谢 RaGe 指出了JavaExec,变得非常简单.这是您的工作:

Thanks to RaGe who pointed to JavaExec this turned out to be pretty simple. Here's what you do:

  1. 就像在常规Gradle驱动的Java项目中一样,将Java代码放在/src/main/java中.确保它在您要调用的文件中具有 main 方法
  2. apply plugin: 'java'添加到 build.gradle
  3. 如果您的Java代码对第三方库具有任何依赖关系,请将其添加到依赖关系部分
  4. 像这样将新任务部分添加到 build.gradle :
  1. Put your Java code in /src/main/java just as you would in the regular Gradle-driven Java project. Make sure it has main method in the file you are going to call
  2. Add apply plugin: 'java' to the build.gradle
  3. If your Java code has any dependencies on 3rd party libs add these to dependencies section
  4. Add new task section to build.gradle like so:

task usefulStuff(type: JavaExec) {
      classpath = sourceSets.main.runtimeClasspath
      main = 'com.me.gradle.UsefulStuff'
      // arguments to pass to the application
      args 'OhmyGod!'
    }

  1. 现在,您可以将该任务称为构建中的任何任务.例如imporantTask.dependsOn usefulStuff

这篇关于如何使用JavaExec任务将Java代码嵌入Gradle构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆