首页 > 解决方案 > 在服务类中获取 Spring ThreadPoolExecutor

问题描述

我在应用程序上下文中创建了一个 bean 线程池执行器。我想使用该线程池执行程序并在另一个类中运行一些代码,该类注释为@Service。

我的应用类

public class TestApplication extends WebMvcConfigurerAdapter {

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {"classpath:/resources/", "classpath:/static/"};

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

    @Bean
    public Executor testAsync() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(10);
        executor.setThreadNamePrefix("TestExecutor-");
        executor.initialize();
        return executor;
    }
}

下面的类是我需要让该线程执行的地方

@Service
public class TastService{
      public void runMyCode(){
         //Here I need to start that thread and then call executor.submit()
      }
}

标签: javaspringthreadpool

解决方案


您可以使用 Autowire 注释注入它。请注意,如果您@Bean在 java config 中使用注解,则 bean 名称将与注解的方法名称相同,除非您使用@Bean注解的 name 属性

    @Service
    public class TastService{

         private final Executor testAsync;

         @Autowire
         public TastService(Executor testAsync) {
             this.testAsync = testAsync;
         }

         public void runMyCode(){
            testAsync.submit()
         }
   }

推荐阅读