Guide to JBang – JBang指南

最后修改: 2021年 12月 24日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this tutorial, we look at JBang.

在本教程中,我们看看JBang

JBang lets Students, Educators, and Professional Developers create, edit and run self-contained source-only or binary Java programs with unprecedented ease. JBang’s goal is to reduce or even remove the ceremony and tedious setup that everyone is so used to around Java.

JBang让学生、教育工作者和专业开发人员创建、编辑和运行独立的纯源码或二进制Java程序,并以前所未有的轻松。JBang的目标是减少甚至去除每个人都习惯的围绕Java的仪式和繁琐的设置

We can enable JBang with just one download and one command to create, edit and run Java as easy as Python, JavaScript, PHP, and similar languages.

我们只需一个下载和一个命令就可以启用JBang,创建、编辑和运行Java,就像Python、JavaScript、PHP和类似语言一样简单。

On its surface, JBang looks like the Launch Single-File Source-Code feature introduced in Java 11. However, JBang goes beyond this by supporting multiple files using dependencies from any Maven compatible repository, and it works with Java 8 up to the recently released Java 17 and beyond.

从表面上看,JBang就像Java 11中引入的启动单文件源代码功能。然而,JBang超越了这一点,它支持使用来自任何Maven兼容库的依赖关系的多个文件,它适用于Java 8,直到最近发布的Java 17及以后

2. Installing JBang

2.安装JBang

The first thing to do is to install JBang.

要做的第一件事是安装JBang。

We can use our package manager of choice for our OS or use the more generic curl/iex based download. We can find download instructions for all major operating systems at jbang.dev/download. In this guide, we’ll use the generic approach:

我们可以使用我们的操作系统选择的软件包管理器,或者使用更通用的基于curl/iex的下载。我们可以在jbang.dev/download找到所有主要操作系统的下载说明。在本指南中,我们将使用通用方法。

On Linux, Mac, or Windows with a bash compatible shell, we can use curl:

在Linux、Mac或Windows的bash兼容的shell上,我们可以使用curl。

curl -Ls https://sh.jbang.dev | bash -s - app setup

or on Windows using PowerShell, we can use iex:

或者在Windows上使用PowerShell,我们可以使用iex。

iex "& { $(iwr https://ps.jbang.dev) } app setup"

In both cases, something like the following prints when running on a new system:

在这两种情况下,当在新系统上运行时,都会打印出类似以下内容。

$ curl -Ls https://sh.jbang.dev | bash -s - app setup
Downloading JBang...
Installing JBang...
Downloading JDK 11. Be patient, this can take several minutes...
Installing JDK 11...
[jbang] Default JDK set to 11
[jbang] Setting up Jbang environment...
Please start a new Shell for changes to take effect

We’ll notice we do not need to have Java installed to get started – JBang will download a Java Development Kit (JDK) from adoptopenjdk (now Eclipse Adoptium) when required.

我们会注意到,我们不需要安装Java就可以开始了–JBang会在需要时从adopenjdk(现在的Eclipse Adoptium)下载一个Java开发包(JDK)。

To check if JBang is installed properly, start a new shell and run jbang version. JBang will print out the version info (note: JBang releases often, so the version might already be higher):

要检查JBang是否正确安装,启动一个新的shell并运行 jbang version. JBang会打印出版本信息(注意:JBang经常发布,所以版本可能已经比较高了)。

$ jbang version
0.83.1

Now we’re ready to get started using JBang.

现在我们准备开始使用JBang了。

3. Our First Java (Script)

3.我们的第一个Java(脚本)

To create our first Java file, we can use jbang init:

为了创建我们的第一个Java文件,我们可以使用 jbang init

$ jbang init hello.java
[jbang] File initialized. You can now run it with 'jbang hello.java' or edit it using 'jbang edit --open=[editor] hello.java' where [editor] is your editor or IDE, e.g. 'netbeans'

We can now run this with jbang hello.java or ./hello.java if our shell permits. Let’s try to run it twice:

现在我们可以用jbang hello.java或者./hello.java(如果我们的shell允许的话)来运行它。让我们试着运行它两次。

./hello.java
[jbang] Building jar...
Hello World
❯ ./hello.java
Hello World

There we go – creating and running java without setting up build tools or even compilation. All handled by JBang. Notice how it prints “Building jar” first but not the second time. The second time it just prints “Hello World”.

我们走吧–创建和运行java,无需设置构建工具,甚至无需编译。所有这些都由JBang处理。注意到它第一次打印了 “Building jar”,但第二次没有。第二次它只是打印了 “Hello World”。

The source code has not changed the second time JBang reuses the already built jar.

第二次JBang重用已经建好的jar时,源代码没有改变。

Let’s make it more exciting and create a java file that uses external dependencies. We can do that using a template:

