英文:
FirebaseApp with name [DEFAULT] doesn't exist. (For Spring Boot)
问题
以下是你提供的代码的中文翻译部分:
我遵循了这个链接来创建一个 Firebase 应用程序 - https://blog.mestwin.net/send-push-notifications-from-spring-boot-server-side-application-using-fcm/
但我遇到了这个错误 - FirebaseApp 的名称为 [DEFAULT] 不存在。 (对于 Spring Boot)
我已经在应用程序属性中添加了 JSON 密钥及其路径... 我无法找出我哪里错了...
这是我的 FCMInitializer -
// 代码部分已省略
这是我的 FCM Service -
// 代码部分已省略
这是我的 PushNotification Service -
// 代码部分已省略
这是我的 PushNotificationController -
// 代码部分已省略
这是我的 Notification Parameter -
// 代码部分已省略
这是我的 PushNotificationRequest -
// 代码部分已省略
这是我的 push notification Response -
// 代码部分已省略
以及这是我的 application-properties:
app.firebase-configuration-file=google/push-notifications-example-firebase-adminsdk.json
app.notifications.defaults={topic: 'common', title: 'Common topic - Hello', message: 'Sending test message 😀', token: 'ss22t03wz208eg:APA2idkkow223FE_0v5yHxqCLTyxAQafj6nWaqi4QzwZTW004q1PUux63UsFN', payloadMessageId: '123', payloadData: 'Hello. This is payload content.'}
请原谅我,因为我在 Firebase 方面还是一个初学者... 我不知道我错在哪里... 我认为可能在应用程序属性中... 另外,我在 FCMService 类的 FirebaseMessaging.getInstance().sendAsync(message).get(); 处遇到了错误。提前感谢。
英文:
I followed this link to create a fire base application-https://blog.mestwin.net/send-push-notifications-from-spring-boot-server-side-application-using-fcm/
And I am getting this error-FirebaseApp with name [DEFAULT] doesn't exist. (For Spring Boot)
I have added the JSON Key and and its path in application properties....Am not able to figure out where I Am going wrong...
This is my FCMInitializer-
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.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.IOException;
@Service
public class FCMInitializer {
@Value("${app.firebase-configuration-file}")
private String firebaseConfigPath;
Logger logger = LoggerFactory.getLogger(FCMInitializer.class);
@PostConstruct
public void initialize() {
try {
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(new ClassPathResource(firebaseConfigPath).getInputStream())).build();
if (FirebaseApp.getApps().isEmpty()) {
FirebaseApp.initializeApp(options);
logger.info("Firebase application has been initialized");
}
} catch (IOException e) {
logger.error(e.getMessage());
}
}
}
This is my FCM Service-
import com.google.firebase.messaging.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ExecutionException;
//import org.slf4j.LoggerFactory;
//import com.highpeak.av.pushnotification.dto.PushNotificationRequest;
@Slf4j
@Service
public class FCMService {
private Logger logger = LoggerFactory.getLogger(FCMService.class);
public void sendMessage(Map<String, String> data, PushNotificationRequest request)
throws InterruptedException, ExecutionException {
Message message = getPreconfiguredMessageWithData(data, request);
String response = sendAndGetResponse(message);
log.info("Sent message with data. Topic: " + request.getTopic() + ", " + response);
}
private Message getPreconfiguredMessageWithData(Map<String, String> data, PushNotificationRequest request) {
return getPreconfiguredMessageBuilder(request).putAllData(data).setTopic(request.getTopic())
.build();
}
public void sendMessageWithoutData(PushNotificationRequest request)
throws InterruptedException, ExecutionException {
Message message = getPreconfiguredMessageWithoutData(request);
String response = sendAndGetResponse(message);
log.info("Sent message without data. Topic: " + request.getTopic() + ", " + response);
}
private String sendAndGetResponse(Message message) throws InterruptedException, ExecutionException {
return FirebaseMessaging.getInstance().sendAsync(message).get();
}
private AndroidConfig getAndroidConfig(String topic) {
return AndroidConfig.builder()
.setTtl(Duration.ofMinutes(2).toMillis()).setCollapseKey(topic)
.setPriority(AndroidConfig.Priority.HIGH)
.setNotification(AndroidNotification.builder().setSound(NotificationParameter.SOUND.getValue())
.setColor(NotificationParameter.COLOR.getValue()).setTag(topic).build()).build();
}
private ApnsConfig getApnsConfig(String topic) {
return ApnsConfig.builder()
.setAps(Aps.builder().setCategory(topic).setThreadId(topic).build()).build();
}
private Message getPreconfiguredMessageWithoutData(PushNotificationRequest request) {
return getPreconfiguredMessageBuilder(request).setTopic(request.getTopic())
.build();
}
private Message.Builder getPreconfiguredMessageBuilder(PushNotificationRequest request) {
AndroidConfig androidConfig = getAndroidConfig(request.getTopic());
ApnsConfig apnsConfig = getApnsConfig(request.getTopic());
return Message.builder()
.setApnsConfig(apnsConfig).setAndroidConfig(androidConfig).setNotification(
new Notification(request.getTitle(), request.getMessage()));
}
public void sendMessageToToken(PushNotificationRequest request)
throws InterruptedException, ExecutionException {
Message message = getPreconfiguredMessageToToken(request);
String response = sendAndGetResponse(message);
log.info("Sent message to token. Device token: " + request.getToken() + ", " + response);
}
private Message getPreconfiguredMessageToToken(PushNotificationRequest request) {
return getPreconfiguredMessageBuilder(request).setToken(request.getToken())
.build();
}
}
This is my PushNotification Service-
package com.example.MyFirstPushNotificationService.PushNotificationsDemo;
import com.google.api.client.util.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
@Service
public class PushNotificationService {
@Value("#{${app.notifications.defaults}}")
private Map<String, String> defaults;
private Logger logger = LoggerFactory.getLogger(PushNotificationService.class);
private FCMService fcmService;
public PushNotificationService(FCMService fcmService) {
this.fcmService = fcmService;
}
@Scheduled(initialDelay = 60000, fixedDelay = 60000)
public void sendSamplePushNotification() {
try {
fcmService.sendMessageWithoutData(getSamplePushNotificationRequest());
} catch (InterruptedException | ExecutionException e) {
logger.error(e.getMessage());
}
}
public void sendPushNotification(PushNotificationRequest request) {
try {
fcmService.sendMessage(getSamplePayloadData(), request);
} catch (InterruptedException | ExecutionException e) {
logger.error(e.getMessage());
}
}
public void sendPushNotificationWithoutData(PushNotificationRequest request) {
try {
fcmService.sendMessageWithoutData(request);
} catch (InterruptedException | ExecutionException e) {
logger.error(e.getMessage());
}
}
public void sendPushNotificationToToken(PushNotificationRequest request) {
try {
fcmService.sendMessageToToken(request);
} catch (InterruptedException | ExecutionException e) {
logger.error(e.getMessage());
}
}
private Map<String, String> getSamplePayloadData() {
Map<String, String> pushData = new HashMap<>();
pushData.put("messageId", defaults.get("payloadMessageId"));
pushData.put("text", defaults.get("payloadData") + " " + LocalDateTime.now());
return pushData;
}
private PushNotificationRequest getSamplePushNotificationRequest() {
PushNotificationRequest request = new PushNotificationRequest(defaults.get("title"),
defaults.get("message"),
defaults.get("topic"));
return request;
}
}
This is my PushNotificationController-
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PushNotificationController {
private PushNotificationService pushNotificationService;
public PushNotificationController(PushNotificationService pushNotificationService) {
this.pushNotificationService = pushNotificationService;
}
@PostMapping("/notification/topic")
public ResponseEntity sendNotification(@RequestBody PushNotificationRequest request) {
pushNotificationService.sendPushNotificationWithoutData(request);
return new ResponseEntity<>(new PushNotificationResponse(HttpStatus.OK.value(), "Notification has been sent."), HttpStatus.OK);
}
@PostMapping("/notification/token")
public ResponseEntity sendTokenNotification(@RequestBody PushNotificationRequest request) {
pushNotificationService.sendPushNotificationToToken(request);
return new ResponseEntity<>(new PushNotificationResponse(HttpStatus.OK.value(), "Notification has been sent."), HttpStatus.OK);
}
@PostMapping("/notification/data")
public ResponseEntity sendDataNotification(@RequestBody PushNotificationRequest request) {
pushNotificationService.sendPushNotification(request);
return new ResponseEntity<>(new PushNotificationResponse(HttpStatus.OK.value(), "Notification has been sent."), HttpStatus.OK);
}
@GetMapping("/notification")
public ResponseEntity sendSampleNotification() {
pushNotificationService.sendSamplePushNotification();
return new ResponseEntity<>(new PushNotificationResponse(HttpStatus.OK.value(), "Notification has been sent."), HttpStatus.OK);
}
}
This is my Notification Parameter-
public enum NotificationParameter {
SOUND("default"),
COLOR("#FFFF00");
private String value;
NotificationParameter(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
This is my PushNotificationRequest-
public class PushNotificationRequest {
private String title;
private String message;
private String topic;
private String token;
public PushNotificationRequest() {
}
public PushNotificationRequest(String title, String messageBody, String topicName) {
this.title = title;
this.message = messageBody;
this.topic = topicName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
This is my push notification Response-
package com.example.MyFirstPushNotificationService.PushNotificationsDemo;
public class PushNotificationResponse {
private int status;
private String message;
public PushNotificationResponse() {
}
public PushNotificationResponse(int status, String message) {
this.status = status;
this.message = message;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
And this is my application-properties:
app.firebase-configuration-file=google/push-notifications-example-firebase-adminsdk.json
app.notifications.defaults={topic: 'common', title: 'Common topic - Hello', message: 'Sending test message \uD83D\uDE42', token: 'ss22t03wz208eg:APA2idkkow223FE_0v5yHxqCLTyxAQafj6nWaqi4QzwZTW004q1PUux63UsFN', payloadMessageId: '123', payloadData: 'Hello. This is payload content.'}
Please forgive me,as i am still a beginner in Fire base.....I am not getting where I am gong wrong....I think its in application properties.....Also I am getting the error at-FirebaseMessaging.getInstance().sendAsync(message).get(); of FCMService class.
Thanks in Advance
答案1
得分: 5
我之前遇到了同样的错误,请尝试对 FCMInitializer.java 中的 initialize() 方法进行调试。在我的情况下,问题是因为 JSON 文件路径不正确导致的,提供了正确的路径后,问题得以解决。
英文:
I was having same error, try debugging initialize() method in FCMInitializer.java, in my case it was having wrong JSON file path, after providing correct path, issue was resolved.
答案2
得分: 2
我希望准时到达,我遇到了相同的问题,我的解决方案是按照 Firebase 控制台建议的进行身份验证。
@Service
public class FCMInitializer {
Logger logger = LoggerFactory.getLogger(FCMInitializer.class);
@PostConstruct
public void initialize() {
try {
FileInputStream serviceAccount =
new FileInputStream("path/to/serviceAccountKey.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://your-project.firebaseio.com")
.build();
FirebaseApp.initializeApp(options);
} catch (IOException e) {
logger.error(e.getMessage());
}
}
}
英文:
I hope to arrive on time, I had the same problem and my solution was to put the authentication that the firebase console suggests.
@Service
public class FCMInitializer {
Logger logger = LoggerFactory.getLogger(FCMInitializer.class);
@PostConstruct
public void initialize() {
try {
FileInputStream serviceAccount =
new FileInputStream("path/to/serviceAccountKey.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://your-project.firebaseio.com")
.build();
FirebaseApp.initializeApp(options);
} catch (IOException e) {
logger.error(e.getMessage());
}
}
}
答案3
得分: 1
请为依赖于 Firebase 的服务添加 @DependsOn("fCMInitializer")
。
示例:
@Service
@DependsOn("fCMInitializer")
public class PushNotificationService
英文:
Add @DependsOn("fCMInitializer")
to services that depend on Firebase.
Example:
@Service
@DependsOn("fCMInitializer")
public class PushNotificationService
答案4
得分: 0
问题出在 Firebase SDK 管理员 JSON 文件的文件路径上。
为了修复这个错误,JSON 文件的位置应该是 target/classes/<文件名在此处>.json
,因为这是 Maven 处理后放置资源文件的规范位置。
英文:
The problem is with the file path to the Firebase SDK Admin JSON file.
To fix the error the location of the JSON file should have been target/classes/<File name here>.json
as this is the canonical place where Maven puts resource files after processing.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论