I defined 2 classes.
AndroidPush.java
public class AndroidPush {
private static String SERVER_KEY = "XXXXX";
private static String DEVICE_TOKEN = "XXXXX";
public static void main(String[] args) throws Exception {
String title = args[0];
String message = args[1];
sendPushNotification(title, message);
}
private static void sendPushNotification(String title, String message) throws Exception {
String pushMessage = "{\"data\":{\"title\":\"" +
title +
"\",\"message\":\"" +
message +
"\"},\"to\":\"" +
DEVICE_TOKEN +
"\"}";
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream outputStream = conn.getOutputStream();
outputStream.write(pushMessage.getBytes());
}
}
And
NotificationProcessing.java
public class NotificationProcessing {
private static NotificationRepo notificationRepo;
@Autowired
public NotificationProcessing(NotificationRepo notificationRepo) {
NotificationProcessing.notificationRepo = notificationRepo;
}
public static void addNotification(Offer offer) throws Exception {
Notification notification = new Notification();
notification.setId(null);
notification.setMessage("There is new offer: " + offer.getTitle());
notification.setLink("/offers/" + offer.getId());
notificationRepo.save(notification);
String[] arguments = new String[] {"New Offer", notification.getMessage()};
AndroidPush.main(arguments);
}
}
I call my repository inside static method like Francisco Speath answered on this question @Autowired and static method
But then, if I try to call my method and store notification I am getting this error:
java.lang.NullPointerException: null
on this line: notificationRepo.save(notification);
I suppose this is because using repository inside of static method, but if I remove static from everywhere and try to access addNotification() method there is another error:
non-static method cannot be referenced from a static context
I'm calling this addNotification() method inside my RestController
@RequestMapping(method = RequestMethod.POST)
public Offer newOffer (@RequestBody Offer offer) {
NotificationProcessing.addCampaignNotification(offer);
return repo.save(offer);
}
So what is solution for using repository inside static method?