解决spring 注入ThreadPoolExecutor 构造歧义

本文详细介绍了如何使用FactoryBean解决在Spring框架中直接注入ThreadPoolExecutor导致的错误,通过实例展示了如何正确配置和使用FactoryBean来创建并注入线程池。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

出处http://stackoverflow.com/questions/6395388/error-creating-bean-cant-inject-a-new-linkedblockingqueue-as-a-constructor-to

这里的解决方法就是不直接注入 ThreadPoolExecutor,而是通过factoryBean注入

public class ThreadPoolExecutorFactory implements FactoryBean 
{
    private final ReentrantLock lock = new ReentrantLock();   
    private ThreadPoolExecutor executor;
    private int corePoolSize;
    private int maximumPoolSize;
    private long keepAliveTime;
    private TimeUnit unit;

    public Object getObject() 
    {
        lock.lock();
        if (executor == null)
            executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
                    keepAliveTime, unit, new LinkedBlockingQueue<Runnable>());
        lock.unlock();
        return executor;
    }

    public Class getObjectType() 
    {
        return ThreadPoolExecutor.class;
    }

    public boolean isSingleton()    
    {
        return true;
    }
}



<bean name="executor" class="ThreadPoolExecutorFactory">
    <constructor-arg value="1" /> 
    <constructor-arg value="20" /> 
    <constructor-arg value="60" />
    <constructor-arg>
        <bean class="java.util.concurrent.TimeUnit" factory-method="valueOf">
            <constructor-arg value="SECONDS" />
        </bean>
    </constructor-arg>
</bean>


在程序中可以注入给ThreadPoolExecutor

@Autowired
@Qualifier(value = "executor")
ThreadPoolExecutor executor;

idea启动springboot项目报错;org.springframework.beans.factory.BeanCreationException. Message: Error creating bean with name 'servletEndpointRegistrar' defined in class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration$WebMvcServletEndpointManagementContextConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]: Factory method 'servletEndpointRegistrar' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.cloud.client.serviceregistry.ServiceRegistryAutoConfiguration$ServiceRegistryEndpointConfiguration': Unsatisfied dependency expressed through field 'registration'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.cloud.client.serviceregistry.Registration' available: expected single matching bean but found 2: eurekaRegistration,consulRegistration 2025-05-27 13:58:16.934 default [main] INFO o.a.catalina.core.StandardService - Stopping service [Tomcat] 2025-05-27 13:58:17.012 default [main] WARN o.a.c.loader.WebappClassLoaderBase - The web applica[tion [api] appears to have started a thread named spring.cloud.inetutils] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread: sun.misc.Unsafe.park(Native Method) java.util.concurrent.locks.LockSupport.park(LockSupport.java:175) java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039) java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442) java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1074) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) java.lang.Thread.run(Thread.java:748) 2025-05-27 13:58:17.017 default [main] WARN o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat 2025-05-27 13:58:17.449 default [main] INFO o.s.b.a.l.ConditionEvaluationReportLoggingListener - Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2025-05-27 13:58:17.460 default [main] ERROR o.s.b.d.LoggingFailureAnalysisReporter - *************************** APPLICATION FAILED TO START *************************** Description: Field registration in org.springframework.cloud.client.serviceregistry.ServiceRegistryAutoConfiguration$ServiceRegis2025-05-27 13:58:17.012 default [main] WARN o.a.c.loader.WebappClassLoaderBase - The web applica[tion [api] appears to have started a thread named spring.cloud.inetutils] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread: sun.misc.Unsafe.park(Native Method) java.util.concurrent.locks.LockSupport.park(LockSupport.java:175) java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039) java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442) java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1074) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) java.lang.Thread.run(Thread.java:748) 2025-05-27 13:58:17.017 default [main] WARN o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat 2025-05-27 13:58:17.449 default [main] INFO o.s.b.a.l.ConditionEvaluationReportLoggingListener - Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2025-05-27 13:58:17.460 default [main] ERROR o.s.b.d.LoggingFailureAnalysisReporter - tryEndpointConfiguration required a single bean, but 2 were found: - eurekaRegistration: defined in BeanDefinition defined in class path resource [org/springframework/cloud/netflix/eureka/EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration.class] - consulRegistration: defined by method 'consulRegistration' in class path resource [org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationAutoConfiguration.class] Action: Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed 25-05-27@13:58:17 INFO - [DUBBO] Run shutdown hook now., dubbo version: 2.0.0.SR1, current host: 127.0.0.1 25-05-27@13:58:17 INFO - [DUBBO] Close all registries [], dubbo version: 2.0.0.SR1, current host: 127.0.0.1 Process finished with exit code 1
最新发布
05-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值