• 아래 코드를 pom.xml에 추가한다.

    <dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-test</artifactId>
    			<scope>test</scope>
    </dependency>
    
    <dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-devtools</artifactId>
    			<scope>runtime</scope>
    			<optional>true</optional>
    </dependency>
    
    <dependency>
    			<groupId>com.google.firebase</groupId>
    			<artifactId>firebase-admin</artifactId>
    			<version>9.1.1</version>
    </dependency>
    
  • 아래 코드를 application.properties에 추가한다.

    # Firebase setting
    firebase.config=hotdeal-server-firebase-adminsdk-7lweh-df7d0cbbd1.json
    firebase.project.id=sample-7667c
    

    ( config는 아까 Firebase 서버측에서 다운로드하여 추가한 파일명을 말한다. )

    ( id는 프로젝트 설정 → 프로젝트 ID에 값을 가져오면 된다. )

  • FirebaseConfig.java를 작성한다.

    import java.io.FileInputStream;
    import java.io.InputStream;
    
    import javax.annotation.PostConstruct;
    
    import org.springframework.context.annotation.Configuration;
    
    import com.google.api.client.util.Value;
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    
    @Configuration
    public class FirebaseConfig {
    
        @Value("${firebase.config}")
        private String firebaseConfig;
        @Value("${firebase.project.id}")
        private String firebaseProjectId;
    
        @PostConstruct
        public void initialize() {
            try {
                InputStream serviceAccount = new FileInputStream(firebaseConfig);
                FirebaseOptions options = new FirebaseOptions.Builder()
                        .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                        .setProjectId(firebaseProjectId)
                        .build();
    
                if (FirebaseApp.getApps().isEmpty()) {
                    FirebaseApp.initializeApp(options);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    • Firebase 설정을 위해 파일을 통째로 가져와야 하므로 FileInputStream을 사용하여 가져온다.

    • GoogleCredentials를 사용하면 stream을 통해 Credential을 추출할 수 있다.

      • import com.google.auth.oauth2.GoogleCredentials;
    • 추출한 Credentials을 포함한 FirebaseOptions을 통해 FirebaseApp을 초기화 후 Spring을 사용할 수 있다.

  • FirebaseService.java를 작성한다.

    import org.springframework.stereotype.Service;
    
    import com.google.firebase.messaging.FirebaseMessaging;
    import com.google.firebase.messaging.FirebaseMessagingException;
    import com.google.firebase.messaging.Message;
    
    @Service
    public class FirebaseService {
    
        public String sendNotification(String content, String token) {
            try {
                Message message = Message.builder()
                        .setToken(token)
                        .putData("title", content)
                        .build();
    
                String response = FirebaseMessaging.getInstance().send(message);
                // return response if firebase messaging is successfully completed.
                return response;
    
            } catch (FirebaseMessagingException e) {
                e.printStackTrace();
                return "Failed";
            }
        }
    }
    
    • Message 전송을 위해 Message 인스턴스를 생성할 때 토큰을 넣어야 하는데, 이 토큰이 무엇을 의미하는지 (클라이언트측) Configuration에서 살펴본다.

    • FirebaseMessaging이 성공적으로 메시지 전송을 마치면 전송 결과가 response로 돌아온다.

    • 해당 알림 전송 기능이 필요한 곳에 “sendNotification” 메서드를 삽입하여 사용하면 된다.