让我们把它变得更刺激,创建一个使用外部依赖的java文件。我们可以用一个模板来做。

jbang init -t cli hellocli.java

The cli is one of the available default templates. By running jbang template list, we can see the list that is available to use:

cli是可用的默认模板之一。通过运行 jbang template list,我们可以看到可以使用的列表。

$ jbang template list
agent = Agent template
cli = CLI template
hello = Basic Hello World template
hello.kt = Basic kotlin Hello World template
qcli = Quarkus CLI template
qmetrics = Quarkus Metrics template
qrest = Quarkus REST template

When we run the hellocli.java we created, we should see it fetch the Picocli dependency and use the arguments we pass in:

当我们运行我们创建的hellocli.java时,我们应该看到它获取了Picocli的依赖关系并使用了我们传入的参数。

$ jbang hellocli.java Baeldung
[jbang] Resolving dependencies...
[jbang]     Resolving info.picocli:picocli:4.5.0...Done
[jbang] Dependencies resolved
[jbang] Building jar...
Hello Baeldung

If we run it a second time, it does not need to resolve the dependency again as we did not edit the source code.

如果我们第二次运行它,它不需要再次解析依赖关系,因为我们没有编辑源代码。

4. JBang Comments

4.JBang评论

Now, if we look into hello.java or hellocli.java, we will see it is just a plain java class:

现在,如果我们查看hello.java或hellocli.java,我们会发现它只是一个普通的java类。

///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS info.picocli:picocli:4.5.0

import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Parameters;

import java.util.concurrent.Callable;

@Command(name = "hellocli", mixinStandardHelpOptions = true, version = "hellocli 0.1",
        description = "hellocli made with jbang")
class hellocli implements Callable<Integer> {

    @Parameters(index = "0", description = "The greeting to print", defaultValue = "World!")
    private String greeting;

    public static void main(String... args) {
        int exitCode = new CommandLine(new hellocli()).execute(args);
        System.exit(exitCode);
    }

    @Override
    public Integer call() throws Exception { // your business logic goes here...
        System.out.println("Hello " + greeting);
        return 0;
    }
}

Notice the two initial lines starts with //, which means the line is a comment in Java.

注意这两行的首字母以//开头,这意味着这一行是Java中的注释。

///usr/bin/env jbang "$0" "$@" ; exit $?

//usr/bin/env jbang "$0" "$@"; exit $?

But in bash/zsh shell, the first line lets us run this file directly as ./hellocli.java.

但是在bash/zsh shell中,第一行让我们直接以./hellocli.java的形式运行这个文件。

//DEPS info.picocli:picocli:4.5.0

//DEPS info.picocli:picocli:4.5.0

The second line starting with //DEPS, is a magic marker line which jbang picks up and uses as its dependencies. The syntax used for dependencies is the canonical maven dependency format used in build tools like Gradle. We can have multiple lines with multiple dependencies on each line, declaring all the dependencies needed. JBang will also fetch transitive dependencies. Thus, we only need to list the top-level ones.

第二行以//DEPS开头,是一个神奇的标记行,jbang会将其作为依赖关系来使用。依赖关系使用的语法是Gradle等构建工具中使用的规范的maven依赖关系格式。我们可以有多行,每行有多个依赖项,声明所有需要的依赖项。JBang也会获取反式的依赖关系。因此,我们只需要列出顶层的依赖。

There are other magic markers JBang will pick up. Here are the main ones:

还有其他一些神奇的标记,JBang会捡到。以下是主要的一些。

JAVA – specify Java version to use, JAVA 11+ means Java 11 or higher, JAVA 14 means exactly Java 14

JAVA – 指定要使用的Java版本,JAVA 11+表示Java 11或更高,JAVA 14表示正是Java 14

JAVA_OPTIONS – will be added to the java command line, use it for setting memory settings and system properties

JAVA_OPTIONS – 将被添加到java命令行中,使用它来设置内存设置和系统属性。

JAVAC_OPTIONS – will be added for the javac compile command. Use it to enable preview or other flags.

JAVAC_OPTIONS – 将为javac编译命令添加。用它来启用预览或其他标志。

There are more examples in the JBang documentation.

JBang文档中有更多例子。

5. Editing

5.编辑工作

Now we understand what JBang reads from the file to make things work. So how can we edit such a .java file and have content assist, refactoring, and other valuable features known from traditional Java-based editors?

现在我们明白了JBang从文件中读取了什么来使事情顺利进行。那么,我们怎样才能编辑这样一个.java文件,并拥有内容辅助、重构和其他传统的基于Java的编辑器中已知的有价值的功能呢?

