There is a class of my thread:

@Component public class MailThread extends Thread { @Autowired private MessageRepo messageRepo; public MailThread() {} @Override public void run() { while (true) { try { Iterable<Message> messages; messages = messageRepo.findByTime("18:50"); for(Message message : messages){ System.out.println(message.toString()); } System.out.println("minute"); Thread.sleep(60000); } catch (InterruptedException ex) { System.out.println(ex.getMessage()); } } } } 

MessageRepo:

 public interface MessageRepo extends JpaRepository<Message, Long> { List<Message> findByTime(String time); } 

I call my thread from Main:

 @SpringBootApplication public class Application { public static void main(String[] args){ SpringApplication.run(Application.class, args); new MailThread().run(); } } 

But I get this error:

 Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:564) at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) Caused by: java.lang.NullPointerException at project.components.MailThread.run(MailThread.java:39) at project.Application.main(Application.java:12) ... 5 mor 

Just where I'm trying to find all the messages from the database (messages = messageRepo.findByTime ("18:50")) When I call from a normal controller, everything works. Tell me please, what's the problem?

1 answer 1

The @Autowire works only on objects created by the Spring container, and not by the new operator.

  • Understood, and how to solve the problem? - user314917
  • And to ensure that every minute from the database got the data? - user314917
  • That is, how to create a MailThread object automatically and run the run method? - user314917
  • five
    Read about @Schedule annotation and do not invent bicycles - GenCloud
  • Accepted, thank you. - user314917