とてもシンプルです。アイデアは、Bean である executor オブジェクトがあり、新しいタスクを (新しいスレッドで) 起動したいオブジェクトに渡されるということです。良い点は、Spring 構成を変更するだけで、使用するタスク エグゼキューターのタイプを変更できることです。以下の例では、いくつかのサンプル クラス (ClassWithMethodToFire) を取り上げ、それを Runnable オブジェクトにラップして発火を行います。また、Runnable を独自のクラスに実際に実装し、execute メソッドで を呼び出すこともできますclassWithMethodToFire.run()
。
これは非常に簡単な例です。
public class SomethingThatShouldHappenInAThread {
private TaskExecutor taskExecutor;
private ClassWithMethodToFire classWithMethodToFire;
public SomethingThatShouldHappenInAThread(TaskExecutor taskExecutor,
ClassWithMethodToFire classWithMethodToFire) {
this.taskExecutor = taskExecutor;
this.classWithMethodToFire = classWithMethodToFire;
}
public void fire(final SomeParameterClass parameter) {
taskExecutor.execute( new Runnable() {
public void run() {
classWithMethodToFire.doSomething( parameter );
}
});
}
}
そして、ここにSpring Beanがあります:
<bean name="somethingThatShouldHappenInAThread" class="package.name.SomethingThatShouldHappenInAThread">
<constructor-arg type="org.springframework.core.task.TaskExecutor" ref="taskExecutor" />
<constructor-arg type="package.name.ClassWithMethodToFire" ref="classWithMethodToFireBean"/>
</bean>
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="5" />
<property name="maxPoolSize" value="10" />
<property name="queueCapacity" value="25" />
</bean>