在一次配置多線程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.
*
* <p>This annotation is semantically equivalent to the {@code <bean>} element's
* {@code primary} attribute in Spring XML.
*
* <p>May be used on any class directly or indirectly annotated with
* {@code @Component} or on methods annotated with @{@link Bean}.
*
* <h2>Example</h2>
* <pre class="code">
* @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) {
* // ...
* }
* }
* </pre>
*
* <p>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.
*
* <p>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 <bean primary="true|false"/>} 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 {
}