Kotlin脚本使用AWS SDK报错:unresolved reference: aws
Kotlin脚本中AWS SDK导入失败的解决方案
问题描述
执行以下Kotlin脚本时,Kotlin协程依赖可正常导入,但AWS SDK相关包提示unresolved reference: aws错误:
脚本代码
#!/usr/bin/env kotlin @file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.1") @file:DependsOn("aws.sdk.kotlin:dynamodb:0.30.1-beta") import kotlinx.coroutines.* import aws.sdk.kotlin.services.dynamodb.DynamoDbClient import aws.sdk.kotlin.services.dynamodb.model.ListTablesRequest runBlocking { val ddb = DynamoDbClient.fromEnvironment() println("starting") }
报错信息
test.main.kts:7:8: error: unresolved reference: aws import aws.sdk.kotlin.services.dynamodb.DynamoDbClient ^ test.main.kts:8:8: error: unresolved reference: aws import aws.sdk.kotlin.services.dynamodb.model.ListTablesRequest ^
原因分析
- 所使用的AWS SDK for Kotlin 0.30.1-beta为旧版本,存在Kotlin脚本环境的兼容性问题,未完全适配脚本的依赖解析机制。
- Kotlin脚本默认依赖拉取逻辑可能存在潜在的仓库访问问题,导致AWS包未正确加载到类路径中。
解决方案
1. 显式声明Maven仓库
在脚本顶部添加仓库声明,确保依赖能从Maven Central正确拉取:
@file:Repository("https://repo1.maven.org/maven2/")
2. 升级到稳定版AWS SDK for Kotlin
替换旧beta版本为最新稳定版(当前推荐1.10.2),稳定版对脚本环境的兼容性更好:
@file:DependsOn("aws.sdk.kotlin:dynamodb:1.10.2")
3. 验证依赖加载状态
在脚本中添加类路径打印语句,确认AWS的jar包已被包含到类路径中:
println("Classpath: ${System.getProperty("java.class.path")}")
修改后的完整脚本示例
#!/usr/bin/env kotlin @file:Repository("https://repo1.maven.org/maven2/") @file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.1") @file:DependsOn("aws.sdk.kotlin:dynamodb:1.10.2") import kotlinx.coroutines.* import aws.sdk.kotlin.services.dynamodb.DynamoDbClient import aws.sdk.kotlin.services.dynamodb.model.ListTablesRequest // 验证类路径是否包含AWS SDK包 println("Classpath: ${System.getProperty("java.class.path")}") runBlocking { val ddb = DynamoDbClient.fromEnvironment() println("DynamoDB client initialized successfully") // 可选:测试列出表操作 val tablesResp = ddb.listTables(ListTablesRequest {}) println("Existing tables: ${tablesResp.tableNames}") }
内容的提问来源于stack exchange,提问作者Franco
相关产品推荐
相关产品推荐

