【问题标题】:Firebase Admin SDK - java.lang.NoClassDefFoundErrorFirebase 管理 SDK - java.lang.NoClassDefFoundError
【发布时间】:2021-06-12 08:00:36
【问题描述】:

我正在尝试将 Firebase Admin SDK 添加到我的 Java Web 应用程序中,但出现以下错误 初始化:

java.lang.NoClassDefFoundError: com/google/firebase/FirebaseOptions
        at backend.servlets.Init.contextInitialized(Init.java:33)

我将 Firebase 依赖项添加到我的 pom.xml 文件中,并使用以下代码来初始化 Firebase: ClassLoader 类加载器 = Thread.currentThread().getContextClassLoader(); InputStream is = classloader.getResourceAsStream("serviceAccount.json");

    FirebaseOptions options = null;
    try {
        options = FirebaseOptions.builder()
                .setCredentials(GoogleCredentials.fromStream(is))
                .build();
    } catch (IOException e) {
        e.printStackTrace();
    }

    FirebaseApp.initializeApp(options);+

谁能帮帮我?

【问题讨论】:

  • 你在用弹簧吗?
  • 不,我没有使用弹簧。该项目是针对 uni 的,我不允许使用任何框架....

标签: java firebase


【解决方案1】:

这是一个你可以使用的实现;

您可能需要使用@PostConstruct 注解。

参考 - Why use @PostConstruct?

建议实施

package com.test.config;

import java.io.FileInputStream;

import javax.annotation.PostConstruct;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.FirebaseMessaging;

@Configuration
public class FirebaseConfig {

    @Bean
    public FirebaseMessaging firebaseMessaging() {
        FirebaseMessaging firebase = FirebaseMessaging.getInstance();
        return firebase;
    }

    @PostConstruct
    public void init() {

        try (FileInputStream serviceAccount = new FileInputStream(
                ResourceUtils.getFile("classpath:ServiceAccount.json"));) {

            @SuppressWarnings("deprecation")
            FirebaseOptions options = new FirebaseOptions.Builder()
                    .setCredentials(GoogleCredentials.fromStream(serviceAccount)).build();
            if (FirebaseApp.getApps().isEmpty()) {
                FirebaseApp.initializeApp(options);
            }

            System.out.println("#####Firebase Initialized#####");

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

}

【讨论】:

  • 感谢您的回答。不幸的是,我没有使用弹簧。该项目是针对 uni 的,我不允许使用任何框架....
猜你喜欢
  • 2017-09-23
  • 2019-03-14
  • 1970-01-01
  • 2019-12-28
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
相关资源
最近更新 更多