解決Autowired required a single bean, but 2 were found問題

今天使用RedisTemplate,代碼如下:

@Controller
public class TemplateController {
	private Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	RedisTemplate template;
執行後出現下面的錯誤

***************************
APPLICATION FAILED TO START
***************************

Description:

Field template in com.jzd1997.studyredis.TemplateController required a single bean, but 2 were found:
	- redisTemplate: defined by method 'redisTemplate' in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration$RedisConfiguration.class]
	- stringRedisTemplate: defined by method 'stringRedisTemplate' in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration$RedisConfiguration.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
百度以後發現了原因:

在使用Spring框架中@Autowired標籤時默認情況下使用 @Autowired 註釋進行自動注入時,Spring 容器中匹配的候選 Bean 數目必須有且僅有一個。當找不到一個匹配的 Bean 時,Spring 容器將拋BeanCreationException 異常,並指出必須至少擁有一個匹配的 Bean。

解決方案在錯誤提示裏面也提到了,我採用@Qualifier解決。

@Qualifier("XXX") 中的 XX是 Bean 的名稱,所以 @Autowired 和 @Qualifier 結合使用時,自動注入的策略就從 byType 轉變成 byName 了。
@Autowired 可以對成員變量、方法以及構造函數進行註釋,而 @Qualifier 的標註對象是成員變量、方法入參、構造函數入參。
示例
配合autowired使用:
@Autowired
@Qualifier("userService")
public IUserService userService;


發佈了64 篇原創文章 · 獲贊 16 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章