1个回答

test
2024-06-20
先说结论:因为Spring帮你调用了这个方法
首先我们把这玩意单独拿出来用
public class SomeTest {
public static void main(String[] args) {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.submit(() -> System.out.println("!"));
}
}
这里就会报错,ThreadPoolTaskExecutor not initialized
然后我们换一个姿势,就没有问题了
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Demo21Application.class, args);
ThreadPoolTaskExecutor myExecutor = context.getBean("myExecutor", ThreadPoolTaskExecutor.class);
myExecutor.submit(() -> System.out.println("hello!"));
}
@Bean
public ThreadPoolTaskExecutor myExecutor() {
return new ThreadPoolTaskExecutor();
}
}
那么spring是怎么调用到这个方法呢,让我们打开 ExecutorConfigurationSupport
@Override
public void afterPropertiesSet() {
initialize();
}
然后这个方法是在 InitializingBean
里定义的,熟悉 Spring Bean 生命周期的朋友们应该已经知道这是怎么回事了,简单说就是对bean的初始化完成之后进行的其他初始化工作
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容