Spring - dependency injection into Thread

3

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 run its own service.

When I do service dependency injection for my main class and step into the thread constructor, everything works the way I want.

However, I do not like the way it is implemented and I believe there is a more beautiful way of doing this, ie the thread itself injects the service it 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 make the dependency injection direct in 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?

Thank you

    
asked by anonymous 15.08.2018 / 19:46

1 answer

0

You can use @Async and make the configuration via Bean , so you can use dependency injection with no problems.

It 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 dependency injection:

 @Service
 public class TesteProcessorService {

      @Autowired
      private ITesteService service;

      @Async("threadPoolTaskExecutor")
      public void run() { service.save(); }
 }
    
12.09.2018 / 13:46