Gradle Parent Build File | Common Dependency Example

By Arvind Rai, September 21, 2014
In this page we will see how to use parent build file or any common gradle file that can be used in more than one gradle project. Create a gradle build file and define the dependency and then it can be included in any gradle project using apply from referring relative path or any http URL. To understand the concept, find the project and gradle build file structure.
common.gradle
|
|
MainProject
	   |
	   |
            -- build.gradle
We have a common.gradle file which will act as parent build file or common dependency file for any project. Find the common.gradle script.
common.gradle
dependencies {
   compile 'org.springframework:spring-jdbc:4.1.0.RELEASE'
}

ext.libs = [
    spring_aop: 'org.springframework:spring-aop:4.1.0.RELEASE',
    junit: 'junit:junit:4.10',
	
	spring_core: dependencies.create('org.springframework:spring-core:4.1.0.RELEASE') {
		exclude module: "commons-logging"
		force = true
	},
	
	hibernate: [
        'org.hibernate:hibernate-annotations:3.5.6-Final',
        'org.hibernate:hibernate-core:4.3.6.Final'
    ]
] 
common.gradle script can be referred in child project using below syntax
1. Using relative path:
apply from: '../common.gradle'
2. Using URL:
apply from: 'http://anydomain.com/common.gradle'

Now find the sample build file which are using common.gradle.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
apply from: '../common.gradle'

repositories {
    mavenCentral()
}

dependencies {
   compile libs.hibernate
   compile libs.spring_core
   compile libs.junit
} 
Common dependency can be set in many ways. Use dependencies as below
dependencies {
   compile 'org.springframework:spring-jdbc:4.1.0.RELEASE'
}
The dependency defined here will automatically be available for every project just by including the common gardle file using apply from. Now if we want to define dependency in common or parent file in the way that it should not be available in our child gradle file until we explicitly call the dependency, We can define using external library.
ext.libs = [
    spring_aop: 'org.springframework:spring-aop:4.1.0.RELEASE',
    junit: 'junit:junit:4.10'
]
The above code can be accessed in child build file using
dependencies {
   compile libs.spring_aop
   compile libs.junit
}
External library can be defined in many ways as below
ext.libs = [
   	spring_core: dependencies.create('org.springframework:spring-core:4.1.0.RELEASE') {
		exclude module: "commons-logging"
		force = true
	}
]
Using dependencies.create method provides the facility to exclude any module or other settings. Now find the below way to define external library using array of dependency.
ext.libs = [
    hibernate: [
        'org.hibernate:hibernate-annotations:3.5.6-Final',
        'org.hibernate:hibernate-core:4.3.6.Final'
    ]
]
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us