You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWSSecurityTokenServiceClientBuilder无法解析withCredentials方法求助

解决方案:Cannot resolve method 'withCredentials' in 'AWSSecurityTokenServiceClientBuilder'

这个错误通常由AWS SDK for Java版本不兼容或API使用方式错误导致,以下分两种常见场景给出修复方案:

场景1:使用AWS SDK for Java V1

1. 统一依赖版本

确保aws-java-sdk-sts与核心依赖aws-java-sdk-core版本完全一致,避免版本冲突。Maven示例依赖:

<dependencies>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-sts</artifactId>
        <version>1.12.500</version> <!-- 替换为最新稳定版 -->
    </dependency>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-core</artifactId>
        <version>1.12.500</version>
    </dependency>
</dependencies>

2. 修正客户端构建代码

确认导入正确的凭证提供者类,若直接调用withCredentials仍报错,可通过AWSStaticCredentialsProvider包装凭证:

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.securitytoken.AWSSecurityTokenService;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder;

public class StsClientFactory {
    public static AWSSecurityTokenService getStsClient() {
        return AWSSecurityTokenServiceClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(new ProfileCredentialsProvider().getCredentials()))
                .withRegion(Regions.US_EAST_1) // 替换为你的目标区域
                .build();
    }
}

场景2:使用AWS SDK for Java V2

若项目采用SDK V2,V1的AWSSecurityTokenServiceClientBuilder已被废弃,需切换到V2的API:

1. 添加V2 STS依赖

Maven示例:

<dependencies>
    <dependency>
        <groupId>software.amazon.awssdk</groupId>
        <artifactId>sts</artifactId>
        <version>2.25.40</version> <!-- 最新稳定版 -->
    </dependency>
    <dependency>
        <groupId>software.amazon.awssdk</groupId>
        <artifactId>profiles</artifactId>
        <version>2.25.40</version>
    </dependency>
</dependencies>

2. 重写客户端构建逻辑

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sts.StsClient;

public class StsV2ClientFactory {
    public static StsClient getStsClient() {
        return StsClient.builder()
                .credentialsProvider(ProfileCredentialsProvider.create())
                .region(Region.US_EAST_1) // 替换为你的目标区域
                .build();
    }
}

额外排查步骤

  • 执行mvn clean install(Maven)或gradle clean build(Gradle)刷新IDE依赖缓存
  • 确认REGION变量类型匹配:V1用com.amazonaws.regions.Regions枚举,V2用software.amazon.awssdk.regions.Region枚举

内容的提问来源于stack exchange,提问作者Xin Chen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 03:05:24