我有以下配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<context:component-scan base-package="com.abc" />
<task:annotation-driven executor="executor"/>
<task:executor id="executor" pool-size="2"/>
</beans>
然后下面的课
public class SomeClassImpl implements SomeClass {
@Async
@Override // overridden from the interface
public void doSomething(){
System.out.println("doing something async");
}
}
一个测试:
@ContextConfiguration("classpath:test-config.xml") // with the xml config above
@RunWith(value = SpringJUnit4ClassRunner.class)
public class SomeClassTest {
@Autowired
private SomeClass someClass;
@Test
public void testSomething() throws Exception {
System.out.println("Calling doSomething");
someClass.doSomething();
Thread.sleep(5000);
}
}
当我运行测试时,一切都按预期工作。但是后来我附加了调试器以逐步了解调用 someClass.doSomething() 时实际发生的情况,我注意到以下内容:
为什么 SimpleAsyncTaskExecutor 创建了 4 个线程?我知道如果我从 task:annotation-driven xml 元素中删除 executor 属性,AsyncExecutionInterceptor 将使用 SimpleAsyncTaskExecutor。但是既然我已经声明了一个任务执行器并从注释驱动的元素中引用了它,为什么要创建一个 SimpleAsyncTaskExecutor 呢?