The answer is jbang edit. With jbang edit JBang will prepare a symbolically linked project that most modern Java-enabled editors can open. If we run it as jbang edit hellocli.java, JBang will ask if it should download and configure VSCodium to get started without any manual setup. Of course, if our favorite IDE is available in the PATH, i.e., Intellij IDEA, we can run jbang edit –open=idea hellocli.java, and JBang will open via idea instead.

答案是jbang edit使用jbang edit,JBang将准备一个符号链接的项目,大多数支持Java的现代编辑器可以打开。如果我们以jbang edit hellocli.java的方式运行它,JBang会询问是否应该下载和配置VSCodium,以便无需任何手动设置就能启动。当然,如果我们最喜欢的IDE在PATH中可用,即Intellij IDEA,我们可以运行jbang edit -open=idea hellocli.java,JBang将通过idea打开。

6. Multiple Files

6.多个文件

Thus far, we have only worked with a single file; what about when we have multiple files? JBang handles multiple source files and arbitrary resources (such as .html files). The two commands for that are //SOURCES and //FILES.

到目前为止,我们只处理了一个文件;当我们有多个文件时,怎么办?JBang可以处理多个源文件和任意的资源(如.html文件)。这方面的两个命令是//SOURCES//FILES

To include a specific source file, use //SOURCE myfile.javaTo include all java source files, use //SOURCE **/*.java.

要包括一个特定的源文件,使用 //SOURCE myfile.java要包括所有java源文件,使用 //SOURCE **/*.java

For resources, the syntax is //FILES <mountpoint>[=<sourcefile>].

对于资源,语法是/FILES <mountpoint>[=<sourcefile>]

//FILES resource.properties
//FILES META-INF/resources/index.html=index.html

Here resource.properties will be copied as-is, and META-INF/resources/index.html gets its content from index.html.

这里resource.properties将被原样复制,META-INF/resources/index.htmlindex.html获得其内容。

All locations are relative to the script location.

Here are a minimal but complete working example with multiple files:

这里有一个最小但完整的工作例子,有多个文件。

///usr/bin/env jbang "$0" "$@" ; exit $?
// Update the Quarkus version to what you want here or run jbang with
// `-Dquarkus.version=<version>` to override it.
//DEPS io.quarkus:quarkus-bom:${quarkus.version:2.4.0.Final}@pom
//DEPS io.quarkus:quarkus-resteasy
//JAVAC_OPTIONS -parameters

//FILES META-INF/resources/index.html=index.html

import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/hello")
@ApplicationScoped
public class jbangquarkus {
    @GET
    public String sayHello() {
        return "Hello from Quarkus with jbang.dev";
    }
}

This example also shows JBang’s integration with Quarkus. By using Quarkus as a dependency, this example just works and provides an index page at http://localhost:8080 and a REST endpoint at http://localhost:8080/hello.

这个例子还展示了JBang与Quarkus的集成。通过使用Quarkus作为依赖关系,这个例子正好可以工作,并在http://localhost:8080提供一个索引页,在http://localhost:8080/hello提供一个REST端点。

With this, we can build small scripts and full-blown microservices or even applications using JBang with any Java-based framework.

有了它,我们可以使用JBang与任何基于Java的框架建立小型脚本和完整的微服务,甚至是应用程序。

7. Sharing Code

7.分享代码

We now can write, run and edit JBang based applications, but what about sharing the code so others can run it?

我们现在可以编写、运行和编辑基于JBang的应用程序,但是如何分享代码以便其他人可以运行它呢?

Using jbang export creates a jar we can share as any other Java app. More interesting is sharing using GitHub, Gitlab, BitBucket, etc.

使用jbang export可以创建一个jar,我们可以像其他Java应用一样分享。更有趣的是使用GitHub、Gitlab、BitBucket等共享。

JBang supports running source code located at a URL and understands what kind of service is behind it. So, for example, to run the JBang Quarkus example above, we can run it directly from the source repository:

JBang支持运行位于URL的源代码,并理解其背后是什么样的服务。因此,例如,要运行上面的JBang Quarkus例子,我们可以直接从源码库中运行它。

jbang https://github.com/eugenp/tutorials/blob/jbangguide/jbang/jbangquarkus.java

jbang https://github.com/eugenp/tutorials/blob/jbangguide/jbang/jbangquarkus.java

JBang will figure out the multiple files needed to download, compile and run as we did early on with local files.

JBang会像我们早期处理本地文件那样,弄清楚下载、编译和运行所需的多个文件。

This way, we can quickly try out others’ code or share it with others. No need to packaging setup – JBang inherently enables easy sharing.

这样,我们就可以快速试用别人的代码或与他人分享。不需要打包设置–JBang本身就能实现轻松分享

7.1. Aliases

7.1. 别名

An URL can be hard to type. Luckily we can also use aliases, i.e., jbang alias add https://github.com/eugenp/tutorials/blob/jbangguide/jbang/jbangquarkus.java will let you use it as jbang jbangquarkus.

