使用Microsoft Graph Java SDK遭遇ClassNotFoundException问题求助
解决方案
问题根源
java.lang.ClassNotFoundException: com.azure.core.credential.TokenCredential 意味着项目类路径中缺少Azure Core库——该类是azure-identity的依赖项,可能因依赖传递失败、版本冲突或构建缓存问题未被正确引入。同时你使用的Graph SDK 5.x版本已弃用TokenCredentialAuthProvider,继续使用会引发兼容性问题。
修复步骤
1. 调整依赖配置
在build.gradle中显式添加与azure-identity 1.7.1兼容的azure-core依赖,确保依赖完整:
dependencies { implementation 'com.azure:azure-identity:1.7.1' implementation 'com.azure:azure-core:1.28.0' implementation 'com.microsoft.graph:microsoft-graph:5.42.0' }
2. 更新代码适配Graph SDK 5.x
Graph SDK 5.x使用AzureIdentityAuthenticationProvider替代旧的TokenCredentialAuthProvider,修改代码如下:
import com.azure.identity.ClientSecretCredential; import com.azure.identity.ClientSecretCredentialBuilder; import com.microsoft.graph.authentication.AzureIdentityAuthenticationProvider; import com.microsoft.graph.graphserviceclient.GraphServiceClient; import java.util.List; public class GraphClientExample { public static void main(String[] args) { final ClientSecretCredential credential = new ClientSecretCredentialBuilder() .clientId("...") .clientSecret("...") .tenantId("...") .build(); final AzureIdentityAuthenticationProvider authProvider = new AzureIdentityAuthenticationProvider( credential, List.of("files.readwrite.all") ); final GraphServiceClient client = GraphServiceClient .builder() .authenticationProvider(authProvider) .buildClient(); } }
3. 清理并重新构建项目
执行以下命令清理缓存并重新拉取依赖:
./gradlew clean build --refresh-dependencies
内容的提问来源于stack exchange,提问作者kerelape
相关产品推荐
相关产品推荐

