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