62. 使用 CLI

安装 CLI 后,可以通过键入spring来运行它。如果您不带任何参数运行spring,将显示一个简单的帮助屏幕:

$ spring
usage: spring [--help] [--version]
       <command> [<args>]

Available commands are:

  run [options] <files> [--] [args]
    Run a spring groovy script

  ... more command help is shown here

您可以使用help获取有关任何受支持命令的更多详细信息。例如:

$ spring help run
spring run - Run a spring groovy script

usage: spring run [options] <files> [--] [args]

Option                     Description
------                     -----------
--autoconfigure [Boolean]  Add autoconfigure compiler
                             transformations (default: true)
--classpath, -cp           Additional classpath entries
-e, --edit                 Open the file with the default system
                             editor
--no-guess-dependencies    Do not attempt to guess dependencies
--no-guess-imports         Do not attempt to guess imports
-q, --quiet                Quiet logging
-v, --verbose              Verbose logging of dependency
                             resolution
--watch                    Watch the specified file for changes

version命令提供了一种快速的方法来检查您使用的 Spring Boot 版本。

$ spring version
Spring CLI v1.5.9.RELEASE

62.1 使用 CLI 运行应用程序

您可以使用run命令编译并运行 Groovy 源代码。 Spring Boot CLI 是完全独立的,因此您不需要任何外部 Groovy 安装。

这是用 Groovy 编写的示例“ hello world” Web 应用程序:

hello.groovy.

@RestController
class WebApplication {

    @RequestMapping("/")
    String home() {
        "Hello World!"
    }

}

要编译和运行应用程序类型:

$ spring run hello.groovy

要将命令行参数传递给应用程序,您需要使用--将其与“ spring”命令参数分开,例如

$ spring run hello.groovy -- --server.port=9000

要设置 JVM 命令行参数,您可以使用JAVA_OPTS环境变量,例如

$ JAVA_OPTS=-Xmx1024m spring run hello.groovy

Note

在 Microsoft Windows 上设置JAVA_OPTS时,请确保引用整个指令,例如set "JAVA_OPTS=-Xms256m -Xmx2048m"。这样可以确保将值正确地传递给流程。

62.1.1 推论"grab"依赖性

标准 Groovy 包含@Grab注解,使您可以声明对第三方库的依赖关系。这项有用的技术允许 Groovy 以与 Maven 或 Gradle 相同的方式下载 jar,而无需使用构建工具。

Spring Boot 进一步扩展了该技术,并将尝试根据您的代码推断出哪些库可以“抢”。例如,由于上面的WebApplication代码使用@RestControllerComments,因此将捕获“ Tomcat”和“ Spring MVC”。

以下各项用作“抓取提示”:

ItemsGrabs
JdbcTemplate , NamedParameterJdbcTemplate , DataSourceJDBC Application.
@EnableJmsJMS Application.
@EnableCachingCaching abstraction.
@TestJUnit.
@EnableRabbitRabbitMQ.
@EnableReactorProject Reactor.
延伸SpecificationSpock test.
@EnableBatchProcessingSpring Batch.
@MessageEndpoint @EnableIntegrationPatternsSpring Integration.
@EnableDeviceResolverSpring Mobile.
@Controller @RestController @EnableWebMvcSpring MVC 嵌入式 Tomcat。
@EnableWebSecuritySpring Security.
@EnableTransactionManagementSpringTransactionManagement。

Tip

请参阅 Spring Boot CLI 源代码中的CompilerAutoConfiguration的子类,以确切地了解如何应用定制。

62.1.2 推导"grab"坐标

Spring Boot 通过允许您指定没有组或版本的依赖项(例如@Grab('freemarker'))来扩展 Groovy 的标准@Grab支持。这将参考 Spring Boot 的默认依赖元数据来推断工件的组和版本。请注意,默认元数据与您所使用的 CLI 版本有关–仅当您移至新版本的 CLI 时,它才会更改,从而使您可以控制依赖项版本的更改时间。可以在appendix中找到一个表格,其中显示了默认元数据中包含的依赖项及其版本。

62.1.3 默认导入语句

为了帮助减少 Groovy 代码的大小,将自动包含多个import语句。注意上面的示例如何引用@Component@RestController@RequestMapping,而无需使用完全限定的名称或import语句。

Tip

许多 SpringComments 无需使用import语句即可工作。在添加导入之前,请尝试运行您的应用程序以查看失败的原因。

62.1.4 自动 Main 方法

与等效的 Java 应用程序不同,您不需要在Groovy脚本中包含public static void main(String[] args)方法。会自动创建一个SpringApplication,并将您的编译后的代码用作source

62.1.5 自定义依赖项 Management

默认情况下,CLI 使用spring-boot-dependencies中声明的依赖性 Management 来解决@Grab依赖性。可以使用@DependencyManagementBomComments 配置其他的依赖 Management,这些 Management 将覆盖默认的依赖 Management。Comments 的值应指定一个或多个 Maven BOM 的坐标(groupId:artifactId:version)。

例如,以下声明:

@DependencyManagementBom("com.example.custom-bom:1.0.0")

将在com/example/custom-versions/1.0.0/下的 Maven 存储库中提取custom-bom-1.0.0.pom

