公共脚本
公共脚本
Gradle 中公共脚本抽取与共享
要解决冗余代码和通用配置的问题,最简单的做法就是抽取出共同部分,作为其它所有项目的
使用git submodule
将所有系统中公共的类库和通用的配置,放到独立的仓库
git submodule add yourGitRepo deps/Common
最后的”deps/Common”是自定义的,意思就是在当前的
如果你
git submodule foreach git pull
以下这段一般大家经常会遇到:当你
git submodule foreach git checkout master
让
Gradle 构建
鉴于上文对
gradle init wrapper
这样,就会自动生成相关的
注:在已有的
Gradle 脚本修改
上面执行完之后,环境已经准备好了,现在要做的就是修改构建脚本:因为已经通过
include "deps:Common"
以上就是把
// 这一段主要是把公共库Common的构建脚本引入,因为一般会有通用的配置在里面
def userGradleScript = file("deps/Common/build.gradle")
if (userGradleScript.exists()) {
apply from: userGradleScript
}
// 使用war插件,这样就默认引入了java插件
apply plugin: 'war'
// for jetty
apply plugin: 'jetty'
stopKey = 'yourStopKey' // 自定义的stopkey
stopPort = xxxx // 停止端口
httpPort = xxxx // 启动http端口
// 项目属性
group = 'yourApp'
version = '1.0.0'
description = """这里描述你的项目"""
// checkstyle config文件地址
checkstyle {
configFile = file("deps/Common/config/checkstyle/checkstyle.xml")
}
// lib依赖
dependencies {
// 依赖公共库Common,compile是和maven里的compile scope一样
compile project(':deps:Common')
compile 'commons-validator:commons-validator:1.4.0'
compile('javax.servlet.jsp.jstl:jstl-api:1.2') {
exclude(module: 'servlet-api') // 防止版本冲突
}
compile 'javax.persistence:persistence-api:1.0.2'
runtime 'mysql:mysql-connector-java:5.1.26'
providedCompile 'org.apache.tomcat:tomcat-servlet-api:7.0.30'
// providedCompile 这个conf在java插件里是报错的,war里是正确的
providedCompile 'javax.servlet.jsp:jsp-api:2.1'
...
}
我们再来简单看下公共项目
// 定义一堆基础插件
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: "jacoco"
apply plugin: 'checkstyle'
apply plugin: 'pmd'
apply plugin: 'findbugs'
apply plugin: 'eclipse'
apply plugin: 'idea'
// 定义项目属性
group = 'Common'
version = '1.0.0'
description = """Giant common library"""
// 定义依赖仓库
repositories {
mavenCentral()
}
// project的额外属性,这里用于定义profile属性,模拟maven的profile
ext {
if (project.hasProperty('profile')) {
profile = project['profile']
} else {
profile = "dev"
}
println "profile:" + profile
}
// 额外增加source path
sourceSets {
main {
resources {
srcDir "src/main/profiles/${profile}"
}
}
}
// project依赖
dependencies {
compile 'ch.qos.logback:logback-core:1.0.13'
compile 'ch.qos.logback:logback-classic:1.0.13'
compile 'ch.qos.logback:logback-access:1.0.13'
compile 'commons-io:commons-io:2.0.1'
compile 'commons-lang:commons-lang:2.6'
compile 'joda-time:joda-time:1.6.2'
compile 'org.testng:testng:6.8.7'
compile 'com.googlecode.jmockit:jmockit:1.5'
...
}
// task 配置
checkstyle {
ignoreFailures = true
sourceSets = [sourceSets.main]
}
findbugs {
ignoreFailures = true
sourceSets = [sourceSets.main]
}
pmd {
ruleSets = ["basic", "braces", "design"]
ignoreFailures = true
sourceSets = [sourceSets.main]
}
jacocoTestReport {
reports {
xml.enabled true
html.enabled true
csv.enabled false
}
sourceSets sourceSets.main
}
tasks.withType(Compile) {
options.encoding = "UTF-8"
}
test {
useTestNG()
jacoco {
excludes = ["org.*"]
}
}
这样,就可以在公共项目里配置好一堆基础的
./gradlew build
// 基于profile构建
./gradlew -Pprofile=dev build
常用构建命令:clean:清除之前的构建