1

I tried to use org.springframework.boot:spring-boot-devtools to speed up development.

My project uses Firebase to authenticate some requests. Firebase initialized via:

@PostConstruct
public void instantiateFirebase() throws IOException {
    FirebaseOptions options = new FirebaseOptions.Builder()
            .setDatabaseUrl(String.format("https://%s.firebaseio.com", configuration.getFirebaseDatabase()))
            .setServiceAccount(serviceJson.getInputStream())
            .build();
    FirebaseApp.initializeApp(options);
}

After context reloading on changing .class file Spring reports error:

Caused by: java.lang.IllegalStateException: FirebaseApp name [DEFAULT] already exists!
    at com.google.firebase.internal.Preconditions.checkState(Preconditions.java:173)
    at com.google.firebase.FirebaseApp.initializeApp(FirebaseApp.java:180)
    at com.google.firebase.FirebaseApp.initializeApp(FirebaseApp.java:160)

What Firebase API allow deregister/destroy FirebaseApp that I should use in @PreDestroy?

gavenkoa
  • 45,285
  • 19
  • 251
  • 303

1 Answers1

3

Looks like it is not possible to disable/shutdown/reinitialize Firebase app.

In my case it is fine to keep that instance in memory without changes.

Depending on your requirements you may use as simple as:

@PostConstruct
public void instantiateFirebase() throws IOException {
    // We use only FirebaseApp.DEFAULT_APP_NAME, so check is simple.
    if ( ! FirebaseApp.getApps().isEmpty())
        return;

    Resource serviceJson = applicationContext.getResource(String.format("classpath:firebase/%s", configuration.getFirebaseServiceJson()));

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setDatabaseUrl(String.format("https://%s.firebaseio.com", configuration.getFirebaseDatabase()))
            .setServiceAccount(serviceJson.getInputStream())
            .build();
    FirebaseApp.initializeApp(options);
}

or filter data like:

for (FirebaseApp app : FirebaseApp.getApps()) {
    if (app.getName().equals(FirebaseApp.DEFAULT_APP_NAME))
        return;
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
gavenkoa
  • 45,285
  • 19
  • 251
  • 303
  • 1
    This is indeed a common way to retrieve the existing default app. If you need to actually change the configuration, you should create a new app instance. See [the Firebase documentation](https://firebase.google.com/docs/configure/#support_multiple_environments_in_your_android_application) or [my answer here](http://stackoverflow.com/questions/37634767/how-to-connect-to-more-than-one-firebase-database-from-an-android-app/37643374#37643374) for more info on how to do that. – Frank van Puffelen Jul 09 '17 at 15:14