在Spring中重构这个的最佳方法是什么?

时间:2011-12-07 14:10:08

标签: java spring

private final ExecutorService executorParsers = Executors.newFixedThreadPool(10);

public void parse(List<MyObjInt> objs) {
   //... bunch of elided stuff ....

   CompletionService<AsupParseObj> parserService = new ExecutorCompletionService<AsupParseObj>(executorParsers);

   for (final AsupStoreObj obj : objs) {
      parserService.submit(new ParseThread(obj));
   }
}

我想DI“ParseThread”但肯定有一个更好的方法来做到这一点,而不是在原型范围内的bean上调用getBean,因为我是Spring的新手,我想我会问......

2 个答案:

答案 0 :(得分:7)

以下是使用lookup-method的完整配置(请参阅3.4.6.1 Lookup method injection):

<bean id="executorParsers" class="java.util.concurrent.Executors" 
        factory-method="newFixedThreadPool" 
        destroy-method="shutdownNow">
    <constructor-arg value="10"/>
</bean>

<bean id="parserService" class="java.util.concurrent.CompletionService">
    <constructor-arg ref="executorParsers"/>
</bean>

<bean id="foo" class="Foo">
    <lookup-method name="createThread" bean="parseThread"/>
</bean>

<bean id="parseThread" class="ParseThread" scope="prototype" lazy-init="true"/>

Java代码:

abstract class Foo {

    @Autowired
    CompletionService parserService;

    protected abstract ParseThread createThread();

    public void parse(List<MyObjInt> objs) {
        for (final AsupStoreObj obj : objs) {
            ParseThread t = createThread();
            t.setObject(obj);
            parserService.submit(t);
        }
    }
}

很遗憾,您无法将任何参数传递给lookup-method(请参阅SPR-7431和我的文章Creating prototype Spring beans on demand using lookup-method),因此需要人工setObject()

如果您不喜欢abstract个方法/类,则查找方法可以是非抽象的无操作方法,或者(更好)默认实现可以抛出异常。 Spring将在运行时覆盖实现,有效地为您调用getBean()

奖励:我也将Executor / CompletionService翻译成了Spring托管bean。请注意,Spring支持这些开箱即用的:Task Execution and Scheduling

答案 1 :(得分:0)

好吧,我不确定你认为Spring会在这里给你买什么,但是我会注入一些吐出Runnable / Callable的工厂。

private final ExecutorService executorParsers = Executors.newFixedThreadPool(10);

@Autowired
private CallableFactory myCallableFactory = new MyCallableFactory(); //create this factory

public void parse(List<MyObjInt> objs) {
   //... bunch of elided stuff ....

   CompletionService<AsupParseObj> parserService = new ExecutorCompletionService<AsupParseObj>(executorParsers);

   for (final AsupStoreObj obj : objs) {
      parserService.submit(myCallableFactory.createCallable(obj));
   }
}

您也可以使用Spring注入ExecutorService