如何使用XML在Spring中创建执行程序服务bean

时间:2018-11-27 02:44:17

标签: java xml spring

我必须在以XML编写的Spring配置文件中创建ScheduledThreadPoolExecutor的bean。在Java中,我将其写为

@Bean(name = "MyThreadPoolList")
    public List<ScheduledThreadPoolExecutor> executorList() {
        List<ScheduledThreadPoolExecutor> executor = new ArrayList<>();
        ScheduledThreadPoolExecutor tempExecutor;
        for (int i = 0; i< 3; i++ ){
            tempExecutor = new ScheduledThreadPoolExecutor(
                    1,
                    NamingThreadFactory.createWithDaemon("ExecutorPool-"+i+"-Thread-%d", true));
            tempExecutor.prestartAllCoreThreads();
            executor.add(i, tempExecutor);
        }
        return Collections.unmodifiableList(executor);
    }

但是我不知道用XML实现此目标的最佳方法是什么。我可以尝试以下操作:

<bean id="MyThreadPoolList" class="java.util.ArrayList">
    <constructor-arg>
        <list>
            <bean class="java.util.concurrent.ScheduledThreadPoolExecutor" init-method="prestartAllCoreThreads">
                 <constructor-arg value="1"/>
                 <constructor-arg>
                     <bean class="my.factory.NamingThreadFactory" factory-method="createWithDaemon">
                           <constructor-arg value="ExecutorPool-0-Thread-%d"/>
                           <constructor-arg type="boolean" value="true"/>
                     </bean>
                </constructor-arg>
            </bean>
            <bean class="java.util.concurrent.ScheduledThreadPoolExecutor" init-method="prestartAllCoreThreads">
                 <constructor-arg value="1"/>
                 <constructor-arg>
                     <bean class="my.factory.NamingThreadFactory" factory-method="createWithDaemon">
                           <constructor-arg value="ExecutorPool-1-Thread-%d"/>
                           <constructor-arg type="boolean" value="true"/>
                     </bean>
                </constructor-arg>
            </bean>
            <bean class="java.util.concurrent.ScheduledThreadPoolExecutor" init-method="prestartAllCoreThreads">
                 <constructor-arg value="1"/>
                 <constructor-arg>
                     <bean class="my.factory.NamingThreadFactory" factory-method="createWithDaemon">
                           <constructor-arg value="ExecutorPool-2-Thread-%d"/>
                           <constructor-arg type="boolean" value="true"/>
                     </bean>
                </constructor-arg>
            </bean>
        </list>
    </constructor-arg>
</bean>

但是问题是:

  1. 重复的代码太多了
  2. 如果将来我想将执行程序服务的数量增加到500个,我将不得不复制500次。

有没有更优雅的方法来实现这一目标?

0 个答案:

没有答案