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

Java后端集成Firebase云消息推送时报java.lang.NoSuchMethodError错误的求助

解决Firebase推送时的NoSuchMethodError: ServiceAccountCredentials.getProjectId()错误

这个错误十有八九是依赖版本不兼容导致的——具体来说是你的项目里google-auth-library-oauth2-http库的版本太低,和当前使用的Firebase Admin SDK版本不匹配,新版本的Firebase SDK需要调用ServiceAccountCredentials.getProjectId()这个方法,但旧版的auth库并没有提供它。

下面是一步步的解决办法:

1. 统一Firebase Admin SDK和相关依赖的版本

首先确保你使用的是Firebase Admin SDK的稳定最新版,同时让Google Auth相关依赖自动适配SDK的版本,避免手动指定版本导致冲突。

Maven示例(pom.xml)

<dependency>
    <groupId>com.google.firebase</groupId>
    <artifactId>firebase-admin</artifactId>
    <version>9.2.0</version> <!-- 替换成最新稳定版 -->
</dependency>

不需要单独引入google-auth-library-oauth2-http,因为Firebase Admin SDK已经包含了兼容的版本。如果之前手动加过这个依赖,直接删掉它。

Gradle示例(build.gradle)

implementation 'com.google.firebase:firebase-admin:9.2.0' // 替换成最新稳定版

同样,不要单独声明auth库的依赖,让SDK自动管理。

2. 排除冲突的旧依赖

如果你的项目里其他依赖(比如Google Cloud相关库)引入了旧版的google-auth-library-oauth2-http,需要显式排除它们:

Maven排除示例

<dependency>
    <groupId>某个冲突的依赖groupId</groupId>
    <artifactId>某个冲突的依赖artifactId</artifactId>
    <version>xxx</version>
    <exclusions>
        <exclusion>
            <groupId>com.google.auth</groupId>
            <artifactId>google-auth-library-oauth2-http</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Gradle排除示例

implementation('某个冲突的依赖groupId:某个冲突的依赖artifactId:xxx') {
    exclude group: 'com.google.auth', module: 'google-auth-library-oauth2-http'
}

3. 清理项目缓存并重新构建

  • Maven:执行mvn clean install
  • Gradle:执行./gradlew clean build(Windows用gradlew clean build)
    这一步能确保你下载的是最新的兼容依赖,而不是本地缓存的旧版本。

4. 验证初始化代码

虽然你说[DEFAULT]应用初始化成功,但还是确认下初始化方式是否正确,避免因为初始化时用了旧的Credentials类导致问题:

FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");

FirebaseOptions options = new FirebaseOptions.Builder()
    .setCredentials(GoogleCredentials.fromStream(serviceAccount))
    .build();

FirebaseApp.initializeApp(options);

不要手动创建ServiceAccountCredentials实例,而是用GoogleCredentials.fromStream()来处理,这样能保证使用的是SDK兼容的版本。

做完这些步骤后,再重新运行你的sendToToken()方法,应该就能解决这个NoSuchMethodError了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:32:36