Spring Boot文档(009)-第八部分

第八部分 构建工具插件

Spring Boot为Maven和Gradle提供了构建工具插件。这些插件提供了多种功能,包括可执行文件包的打包。本节提供了有关这两种插件的更多详细信息,以及在需要扩展不受支持的构建系统时的一些帮助。如果你是刚开始,你可能需要阅读“ 第13章,构建系统 ”,从 第三部分,“使用Spring引导”首节。

66. Spring Boot Maven插件

春季启动Maven插件提供了Maven的春季启动支持,让你打包可执行的JAR或战争档案和运行“就地”的应用程序。要使用它,你必须使用Maven 3.2(或更好)。

[注意]

有关完整的插件文档,请参阅Spring Boot Maven Plugin站点

66.1包括插件

要使用Spring Boot Maven插件,只需在plugins 您的部分中包含适当的XMLpom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!-- ... -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.5.14.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

这个配置将重新包装package在Maven生命周期阶段构建的jar或war 。以下示例在target目录中显示重新打包的jar以及原始jar :

$ mvn package
$ ls target/*.jar
target/myproject-1.0.0.jar target/myproject-1.0.0.jar.original

如果你不包含<execution/>上面的配置,你可以自己运行插件(但只有在使用包目标时)。例如:

$ mvn package spring-boot:repackage
$ ls target/*.jar
target/myproject-1.0.0.jar target/myproject-1.0.0.jar.original

如果您正在使用里程碑或快照版本,则还需要添加适当的 pluginRepository元素:

<pluginRepositories>
    <pluginRepository>
        <id>spring-snapshots</id>
        <url>https://repo.spring.io/snapshot</url>
    </pluginRepository>
    <pluginRepository>
        <id>spring-milestones</id>
        <url>https://repo.spring.io/milestone</url>
    </pluginRepository>
</pluginRepositories>

66.2打包可执行的jar和war文件

一旦spring-boot-maven-plugin包含在你的文件中,pom.xml它会自动尝试重写归档文件,使它们可以使用spring-boot:repackage 目标执行。你应该配置你的项目使用通常的packaging元素来构建一个jar或war(如果适用):

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <!-- ... -->
    <packaging>jar</packaging>
    <!-- ... -->
</project>

在这个package阶段你的现有存档将被Spring Boot增强。您要启动的主类可以使用配置选项指定,也可以通过Main-Class以常用方式向清单中添加属性来指定。如果你没有指定一个主类,插件将用public static void main(String[] args)方法搜索一个类 。

要构建和运行项目工件,可以键入以下内容:

$ mvn package
$ java -jar target/mymodule-0.0.1-SNAPSHOT.jar

要构建可执行并可部署到外部容器中的war文件,需要将嵌入容器依赖项标记为“提供”,例如:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <!-- ... -->
    <packaging>war</packaging>
    <!-- ... -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- ... -->
    </dependencies>
</project>
[小费]

有关如何创建可部署战争文件的更多详细信息,请参阅“ 部分86.1,”创建可部署战争文件 “部分。

高级配置选项和示例可在 插件信息页面中找到

67. Spring Boot Gradle插件

Spring Boot Gradle插件在Gradle中提供Spring Boot支持,允许您打包可执行jar或war档案,运行Spring Boot应用程序并使用由其提供的依赖关系管理spring-boot-dependencies

67.1包括插件

要使用Spring Boot Gradle Plugin,请使用以下plugins块进行配置:

plugins {
    id 'org.springframework.boot' version '1.5.14.RELEASE'
}

67.2 Gradle依赖管理

spring-boot插件会自动应用 依赖管理插件并将其配置为导入spring-boot-starter-parentbom。这为Maven用户提供了一种类似的依赖管理体验。例如,它允许您在声明bom中管理的依赖项时省略版本号。为了使用这个功能,只需以通常的方式声明依赖关系,但保留版本号为空:

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.thymeleaf:thymeleaf-spring4")
    compile("nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect")
}
[注意]

spring-boot您声明的gradle插件的版本决定了spring-boot-starter-parent导入的bom 的版本(这确保了版本总是可重复的)。您应该始终将spring-bootGradle插件的版本设置为您希望使用的实际Spring Boot版本。所提供版本的细节可以在附录中找到。

要了解有关Dependency Management插件功能的更多信息,请参阅其文档

67.3打包可执行的jar和war文件

一旦spring-boot插件已经应用到您的项目中,它将自动尝试重写存档以使其可以使用 bootRepackage任务执行。你应该配置你的项目以通常的方式建立一个jar或war(适当的时候)。

要启动的主类可以使用配置选项指定,也可以通过向Main-Class清单添加属性来指定。如果你没有指定一个主类,插件将用public static void main(String[] args)方法搜索一个类 。

[小费]

检查第67.6节“重新包装配置”以获取配置选项的完整列表。

要构建和运行项目工件,可以键入以下内容:

$ gradle build
$ java -jar build/libs/mymodule-0.0.1-SNAPSHOT.jar

要构建一个既可执行又可部署到外部容器中的war文件,您需要将嵌入容器依赖项标记为属于war插件的 providedRuntime配置,例如:

...
apply plugin: 'war'

war {
    baseName = 'myapp'
    version =  '0.5.0'
}

repositories {
    jcenter()
    maven { url "https://repo.spring.io/libs-snapshot" }
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
    ...
}
[小费]

有关如何创建可部署战争文件的更多详细信息,请参阅“ 部分86.1,”创建可部署战争文件 “部分。

67.4就地运行项目

要在不首先创建jar的情况下就地运行项目,可以使用“bootRun”任务:

$ gradle bootRun

如果devtools已添加到您的项目中,它将自动监控您的应用程序的更改。或者,您也可以运行应用程序,以便您的静态类路径资源(即src/main/resources 默认情况下)可在实时应用程序中重新加载,这在开发时可能会有所帮助。

bootRun {
    addResources = true
}

使静态类路径资源可重新加载意味着bootRun不使用processResources任务的输出,即,在使用时bootRun,应用程序将以未处理的形式使用资源。

67.5 Spring Boot插件配置

gradle插件会自动扩展您的构建脚本DSL和springBootBoot插件的全局配置元素。像使用其他Gradle扩展一样设置适当的属性(请参阅下面的配置选项列表):

springBoot {
    backupSource = false
}

67.6重新包装配置

该插件添加了一个bootRepackage您也可以直接配置的任务,例如:

bootRepackage {
    mainClass = 'demo.Application'
}

以下配置选项可用:

NameDescription

enabled

Boolean flag to switch the repackager off (sometimes useful if you want the other Boot features but not this one)

mainClass

The main class that should be run. If not specified, and you have applied the application plugin, the mainClassNameproject property will be used. If the application plugin has not been applied or no mainClassName has been specified, the archive will be searched for a suitable class. "Suitable" means a unique class with a well-formed main() method (if more than one is found the build will fail). If you have applied the application plugin, the main class can also be specified via its "run" task (main property) and/or its "startScripts" task (mainClassName property) as an alternative to using the "springBoot" configuration.

classifier

A file name segment (before the extension) to add to the archive, so that the original is preserved in its original location. Defaults to null in which case the archive is repackaged in place. The default is convenient for many purposes, but if you want to use the original jar as a dependency in another project you must use a classifier to define the executable archive.

withJarTask

The name or value of the Jar task (defaults to all tasks of type Jar) which is used to locate the archive to repackage.

customConfiguration

The name of the custom configuration which is used to populate the nested lib directory (without specifying this you get all compile and runtime dependencies).

executable

Boolean flag to indicate if jar files are fully executable on Unix like operating systems. Defaults to false.

embeddedLaunchScript

The embedded launch script to prepend to the front of the jar if it is fully executable. If not specified the 'Spring Boot' default script will be used.

embeddedLaunchScriptProperties

Additional properties that to be expanded in the launch script. The default script supports a mode property which can contain the values autoservice or run.

excludeDevtools

Boolean flag to indicate if the devtools jar should be excluded from the repackaged archives. Defaults to true.

67.7使用自定义Gradle配置重新打包

有时,它可能更适合于从解决不包默认的依赖 compileruntimeprovided范围。如果创建的可执行jar文件是按照原样运行的,则需要将所有依赖关系嵌套在其中; 但是,如果计划要分解jar文件并手动运行主类,则可能已经有一些可用的库CLASSPATH。在这种情况下,您可以使用不同的依赖关系对jar进行重新打包。

使用自定义的配置将自动禁用依赖从解决 compileruntimeprovided范围。自定义配置可以全局定义(在springBoot部分内)或每个任务。

task clientJar(type: Jar) {
    appendix = 'client'
    from sourceSets.main.output
    exclude('**/*Something*')
}

