java – Spring – Thread dependency injection

Question:

I need a little help.

I'm doing some tests with Spring Boot and I have my services + some processes that I want to run in thread. Each thread will execute its own service.

When I do service dependency injection through my main class and pass it into the thread's constructor, everything works the way I want.

However, I don't like the way it is implemented and I believe that there is a prettier way to do this, that is, the thread itself inject the service that it will use.

How is today:

Main Class:

@Autowired
ITesteService service;

public static void main(String[] args) {
    SpringApplication.run(BaseUnicaApplication.class, args);
}

@Override
public void run(ApplicationArguments args) throws Exception {

    ExecutorService executor = Executors.newFixedThreadPool(1);
                    executor.submit(new TesteProcessor(service));

}

Thread

public class TesteProcessor implements Runnable  {

private ITesteService service;

public TesteProcessor() {
    this.service = service;
}

public void run() {

    service.save

I've already tried to make the dependency injection directly on the service, but NullPointer occurs when I use the service.

public class TesteProcessor implements Runnable  {

@Autowired
private ITesteService service;

public TesteProcessor() {
}

public void run() {
    service.save
}

What would be the best way to do this?

Thanks

Answer:

You can use @Async and do the configuration via Bean , so you can use dependency injection without any problems.

Would be like this:

@Configuration
@EnableAsync
public class SpringAsyncConfig {

    @Bean(name = "threadPoolTaskExecutor")
    public Executor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(5);
        executor.setQueueCapacity(50);
        executor.setThreadNamePrefix("MyExecutor-");
        executor.initialize();
        return executor;
    }
}

And to use:

 @Service
 public class ClassePrincipalService {

     @Autowired
     private TesteProcessorService testeProcessorService ;

     public void save() {
         // cada chamada aqui será assyncrona, abrindo uma nova thread
         testeProcessorService.run();
     }
 }

And now, with dependency injection:

 @Service
 public class TesteProcessorService {

      @Autowired
      private ITesteService service;

      @Async("threadPoolTaskExecutor")
      public void run() { service.save(); }
 }
Scroll to Top