一个URL可能很难输入。幸运的是,我们也可以使用别名,例如, jbang alias add https://github.com/eugenp/tutorials/blob/jbangguide/jbang/jbangquarkus.java 将让你把它作为jbang jbangquarkus使用。

By default, JBang installs these aliases globally for the current user. Still, it is also possible to add them to a specific directory using -f, so it only applies to this directory and its subdirectories.

默认情况下,JBang为当前用户全局安装这些别名。不过,也可以用-f,把它们添加到一个特定的目录中,这样它就只适用于这个目录和它的子目录。

jbang alias add -f . https://github.com/eugenp/tutorials/blob/jbangguide/jbang/jbangquarkus.java

jbang alias add -f . https://github.com/eugenp/tutorials/blob/jbangguide/jbang/jbangquarkus.java

Great for adding project-specific commands. Commands that can be shared are not tied to nor require a Gradle or Maven plugins to be written.

很适合添加项目专用命令。可共享的命令不与Gradle或Maven插件绑定,也不需要编写Gradle或Maven插件

These aliases get stored in a jbang-catalog.json file, and we can add these anywhere and host them from anywhere.

这些别名被存储在jbang-catalog.json文件中,我们可以在任何地方添加这些别名,并从任何地方托管它们。

7.2. App Installs

7.2 应用程序的安装

Aliases lead to another helpful command found in most other popular ecosystems except Java: installing scripts/applications. Think npm install, pip install, etc.

别名导致了另一个在除Java之外的大多数其他流行的生态系统中发现的有用命令:安装脚本/应用程序。想想npm installpip install,等等。

With JBang, it is called jbang app install, and it works with both local and remote JBang scripts and jars.

在JBang中,它被称为jbang app install,,它对本地和远程的JBang脚本和jars都适用。

For example, to install our hello.java:

例如,要安装我们的hello.java。

jbang app install hello.java

jbang app install hello.java

Now a `hello` command has been added to our path.

现在,一个`hello`命令已经被添加到我们的路径中。

The same goes for the remote jbangquarkus.java:

远程jbangquarkus.java也是如此。

jbang app install https://github.com/eugenp/tutorials/blob/jbangguide/jbang/jbangquarkus.java

jbang app install https://github.com/eugenp/tutorials/blob/jbangguide/jbang/jbangquarkus.java

When you run such a line, it will make a command called jbangquarkus available on the path.

当你运行这样一行时,它将使一个名为jbangquarkus的命令在路径上可用。

jbang app install works for aliases too.

jbang应用程序安装也适用于别名。

As mentioned, aliases can be stored and shared anywhere thus to be able to find it, aliasesjbang.dev hosts a JBang AppStore at https://jbang.dev/apppstore. Here we can search and find scripts published via jbang-catalog.json files:

如前所述,aliases可以在任何地方存储和共享,因此为了能够找到它,aliasesjbang.dev在https://jbang.dev/apppstore主持一个JBang AppStore。在这里我们可以搜索并找到通过jbang-catalog.json文件发布的脚本。

jbang appstore

Thus if we make a jbang-catalog.json, its contents and description will show up here. Try to search for “eugenp” and find the scripts used in this article.

因此,如果我们做一个jbang-catalog.json,它的内容和描述会在这里显示出来。尝试搜索 “eugenp “并找到本文中使用的脚本。

8. Conclusion

8.结语

In this article, we installed JBang, allowing us to create, edit, build, run and install Java applications and scripts with unprecedented ease.
No setup or pre-existing knowledge around Maven or Gradle is required to start with Java. When we get further, JBang supports using Maven coordinates to fetch dependencies allowing us to use anything from the vast Java ecosystem, including runtime frameworks like Spring and Quarkus or even graphical frameworks like JavaFX.

在本文中,我们安装了JBang,使我们能够以前所未有的轻松方式创建、编辑、构建、运行和安装Java应用程序和脚本。
在开始使用Java时,不需要设置或预先掌握有关Maven或Gradle的知识。当我们更进一步时,JBang支持使用Maven坐标来获取依赖,允许我们使用庞大的Java生态系统中的任何东西,包括Spring和Quarkus等运行时框架,甚至是JavaFX等图形框架。

JBang works with any modern IDE, supports multiple files, and understands what is behind a URL, allowing easy publishing and sharing of source code and aliases that runs a jar.

JBang能与任何现代IDE一起工作,支持多个文件,并能理解URL背后的内容,允许轻松发布和共享运行jar的源代码和别名

JBang has documentation and AppStore available from its website.

JBang的文档和AppStore可从其网站获得。

Examples from this tutorial are available over on GitHub.

本教程中的例子可在GitHub上找到over