很简单 这个想法是,你有一个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 );
}
});
}
}
And here are the Spring beans:
<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>