如何修复此FirebaseApp名称[DEFAULT]已经存在!弹簧靴和firebase

时间:2018-06-13 05:52:52

标签: spring firebase spring-boot

我正在尝试为我的应用程序制作firebase auth和spring boot工作

这是我的Application.java

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.reactive.function.client.WebClient;

import java.io.IOException;

@SpringBootApplication
@EnableScheduling
public class Application {
    public static final Logger logger = LoggerFactory.getLogger("com.qmexpress");
    static String FB_BASE_URL="https://qm-tracker-backend.firebaseio.com";

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);
        try {
            FirebaseOptions options = new FirebaseOptions.Builder()
                    .setCredentials(GoogleCredentials.fromStream(new ClassPathResource("/qm-tracker-backend-firebase-adminsdk-wowh8-d8b0c278a7.json").getInputStream()))
                    .setDatabaseUrl(FB_BASE_URL)
                    .build();
            FirebaseApp.initializeApp(options);

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Bean
    public WebClient webClient() {
        return WebClient.create();
    }

}

运行应用程序后,我收到此消息

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:496)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: FirebaseApp name [DEFAULT] already exists!
    at com.google.common.base.Preconditions.checkState(Preconditions.java:444)
    at com.google.firebase.FirebaseApp.initializeApp(FirebaseApp.java:227)
    at com.google.firebase.FirebaseApp.initializeApp(FirebaseApp.java:218)
    at com.google.firebase.FirebaseApp.initializeApp(FirebaseApp.java:205)
    at com.qmexpress.Application.main(Application.java:37)
    ... 6 more

4 个答案:

答案 0 :(得分:4)

希望这可以帮助遇到同样问题的人:

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.reactive.function.client.WebClient;

import java.io.IOException;
@SpringBootApplication
@EnableScheduling
public class Application {
    public static final Logger logger = LoggerFactory.getLogger("com.example");
    static String FB_BASE_URL="https://example.firebaseio.com";

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);
        try {
            FirebaseOptions options = new FirebaseOptions.Builder()
                    .setCredentials(GoogleCredentials.fromStream(new ClassPathResource("/serviceAccountKey.json").getInputStream()))
                    .setDatabaseUrl(FB_BASE_URL)
                    .build();
            if(FirebaseApp.getApps().isEmpty()) { //<--- check with this line
                FirebaseApp.initializeApp(options);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Bean
    public WebClient webClient() {
        return WebClient.create();
    }

}

pom.xml,如果您想验证。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>logistic</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>Backend-API</name>
    <description>example</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>nz.net.ultraq.thymeleaf</groupId>
            <artifactId>thymeleaf-layout-dialect</artifactId>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.10</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160810</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.google.firebase</groupId>
            <artifactId>firebase-admin</artifactId>
            <version>6.2.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.codehaus.jackson</groupId>
                    <artifactId>jackson-core-asl</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.http-client</groupId>
                    <artifactId>google-http-client-jackson</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.http-client</groupId>
                    <artifactId>google-http-client-gson</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.api-client</groupId>
                    <artifactId>google-api-client-gson</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>joda-time</groupId>
                    <artifactId>joda-time</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.code.gson</groupId>
                    <artifactId>gson</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.auto.value</groupId>
                    <artifactId>auto-value</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.threeten</groupId>
                    <artifactId>threetenbp</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.json</groupId>
                    <artifactId>json</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.cloud</groupId>
                    <artifactId>google-cloud-firestore</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.apis</groupId>
                    <artifactId>google-api-services-storage</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.httpcomponents</groupId>
                    <artifactId>httpclient</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.httpcomponents</groupId>
                    <artifactId>httpcore</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.api</groupId>
                    <artifactId>gax</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.cloud</groupId>
                    <artifactId>google-cloud-storage</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
            <version>3.0.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.google.api-client</groupId>
            <artifactId>google-api-client-gson</artifactId>
            <version>1.23.0</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>


</project>

答案 1 :(得分:1)

是的,上面的解决方案是正确的,这是由于静态上下文引起的,例如在spring项目中,此bean从不抛出该异常

@Configuration
public class FirestoreConfiguration {
    @Value("${spring.gcp.firestore.projectid}")
    private String projectId;

    @Bean
    public Firestore FirestoreDb() throws IOException {
        // Use the application default credentials
        GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
        FirebaseOptions options = new FirebaseOptions.Builder()
            .setCredentials(credentials)
            .setProjectId(projectId)
            .build();
        FirebaseApp.initializeApp(options); //<-------- Here

        return FirestoreClient.getFirestore();
    }
}

但是在另一个Java项目中,我使用此代码,并且需要验证是否不存在。

public class FirestoreConfiguration {
    // static method
    public static Firestore FirestoreDb() throws IOException {
        // Use the application default credentials
        GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(credentials)
                .setProjectId(Envars.getEnvar("GOOGLE_CLOUD_PROJECT"))
                .build();

        if(FirebaseApp.getApps().isEmpty()) { //<------- Here
            FirebaseApp.initializeApp(options);
        }

        return FirestoreClient.getFirestore();
    }
}

答案 2 :(得分:1)

此配置对我有用

@Bean
FirebaseMessaging firebaseMessaging() throws IOException {
    GoogleCredentials googleCredentials = GoogleCredentials
            .fromStream(new ClassPathResource("fcm/appName-fa2db-firebase-adminsdk-zn2y1-98b7de2ad9.json").getInputStream());
    FirebaseOptions firebaseOptions = FirebaseOptions
            .builder()
            .setCredentials(googleCredentials)
            .build();
    FirebaseApp app = null;
    if(FirebaseApp.getApps().isEmpty()) {
        app = FirebaseApp.initializeApp(firebaseOptions, "appName");
    }else {
        app = FirebaseApp.initializeApp(firebaseOptions);
    }
    
    return FirebaseMessaging.getInstance(app);
}

答案 3 :(得分:0)

出现此异常是因为您试图再次创建[DEFAULT] FirebaseApp,只需在初始化之前添加验证即可检查它是否存在,就像这样:

if(FirebaseApp.getInstance(FirebaseApp.DEFAULT_APP_NAME) != null) {
    try {.... rest of your code
}

另外,最好添加一个配置类,而不是在main方法中添加代码。