我正在尝试创建一个java.util.concurrent.ThreadPoolExecutor
的bean,下面是我在spring配置文件中的内容:
<bean id="threadPoolExector" class="java.util.concurrent.ThreadPoolExecutor" lazy-init="true" scope="singleton">
<property name="corePoolSize" value="${corePoolSize}"/>
<property name="maximumPoolSize" value="${maximumPoolSize}"/>
<property name="keepAliveTime" value="${keepAliveTime}"/>
<property name="unit" value="java.util.concurrent.TimeUnit.SECONDS"/>
<property name="workQueue" ref="abcBlockingQueueImpl"></property>
</bean>
<bean id="abcBlockingQueueImpl" class="my.package.AbcBlockingQueueImpl" lazy-init="true" scope="singleton"/>
然后我尝试创建如下:
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) applicationContext.getBean("threadPoolExector");
但是我得到了以下异常,我知道ThreadPoolExecutor
没有no-arg,但我很惊讶我得到了这个例外。
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'threadPoolExector' defined in ServletContext resource [/WEB-INF/context/web-applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [java.util.concurrent.ThreadPoolExecutor]: No default constructor found; nested exception is java.lang.NoSuchMethodException: java.util.concurrent.ThreadPoolExecutor.<init>()
之前我使用过Spring bean,但这看起来像一个奇怪的问题。
答案 0 :(得分:1)
问题出在最后:
... No default constructor found; ...
ThreadPoolExecutor没有默认构造函数,您必须模拟代码中描述的内容:使用<constructor-arg>
标记而不是<property>
标记为至少最小构造函数设置构造函数参数:
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
在上下文XML文件中:
<bean id="threadPoolExector" class="java.util.concurrent.ThreadPoolExecutor" lazy-init="true" scope="singleton">
<constructor-arg index="0" type="int" value="${corePoolSize}"/>
<constructor-arg index="1" type="int" value="${maximumPoolSize}"/>
<constructor-arg index="2" type="long" value="${keepAliveTime}"/>
<constructor-arg index="3" type="java.util.concurrent.TimeUnit" value="java.util.concurrent.TimeUnit.SECONDS"/>
<constructor-arg index="4" ref="abcBlockingQueueImpl"/>
</bean>