task clientBoot(type: BootRepackage, dependsOn: clientJar) {
    withJarTask = clientJar
    customConfiguration = "mycustomconfiguration"
}

在上面的例子中,我们创建了一个新的clientJarJar任务来打包来自编译源的自定义文件集。然后,我们创建了一个新的clientBoot BootRepackage任务,并指示它只处理clientJar任务和 mycustomconfiguration

configurations {
    mycustomconfiguration.exclude group: 'log4j'
}

dependencies {
    mycustomconfiguration configurations.runtime
}

我们所指的配置BootRepackage是普通的 Gradle配置。在上面的例子中,我们创建了一个新的配置,命名 mycustomconfiguration它来从一个派生runtime和排除log4j 组。如果clientBoot执行该任务,重新打包的引导jar将具有所有依赖runtime但不包括log4j罐子。

67.7.1配置选项

以下配置选项可用:

NameDescription

mainClass

The main class that should be run by the executable archive.

providedConfiguration

The name of the provided configuration (defaults to providedRuntime).

backupSource

If the original source archive should be backed-up before being repackaged (defaults to true).

customConfiguration

The name of the custom configuration.

layout

The type of archive, corresponding to how the dependencies are laid out inside (defaults to a guess based on the archive type). Seeavailable layouts for more details.

