在一次配置多线程bean的过程中报了如下错误:
Field xxx required a single bean, but 2 were found:
- async-task-pool: defined by method ‘asyncTaskPool’ in class path resource
- async-task-executor: defined by method ‘asyncTaskExecutor’ in class path resource
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
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
/**
* 线程池配置
*/
@Slf4j
@Configuration
public class ExecutorConfig {
/**
* 任务执行器BeanName
*/
public static final String TASK_EXECUTOR = "task-executor";
/**
* 任务执行器BeanName
*/
public static final String TASK_POOL = "task-pool";
/**
* 配置任务执行器
*/
@Bean(TASK_POOL)
public ThreadPoolTaskExecutor asyncTaskPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(20);
executor.setMaxPoolSize(30);
executor.setQueueCapacity(1000);
executor.setKeepAliveSeconds(60);
executor.setRejectedExecutionHandler((r, currentExecutor) -> {
log.error("任务执行器队列已占满,请及时处理...");
});
initDefaultThread(executor, TASK_POOL);
executor.initialize();
return executor;
}
/**
* 配置任务执行器
*/
@Bean(TASK_EXECUTOR)
public Executor asyncTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(1000);
executor.setKeepAliveSeconds(60);
executor.setRejectedExecutionHandler((r, currentExecutor) -> log.error("任务执行器队列已占满,请及时处理..."));
initDefaultThread(executor, TASK_EXECUTOR);
executor.initialize();
return executor;
}
private void initDefaultThread(ThreadPoolTaskExecutor executor, String taskExecutorName) {
executor.setThreadFactory(r -> {
Thread thread = new Thread(r);
thread.setName(taskExecutorName + "-" + thread.getId());
thread.setUncaughtExceptionHandler((t, e) -> log.error("线程异常,线程名:{}", t.getName()));
return thread;
});
}
}
先看下报错的源码
@Override
protected FailureAnalysis analyze(Throwable rootFailure,
NoUniqueBeanDefinitionException cause, String description) {
if (description == null) {
return null;
}
String[] beanNames = extractBeanNames(cause);
if (beanNames == null) {
return null;
}
StringBuilder message = new StringBuilder();
message.append(String.format("%s required a single bean, but %d were found:%n",
description, beanNames.length));
for (String beanName : beanNames) {
buildMessage(message, beanName);
}
return new FailureAnalysis(message.toString(),
"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",
cause);
}
异常为Bean定义非唯一异常,为啥报错呢?
我们注入Bean通常会用@Resource和 @Autowired:
@Autowired 按 byType 自动注入,
@Resource默认按 byName 自动注入。
@Autowired是通过byType形式,Spring容器将无法确定到底要用哪一个 Bean,因此异常发生了。
解决方案报错提示中给出了:
使用@Primary注解在其中一个bean上,或者消费的时候@Qualifier指定
/**
* 配置任务执行器
*/
@Bean(TASK_EXECUTOR)
@Primary
public Executor asyncTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(1000);
executor.setKeepAliveSeconds(60);
executor.setRejectedExecutionHandler((r, currentExecutor) -> log.error("任务执行器队列已占满,请及时处理..."));
initDefaultThread(executor, TASK_EXECUTOR);
executor.initialize();
return executor;
}
再次重启完美解决。
附上Primary源码:
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates that a bean should be given preference when multiple candidates
* are qualified to autowire a single-valued dependency. If exactly one
* 'primary' bean exists among the candidates, it will be the autowired value.
*
* This annotation is semantically equivalent to the {@code } element's
* {@code primary} attribute in Spring XML.
*
* May be used on any class directly or indirectly annotated with
* {@code @Component} or on methods annotated with @{@link Bean}.
*
*
Example
*
* @Component
* public class FooService {
*
* private FooRepository fooRepository;
*
* @Autowired
* public FooService(FooRepository fooRepository) {
* this.fooRepository = fooRepository;
* }
* }
*
* @Component
* public class JdbcFooRepository {
*
* public JdbcFooService(DataSource dataSource) {
* // ...
* }
* }
*
* @Primary
* @Component
* public class HibernateFooRepository {
*
* public HibernateFooService(SessionFactory sessionFactory) {
* // ...
* }
* }
*
*
* Because {@code HibernateFooRepository} is marked with {@code @Primary},
* it will be injected preferentially over the jdbc-based variant assuming both
* are present as beans within the same Spring application context, which is
* often the case when component-scanning is applied liberally.
*
*
Note that using {@code @Primary} at the class level has no effect unless
* component-scanning is being used. If a {@code @Primary}-annotated class is
* declared via XML, {@code @Primary} annotation metadata is ignored, and
* {@code } is respected instead.
*
* @author Chris Beams
* @since 3.0
* @see Lazy
* @see Bean
* @see ComponentScan
* @see org.springframework.stereotype.Component
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Primary {
}