指定多个 BOM 时,将按照声明的 Sequences 应用它们。例如:

@DependencyManagementBom(["com.example.custom-bom:1.0.0",
        "com.example.another-bom:1.0.0"])

表示another-bom中的依赖项 Management 将覆盖custom-bom中的依赖项 Management。

您可以在可以使用@Grab的任何地方使用@DependencyManagementBom,但是,为了确保依赖性 Management 的 Sequences 一致,您只能在应用程序中使用@DependencyManagementBom一次。 Spring IO 平台是依存关系 Management(是 Spring Boot 依存关系 Management 的超集)的有用来源。 @DependencyManagementBom('io.spring.platform:platform-bom:1.1.2.RELEASE')

62.2 测试您的代码

test命令允许您编译和运行应用程序的测试。典型用法如下:

$ spring test app.groovy tests.groovy
Total: 1, Success: 1, : Failures: 0
Passed? true

在此示例中,tests.groovy包含 JUnit @Test方法或 Spock Specification类。所有通用框架 Comments 和静态方法都应该可用,而不必import

这是我们上面使用的tests.groovy文件(用于 JUnit 测试):

class ApplicationTests {

    @Test
    void homeSaysHello() {
        assertEquals("Hello World!", new WebApplication().home())
    }

}

Tip

如果您有多个测试源文件,则可能希望将它们组织到test目录中。

62.3 具有多个源文件的应用程序

您可以对所有接受文件 Importing 的命令使用“ shell globbing”。这使您可以轻松地从单个目录中使用多个文件,例如

$ spring run *.groovy

如果要将“测试”或“规范”代码与主应用程序代码分开,则该技术也很有用:

$ spring test app/*.groovy test/*.groovy

62.4 打包您的应用程序

您可以使用jar命令将应用程序打包为独立的可执行 jar 文件。例如:

$ spring jar my-app.jar *.groovy

生成的 jar 将包含通过编译应用程序产生的类以及应用程序的所有依赖关系,以便随后可以使用java -jar来运行它。 jar 文件还将包含来自应用程序的 Classpath 的条目。您可以使用--include--exclude将显式路径添加到 jar 中(两者均以逗号分隔,并且都接受值“”和“-”的前缀以表示应将其从默认值中删除)。默认包括

public/**, resources/**, static/**, templates/**, META-INF/**, *

并且默认排除为

.*, repository/**, build/**, target/**, **/*.jar, **/*.groovy

有关更多信息,请参见spring help jar的输出。

62.5 初始化新项目

init命令允许您使用start.spring.io创建新项目,而无需离开 Shell。例如:

$ spring init --dependencies=web,data-jpa my-project
Using service at https://start.spring.io
Project extracted to '/Users/developer/example/my-project'

这将使用spring-boot-starter-webspring-boot-starter-data-jpa创建一个具有基于 Maven 的项目的my-project目录。您可以使用--list标志列出服务的功能

$ spring init --list
=======================================
Capabilities of https://start.spring.io
=======================================

Available dependencies:
-----------------------
actuator - Actuator: Production ready features to help you monitor and manage your application
...
web - Web: Support for full-stack web development, including Tomcat and spring-webmvc
websocket - Websocket: Support for WebSocket development
ws - WS: Support for Spring Web Services

Available project types:
------------------------
gradle-build -  Gradle Config [format:build, build:gradle]
gradle-project -  Gradle Project [format:project, build:gradle]
maven-build -  Maven POM [format:build, build:maven]
maven-project -  Maven Project [format:project, build:maven] (default)

...

init命令支持许多选项,有关更多详细信息,请检查help输出。例如,以下命令使用 Java 8 和war打包创建 gradle 项目:

$ spring init --build=gradle --java-version=1.8 --dependencies=websocket --packaging=war sample-app.zip
Using service at https://start.spring.io
Content saved to 'sample-app.zip'

62.6 使用嵌入式 Shell

Spring Boot 包含用于 BASH 和 zsh shell 的命令行完成脚本。如果您不使用这两个 Shell 程序(也许您是 Windows 用户),则可以使用shell命令启动集成 Shell 程序。

$ spring shell
Spring Boot (v1.5.9.RELEASE)
Hit TAB to complete. Type \'help' and hit RETURN for help, and \'exit' to quit.

从嵌入式 Shell 程序内部,您可以直接运行其他命令:

$ version
Spring CLI v1.5.9.RELEASE

嵌入式 Shell 支持 ANSI 颜色输出以及tab完成。如果需要运行本机命令,则可以使用!前缀。击中ctrl-c将退出嵌入式 Shell。

62.7 将扩展添加到 CLI

您可以使用install命令将扩展添加到 CLI。该命令采用group:artifact:version格式的一组或多组工件坐标。例如:

$ spring install com.example:spring-boot-cli-extension:1.0.0.RELEASE

除了安装由您提供的坐标标识的工件之外,还将安装所有工件的依赖项。

要卸载依赖项,请使用uninstall命令。与install命令一样,它采用一组或多组group:artifact:version格式的工件坐标。例如:

$ spring uninstall com.example:spring-boot-cli-extension:1.0.0.RELEASE

它将卸载由您提供的坐标及其依赖项标识的工件。

要卸载所有其他依赖项,可以使用--all选项。例如:

$ spring uninstall --all