0

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)

I added the Firebase Dependency to my pom.xml file and use the following code to init Firebase : ClassLoader 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);+

Can anyone help me ?

Thiemo
  • 11
  • 1

1 Answers1

0

Here's an implementation you can use;

You might need to use @PostConstruct annotation.

reference - Why use @PostConstruct?

Suggested Implementation

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());
        }

    }

}
ThivankaW
  • 511
  • 1
  • 8
  • 21
  • Thanks for the answer. Unfortunately I'm not using spring. The project is for uni and I'm not allowed to use any Frameworks.... – Thiemo Jun 12 '21 at 09:50