layoutFactory

A layout factory that can be used if a custom layout is required. Alternative layouts can be provided by 3rd parties. Layout factories are only used when layout is not specified.

requiresUnpack

A list of dependencies (in the form “groupId:artifactId” that must be unpacked from fat jars in order to run. Items are still packaged into the fat jar, but they will be automatically unpacked when it runs.

67.7.2可用布局

layout属性配置归档的格式以及是否应包含引导加载程序。以下布局可用:

NameDescriptionExecutable

JAR

Regular executable JAR layout.

Yes

WAR

Executable WAR layoutprovided dependencies are placed in WEB-INF/lib-provided to avoid any clash when the waris deployed in a servlet container.

Yes

ZIP (alias to DIR)

Similar to JAR layout, using PropertiesLauncher.

Yes

MODULE

Bundle dependencies (excluding those with provided scope) and project resources.

No

NONE

Bundle all dependencies and project resources.

No

67.7.3使用自定义布局

如果您对如何在重新打包的jar中安排依赖项和加载器类有自定义要求,则可以使用自定义布局。定义一个或多个LayoutFactory实现的任何库都可以添加到构建脚本依赖项中,然后布局工厂在springBoot配置中可用。例如:

buildscript {
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.14.RELEASE")
		classpath("com.example:custom-layout:1.0.0")
	}
}

springBoot {
	layoutFactory = new com.example.CustomLayoutFactory()
}
[注意]

如果LayoutFactory构建类路径上只有一个自定义,并且列在META-INF/spring.factories其中,则不必在springBoot配置中明确设置它 。布局工厂仅在未layout指定明确的情况下使用。

67.8了解Gradle插件的工作原理

何时spring-boot应用于您的Gradle项目时,将bootRepackage 自动创建一个名为默认任务。该bootRepackage任务取决于Gradle assemble任务,并且在执行时会尝试查找所有限定符为空的jar工件(即,测试和源jar被自动跳过)。

由于bootRepackage找到'all'创建的jar工件,Gradle任务执行的顺序非常重要。大多数项目只创建一个jar文件,所以通常这不是问题; 然而,如果你打算创建一个更复杂的项目设置,使用自定义JarBootRepackage任务,那么几乎没有什么需要考虑的。

如果您只是从项目中创建自定义jar文件,则可以简单地禁用默认jarbootRepackage任务:

jar.enabled = false
bootRepackage.enabled = false

另一种选择是指示默认bootRepackage任务仅使用默认jar任务。

bootRepackage.withJarTask = jar

