There is some bin

@Repository @Transactional public class UserServiceImpl implements UserService { ... } 

It must be called in another method that creates new threads:

 @Autowired UserService userService; new Thread(new NewClientsThread(new Runnable(){ @Override public void run() { //Здесь вызывается userService } })).start(); 

But when working at the time of accessing the bin, I get a NullPointerException. I understand that the context of the spring is not available in the new stream.

Are there any ways to overcome this problem?

  • one
    Add a UserService field to NewClientsThread. And add a constructor of type NewClientsThread (UserService u, Runnable target); And pass your userService parameter to the constructor - Chubatiy
  • one
    bin wasn’t injected, see the start logs at the start - AdamSkywalker

1 answer 1

Replace

 new Thread(new NewClientsThread(new Runnable(){ @Override public void run() { //Здесь вызывается userService } })).start(); 

on

 new Thread(new NewClientsThread(new Runnable(){ @Autowired UserService userService; @Override public void run() { SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); //далее вызывается userService } })).start(); 

I want to note that, in my opinion, you have somewhere an architectural flaw crept in, because the creation of threads should be used in very rare cases.

  • And how can you do without threads if you need parallel execution of several processes? - carapuz
  • one
    @carapuz in any way. I want to note that I meant just the explicit creation of threads. They have a lot of problems, including memory leaks and pool overflows. If you have something planned, it is better to use the scheduler and run the control's bin method from it. If situational flows are nevertheless necessary, it is better to run them through pools - Temka is also