讲过用Gradle 构建Java 项目和用Gradle 构建Java Web 项目之后,这次我们详细讲下Gradle的War插件。原文地址:Chapter 49. The War Plugin
War 插件继承于Java插件,添加了打包web 应用WAR包的支持。此插件禁用了Java 插件的JAR 包打包功能,添加了WAR 包打包功能。
49.1. 用法
为了使用War 插件,需要在你的Gradle 构建脚本中添加下面这段:
build.gradle
apply plugin: 'war'
49.2. 任务
War 插件为项目添加了以下这些任务: Task name|Depends on|Type|Description ---|---|---|--- war|compile|War|Assembles the application WAR file.
War 插件 添加了下面这些来自Java 插件的依赖到任务中: Task name|Depends on ---|--- assemble|war
49.3.项目结构
Directory | Meaning |
---|---|
src/main/webapp | Web application sources |
49.4.依赖管理
War 插件带来了两个配置属性:providedCompile 和 provideRuntime。这两个配置的作用域分别跟compile 和 runtime 配置一致,除非他们不是添加到WAR 包。有个重要的点,这些provided 配置的行为传递性。假设你添加依赖commons-httpclient:commons-httpclient:3.0 到其中一个provided 配置。这个依赖有个依赖是commons-codec。因为这是“provided”配置,这意味着着两个依赖都不会打包进你的WAR包,即使commons-codec 包显性的配置为 compile。如果你不想要这个传递行为,一个简单的做法,就是这么来定义你的provided 依赖:commons-httpclient:commons-httpclient:3.0@jar。
49.5.默认配置
Property name | Type | Default value | Description |
---|---|---|---|
webAppDirName | String | src/main/webapp | The name of the web application source directory, relative to the project directory. |
webAppDir | File (read-only) | projectDir/webAppDirName | The web application source directory. |
These properties are provided by a WarPluginConvention convention object.
49.6.War
War 任务的默认行为是拷贝src/main/webapp 目录下的内容到包的根目录。你的webapp 目录下可能有个包含web.xml 的子目录 WEB-INF。编译后的clesses文件会被编译到WEB-INF/classes。所有的runtime 配置的依赖包会被拷贝到WEB-INF/lib。
The War class in the API documentation has additional useful information.
49.7.自定义
下面是一个包含最重要自定义项的栗子:
build.gradle
configurations {
moreLibs
}
repositories {
flatDir { dirs "lib" }
mavenCentral()
}
dependencies {
compile module(":compile:1.0") {
dependency ":compile-transitive-1.0@jar"
dependency ":providedCompile-transitive:1.0@jar"
}
providedCompile "javax.servlet:servlet-api:2.5"
providedCompile module(":providedCompile:1.0") {
dependency ":providedCompile-transitive:1.0@jar"
}
runtime ":runtime:1.0"
providedRuntime ":providedRuntime:1.0@jar"
testCompile "junit:junit:4.12"
moreLibs ":otherLib:1.0"
}
war {
from 'src/rootContent' // adds a file-set to the root of the archive
webInf { from 'src/additionalWebInf' } // adds a file-set to the WEB-INF dir.
classpath fileTree('additionalLibs') // adds a file-set to the WEB-INF/lib dir.
classpath configurations.moreLibs // adds a configuration to the WEB-INF/lib dir.
webXml = file('src/someWeb.xml') // copies a file to WEB-INF/web.xml
}
Of course one can configure the different file-sets with a closure to define excludes and includes.