如果您有一个默认项目设置,其中主jar文件被创建并重新打包,'''您还想创建其他自定义jar,您可以将自定义重新打包任务组合在一起并使用,dependsOn以便bootJars任务在默认bootRepackage任务完成后运行执行:

task bootJars
bootJars.dependsOn = [clientBoot1,clientBoot2,clientBoot3]
build.dependsOn(bootJars)

上述所有调整通常用于避免已经创建的引导jar再次被重新打包的情况。重新包装现有的启动jar不会破坏任何东西,但是您可能会发现它包含不必要的依赖关系。

67.9使用Gradle将工件发布到Maven存储库

如果您声明没有版本的依赖关系,并且想要将构件发布到Maven存储库,则需要使用Spring Boot的依赖管理的详细信息来配置Maven出版物。这可以通过将其配置为发布从中继承spring-boot-starter-parent或导入依赖管理的 poms来实现spring-boot-dependencies。这个配置的确切细节取决于你如何使用Gradle以及你如何发布工件。

67.9.1配置Gradle生成继承依赖管理的pom

以下是配置Gradle以生成继承的pom的示例spring-boot-starter-parent。有关更多信息,请参阅 Gradle用户指南

uploadArchives {
    repositories {
        mavenDeployer {
            pom {
                project {
                    parent {
                        groupId "org.springframework.boot"
                        artifactId "spring-boot-starter-parent"
                        version "1.5.14.RELEASE"
                    }
                }
            }
        }
    }
}

67.9.2配置Gradle生成一个导入依赖管理的pom

以下是配置Gradle生成导入由其提供的依赖关系管理的pom的示例spring-boot-dependencies。有关更多信息,请参阅 Gradle用户指南

uploadArchives {
    repositories {
        mavenDeployer {
            pom {
                project {
                    dependencyManagement {
                        dependencies {
                            dependency {
                                groupId "org.springframework.boot"
                                artifactId "spring-boot-dependencies"
                                version "1.5.14.RELEASE"
                                type "pom"
                                scope "import"
                            }
                        }
                    }
                }
            }
        }
    }
}

68. Spring Boot AntLib模块

Spring Boot AntLib模块为Apache Ant提供了基本的Spring Boot支持。您可以使用该模块创建可执行的jar。要使用这个模块,你需要spring-boot在你的下面声明一个额外的命名空间build.xml

<project xmlns:ivy="antlib:org.apache.ivy.ant"
    xmlns:spring-boot="antlib:org.springframework.boot.ant"
    name="myapp" default="build">
    ...
</project>

您需要记住使用该-lib选项启动Ant ,例如:

$ ant -lib <folder containing spring-boot-antlib-1.5.14.RELEASE.jar>
[小费]

“使用Spring Boot”部分包含更完整的使用Apache Ant的示例 spring-boot-antlib

68.1 Spring Boot Ant任务

一旦spring-boot-antlib声明了名称空间,就可以使用以下附加任务。

68.1.1 spring-boot:exejar

exejar任务可用于创建Spring Boot可执行程序jar。该任务支持以下属性:

AttributeDescriptionRequired

destfile

The destination jar file to create

Yes

classes

The root directory of Java class files

Yes

start-class

The main application class to run

No (default is first class found declaring a main method)

68.1.2例子

指定start-class。

<spring-boot:exejar destfile="target/my-application.jar"
        classes="target/classes" start-class="com.foo.MyApplication">
    <resources>
        <fileset dir="src/main/resources" />
    </resources>
    <lib>
        <fileset dir="lib" />
    </lib>
</spring-boot:exejar>

检测 start-class. 

<exejar destfile="target/my-application.jar" classes="target/classes">
    <lib>
        <fileset dir="lib" />
    </lib>
</exejar>

68.2 spring-boot:findmainclass

这个findmainclass任务在内部被exejar用来定位一个声明一个类的类 main。如果需要,您也可以直接在您的构建中使用此任务。支持以下属性

AttributeDescriptionRequired

classesroot

The root directory of Java class files

Yes (unless mainclass is specified)

mainclass

Can be used to short-circuit the main class search

No

property

The Ant property that should be set with the result

No (result will be logged if unspecified)

68.2.1例子

find and log。 

<findmainclass classesroot="target/classes" />

Find and set. 

<findmainclass classesroot="target/classes" property="main-class" />

Override and set. 

<findmainclass mainclass="com.foo.MainClass" property="main-class" />

69.支持其他构建系统

如果您想使用Maven,Gradle或Ant以外的构建工具,您可能需要开发自己的插件。可执行jar需要遵循特定的格式,并且某些条目需要以未压缩的形式写入(有关详细信息,请参阅附录中的 可执行jar格式部分)。

Spring Boot Maven和Gradle插件都使用它spring-boot-loader-tools来实际生成罐子。如果需要,您也可以自由直接使用此库。

69.1重新包装档案

重新打包现有的存档,以使其成为自包含的可执行存档用途org.springframework.boot.loader.tools.Repackager。该Repackager班采取的是指现有的罐子或战争归档单个构造函数的参数。使用两种可用repackage()方法之一来替换原始文件或写入新的目标。在重新打包程序运行之前,还可以对各种设置进行配置。

69.2嵌套库

重新打包存档时,可以使用该org.springframework.boot.loader.tools.Libraries界面包含对依赖项文件的引用 。我们不提供Libraries这里的具体实现,因为它们通常构建特定于系统。

如果你的档案已经包含你可以使用的库Libraries.NONE

69.3找到main class

如果您不使用Repackager.setMainClass()指定主类,则重新打包程序将使用ASM读取类文件并尝试使用public static void main(String[] args)方法查找合适的类。如果找到多个候选人,则会引发异常。

69.4重新包装实施示例

这是一个典型的重新包装示例:

Repackager repackager = new Repackager(sourceJarFile);
repackager.setBackupSource(false);
repackager.repackage(new Libraries() {
            @Override
            public void doWithLibraries(LibraryCallback callback) throws IOException {
                // Build system specific implementation, callback for each dependency
                // callback.library(new Library(nestedFile, LibraryScope.COMPILE));
            }
        });

70.接下来要读什么

如果您对构建工具插件的工作方式感兴趣,可以查看spring-boot-toolsGitHub 上的模块。附录中介绍了有关可执行jar格式的更多技术细节。

如果您有具体构建相关的问题,你可以检查出“ 如何做 ”的指南。

转载于:https://my.oschina.net/u/128964/blog/1831787

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值