gradle项目中profile的实现

gradle中并没有直接类似maven中的profile支持,只能变通的用其它方法来处理,在打包不同环境的应用时,通常会遇到二类问题:

一、不同的环境依赖的jar包不同

拿web开发来说,生产环境一般会采用weblogic,jboss这类重量级的容器,通常这类web server已经内置了很多第三方的通用jar包,而开发环境,一般采用嵌入式jetty这类轻量级的容器,内置的jar包会少一些,在maven中可以用<scope>provided</scope>来处理,到了gradle中可以这么处理:

build.gradle文件参考下面的写法:

def env = System.getProperty("env") ?: "dev"

apply from: "profile-${env}.gradle"

大概意思是,根据传入的参数env不同,加载不同的profile文件。在同级目录下,要放二个文件(下面演示的场景为,dev环境加载的spring版本为4.1.6,而prod环境加载的spring版本为4.2.3):

profile-dev.gradle

dependencies {
    compile 'org.springframework:spring-core:4.1.6.RELEASE'
    compile 'org.springframework:spring-beans:4.1.6.RELEASE'
    compile 'org.springframework:spring-context:4.1.6.RELEASE'
    compile 'org.springframework:spring-context-support:4.1.6.RELEASE'
    compile 'org.springframework:spring-aop:4.1.6.RELEASE'
}

profile-prod.gradle

dependencies {
    compile 'org.springframework:spring-core:4.2.3.RELEASE'
    compile 'org.springframework:spring-beans:4.2.3.RELEASE'
    compile 'org.springframework:spring-context:4.2.3.RELEASE'
}

编译时,gradle命令这么写:

gradle build -Denv=prod  这样编译的就是prod环境

gradle build -Denv=dev  这样编译的就是dev环境(注:dev是默认环境,所以如果是dev环境,最后的-Denv=dev也可以省略)

 

二、不同的环境,配置的参数不同

思路:为每个环境建不同的目录,把各环境的属性文件按目录存放,编译时动态设置gradle的资源目录

sourceSets {
    main {
        resources {
            srcDirs = ["src/main/resources", "src/main/profile/$env"]
        }
    }
}

在刚才的基础上,再加入这一段即可。

整个项目的结构图如下:

 

示例源代码: https://github.com/yjmyzz/gradle-profile-sample

posted @ 2015-12-19 16:01  菩提树下的杨过  阅读(16941)  评论(0编辑  收藏  举报