The majority of Java projects are based on libraries (jars) i.e called project dependencies. To build java projects it’s required to configure and manage dependencies.
Dependency Management
To configure a dependency in a project required this information:
- Which dependency you need i.e(name and version)
- What it’s needed for i.e (compilation or run)
- Where to look for it .i.e (Repository)
Here first two things need to configure in dependencies {} section while the third point will configure in repositories {} section in build.gradle.
See Also: Gradle: Repositories Configuration
repositories {
mavenCentral()
}
dependencies {
//use for hibernate
implementation 'org.hibernate:hibernate-core:3.6.7.Final'
// Use JUnit test framework
testImplementation 'junit:junit:4.12'
}
In this above example:
- mavenCentral() is repository where gradle search for dependencies.
- implementaion and testImplimation are scopes for dependencies which tell gradle to when these dependencies need to use.
- junit:junit:4.12 is the ID of the dependency, In form of ‘<group>:<module>:<version>’ or ‘<groupId>:<artifactId>:<version>’ in maven terminology.
Scopes of Gradle Dependencies
Gradle provides lots of scopes to configure dependencies in projects.
Scope | Description |
compileOnly | Use for dependencies those are required to compile your production code but that should not be part of the runtime classpath. |
implementation (supersedes compile) | Use for compilation and runtime. |
runtimeOnly supersedes runtime) | Use only at runtime, not for compilation |
testCompileOnly | It’s same as compileOnly for the tests |
testImplementaion | It’s the same as implementation for the tests. |
testRuntimeOnly | It’s the same as runtimeOnly for the tests. |
Note: Java Library Plugin creates one more configuration – api – for dependencies that are required for compiling both modules and any modules depend on it.
Dependencies from Local File Systems
You can also set dependencies from local file system or from lib folder.
Dependencies from Project lib folder
dependencies {
// for specific jars
runtime files('libs/library1.jar', 'libs/library2.jar')
//for all jars in lib folder
runtime fileTree(dir: 'libs', include: '*.jar')
}
Dependencies from Local Machine
dependencies {
compile fileTree(dir: "${System.properties['user.home']}/libs/banks", include: '*.jar')
}
References
https://docs.gradle.org/current/userguide/building_java_projects.html
You must log in to post a comment.