在 Gradle 中管理 Java 依赖,主要通过 build.gradle(Groovy DSL)或 build.gradle.kts(Kotlin DSL) 文件来完成。下面从基础到常见用法给你系统讲一下。
plugins {
id 'java'
}
或使用 Kotlin DSL:
plugins {
java
}
repositories {
mavenCentral()
// 或
// maven { url 'https://repo.spring.io/milestone' }
}
dependencies {
implementation 'org.apache.commons:commons-lang3:3.12.0'
testImplementation 'junit:junit:4.13.2'
}
等价 Kotlin DSL:
dependencies {
implementation("org.apache.commons:commons-lang3:3.12.0")
testImplementation("junit:junit:4.13.2")
}
| 配置 | 说明 |
|---|---|
implementation |
编译 + 运行(推荐) |
api |
编译 + 运行,且暴露给依赖方(用于库) |
compileOnly |
只编译,不打包 |
runtimeOnly |
只运行,不编译 |
testImplementation |
测试代码使用 |
annotationProcessor |
注解处理器 |
示例:
implementation 'com.google.guava:guava:31.1-jre'
compileOnly 'org.projectlombok:lombok:1.18.30'
annotationProcessor 'org.projectlombok:lombok:1.18.30'
implementation 'mysql:mysql-connector-java:8.0.33'
ext {
springVersion = '5.3.30'
}
implementation "org.springframework:spring-core:${springVersion}"
platform(BOM)dependencies {
implementation platform('org.springframework.boot:spring-boot-dependencies:2.7.18')
implementation 'org.springframework.boot:spring-boot-starter-web'
}
./gradlew dependencies
./gradlew dependencies --configuration implementation
implementation('com.example:lib:1.0') {
exclude group: 'org.slf4j', module: 'slf4j-api'
}
Gradle 默认使用 最高版本。
手动强制版本:
configurations.all {
resolutionStrategy {
force 'com.google.guava:guava:32.1.3-jre'
}
}
dependencies {
implementation files('libs/xxx.jar')
}
或整个目录:
implementation fileTree(dir: 'libs', include: ['*.jar'])
dependencies {
implementation project(':common')
}
✅ 优先用 implementation
✅ 使用 platform / BOM 管理版本
✅ 定期 ./gradlew dependencies 检查
❌ 避免过多 compile (已废弃)
如果你愿意,我可以:
你可以直接说你的使用场景。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。