java - 在服务类中获取 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()
}
}
解决方案
您可以使用 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()
}
}
推荐阅读
- javascript - 获取类型错误“无法读取 HTMLButtonElement.generateQuiz 中未定义的属性 '0'
- snowflake-cloud-data-platform - 带有嵌入双引号的雪花复制
- c# - 如何在 where 子句上基于 SqlCommand 或 SqlDataAdapter 填充 datagridview?SqlDataAdapter 不适用于哪里?
- arrays - 计算 C 中一致字符串的数量
- ssis - 在 SSIS Execute SQL Task 中传递上个月的第一天和最后一天
- javascript - 在 WordPress 中使用 Twig 实现 AJAX 帖子过滤器
- git - 如何接受 git push?git 适合在 github 上发送完整的项目吗?我应该使用其他方法,哪个?嘘?
- javascript - 如何使用 Puppeteer 选择 RSS Feed 项元素?
- python-3.x - 如何在 Python 3 中运行可执行文件,同时将两个输入传递给提示符并将输出重定向到文本文件
- c++ - 在联合本身初始化后如何初始化联合成员?