【问题标题】:Getting Spring ThreadPoolExecutor in a Service class在服务类中获取 Spring ThreadPoolExecutor
【发布时间】:2019-11-07 00:28:26
【问题描述】:

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

【问题讨论】:

  • 不要...只需将@Async 放在方法上即可。为什么你需要自己提交薄?如果您真的需要它,只需自动连接 TaskExecutor 并使用它。
  • 当我使用@Autowire 注释应用程序失败并出现无法绑定的错误。我不能使用@Async,因为我想要当前线程上的一些上下文数据到新的起始线程。这就是为什么我试图通过 Spring Boot 获取线程
  • @Bean 方法的返回类型更改为ThreadPoolTaskExecutor,然后注入TaskExecutor(不是完整类型,只是接口!)。

标签: java spring threadpool


【解决方案1】:

您可以使用 Autowire 注释注入它。请注意,如果您在 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()
         }
   }

【讨论】:

  • 名称与它无关(它是一个后备).. 类型。
  • 是的。你说的对。但据我所知,如果您有多个同一类型的 bean,名称也可能很重要。
【解决方案2】:

您可以从服务文件中的ApplicationContext 获取testAsync bean。

在服务类中,

import org.springframework.context.ApplicationContext;

@Service
public class TastService{

    @Autowired
    private ApplicationContext applicationContext;

    public void runMyCode(){
        //Here I need to start that thread and then call executor.submit()
        Executor executor = (Executor) applicationContext
                .getBean("testAsync");
    }
}

但您还需要注意,testAsync 方法在应用程序启动期间首先加载,然后再加载 TastService。否则它会失败。这可以通过添加@DependsOn(link) 来实现

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多