Aks*_*usa 2 java timertask spring-boot
我正在使用 TimerTask 运行 springboot 应用程序,我的服务对象显示为空。
我尝试了各种方法,但无法摆脱空指针异常。
主要类。
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
服务类
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);
}
Run Code Online (Sandbox Code Playgroud)
ListNotification 和 Notification 类工作正常。
安慰
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)
Run Code Online (Sandbox Code Playgroud)
这是 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);
}
}
Run Code Online (Sandbox Code Playgroud)
首先我得到 listElement 对象为空。所以我明白了,而不是在 schedule 方法的参数中使用新的 NotifyService() 我应该使用注入的 bean,但我不知道如何去做。
主类中的 run 方法是应用程序的起点。我不认为在启动应用程序之前您可以自动装配对象。尝试这样做
@SpringBootApplication
public class NotifyMain {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(NotifyMain.class, args);
NotifyService notifyService = (NotifyService) context.getBean(NotifyService.class);
context.getBean(Timer.class).schedule(notifyService, 10, 10);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
330 次 |
| 最近记录: |