Spring - Thread Dependency Injection

Asked

Viewed 219 times

3

I need a little help.

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

When I inject service dependency into my main class and step into the thread constructor, everything works the way I want it to.

However, I do not like the way it is implemented and I believe that there is a more beautiful way to do this, that is, the thread itself inject the service that will use.

How are you 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 have tried to do the direct dependency injection in the service, but Nullpointer occurs when using 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 that?

Thank you

1 answer

0

You can use the @Async and set up via Bean, can thus use dependency injection smoothly.

Would look 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 addiction injection:

 @Service
 public class TesteProcessorService {

      @Autowired
      private ITesteService service;

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.