I am running springboot application with TimerTask my object of service is showing null.
I have tried various methods but unable to get rid of the Null pointer exception.
main class .
@SpringBootApplication
@ComponentScan(basePackages = {"com.comments.demo"})
public class NotifyMain {
@Autowired
static
NotifyService notifyService;
public static void main(String[] args) {
Timer timer1 = new Timer();
timer1.schedule(notifyService, 10, 10);
SpringApplication.run(NotifyMain.class, args);
}
}
Service class
package com.comments.demo;
@Service
@Configurable
public class NotifyService extends TimerTask{
@Autowired
ListNotification listElement;
@Override
public void run() {
Notification notification= new Notification();
listElement.add(notification);
}
ListNotification and Notification class are working fine.
console
Exception in thread "main" java.lang.NullPointerException
at java.util.Timer.sched(Timer.java:399)
at java.util.Timer.schedule(Timer.java:248)
at com.comments.demo.NotifyMain.main(NotifyMain.java:22)
here is the code of ListNotification
package com.comments.demo;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ListNotification {
private List<Notification> notifications = new ArrayList<>();
@Autowired
private NotificationObserver notificationObserver;
public void setNotifications(List<Notification> notifications) {
this.notifications = notifications;
}
public void add(Notification notification) {
notifications.add(notification);
notifyListeners(notification);
}
private void notifyListeners(Notification newValue) {
notificationObserver.observation(newValue);
}
}
first I was getting listElement object null. so i got that instead of using the new NotifyService() in parameter of schedule method i should use the injected bean but how to do it I don't know.