본문 바로가기
Spring/Spring Boot

[Spring Boot - Firebase] 연동하기

by seoyamin 2023. 10. 28.
준비물 : Firebase 프로젝트

 

기존 Firestore Database에서 스프링 서버로 데이터를 불러오기 위해 연동하는 과정을 진행해 볼 것이다.

Firebase 프로젝트는 이미 생성했다고 가정하고 진행하겠다.

 

 

1. Firebase 비공개 키 다운로드

Firebase 프로젝트 대시보드의 프로젝트 개요 / 프로젝트 설정 / 서비스 계정으로 이동한다.

 

SDK 언어를 Java로 설정한 후, 새 비공개 키 생성을 클릭한다.

 

스프링 프로젝트의 src / main / resources에 다운받아진 json 비공개 키를 복붙한다.

파일명은 각자 지정하면 되는데, 나는 firebaseServiceAccountKey.json으로 저장했다.

 

 

2. FirebaseConfig 설정

스프링부트 프로젝트에 FirebaseConfig.java 파일을 만들고 Firebase와 관련된 설정을 해준다.

1번에서 다운로드한 firebaseServiceAccountKey.json을 바탕으로 init하는 과정이 진행되는 곳이다.

 

// FirebaseConfig.java

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Configuration;

import java.io.FileInputStream;

@Configuration
public class FirebaseConfig {

    @PostConstruct
    public void init() {
        try {
            FileInputStream serviceAccount = new FileInputStream("/src/main/resources/firebaseServiceAccountKey.json");
            FirebaseOptions options = new FirebaseOptions.Builder()
                    .setCredentials(GoogleCredentials.fromStream(serviceAccount)).build();

            FirebaseApp.initializeApp(options);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

 

3. Firestore 이용해보기

아래는 Firestore에서 패널 정보를 가져와 Java Entity로 가공하는 예제 코드이다.

ApiFuture과 Firebase 문법을 이용하면 간편하게 데이터를 가져올 수 있다.

private Panel createPanelFromFirestore(String uid) throws ExecutionException, InterruptedException, ParseException {
    Firestore db = FirestoreClient.getFirestore();

    // Fetch - Firebase Panel Info
    ApiFuture<DocumentSnapshot> future = db.collection(COLLECTION_NAME).document(uid).get();
    DocumentSnapshot documentSnapshot = future.get();

    if(documentSnapshot.exists()) {
        PanelInfoDAO panelInfoDAO = PanelInfoDAO.builder()
                .uid(documentSnapshot.getString("uid"))
                .name(documentSnapshot.getString("name"))
                .email(documentSnapshot.getString("email"))
                .build();

        Panel panel = panelMapper.toEntityExisting(panelInfoDAO, panelInfoFirstSurveyDAO);
        return panel;

    } else {
        throw PanelNotFoundFB.EXCEPTION;
    }
}