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

use*_*751 7 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));
   }
}
Run Code Online (Sandbox Code Playgroud)

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

Tom*_*icz 7

以下是使用的完整配置lookup-method(参见3.4.6.1查找方法注入):

<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"/>
Run Code Online (Sandbox Code Playgroud)

和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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是你无法传递任何参数lookup-method(参见SPR-7431和我的文章使用查找方法按需创建原型Spring bean),因此需要人工setObject().

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

额外奖励:我还翻译了Executor/ CompletionService或Spring托管bean.请注意,Spring支持这些开箱即用的功能:任务执行和调度.