簡體   English   中英

Firebase 管理員 SDK - java.lang.NoClassDefFoundError

[英]Firebase Admin SDK - java.lang.NoClassDefFoundError

I'm trying to add the Firebase Admin SDK to my Java Web App, but getting the following error on init:

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

我將 Firebase 依賴項添加到我的 pom.xml 文件中,並使用以下代碼來初始化 Firebase: ClassLoader classLoader(.getcurrentContextClassLoader(.getcurrentContextClassLoader); InputStream 是 = classloader.getResourceAsStream("serviceAccount.json");

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

    FirebaseApp.initializeApp(options);+

誰能幫我?

這是您可以使用的實現;

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

參考 - 為什么使用@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());
        }

    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM