java - 在 Service 类中获取 Spring ThreadPoolExecutor

标签 java spring threadpool

我在应用程序上下文中创建了一个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()
      }
}

最佳答案

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

    @Service
    public class TastService{

         private final Executor testAsync;

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

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

关于java - 在 Service 类中获取 Spring ThreadPoolExecutor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56749431/

相关文章:

java - 如何在 Java 中以同步方式处理异步回调?

java - 如何模拟jsp :param in SpringMVC

maven - Web应用程序中的Elasticsearch Java API错误:java.lang.NoClassDefFoundError:无法初始化类org.elasticsearch.threadpool.ThreadPool

java - Primefaces - FileUploader 不调用 ManagedBean

java - 陷入 Spring MVC 新手教程

java - 无法解析导入 javax.servlet 和 org.hibernate - Ubuntu 12.04 上的 Eclipse Kepler

java - Spring:Tomcat 响应中的 HTTP 状态 406

java - 丢失 ThreadPoolExecutor 中所有提交的任务

如果任务持续时间超过周期,Java ScheduledThreadPool 将使用额外的线程

java.lang.VerifyError : Bad type on operand stack