解决Autowired required a single bean, but 2 were found问题

柔情只为你懂 2022-05-31 00:23 374阅读 0赞

今天使用RedisTemplate,代码如下:

  1. @Controller
  2. public class TemplateController {
  3. private Logger log = LoggerFactory.getLogger(this.getClass());
  4. @Autowired
  5. RedisTemplate template;

执行后出现下面的错误

  1. ***************************
  2. APPLICATION FAILED TO START
  3. ***************************
  4. Description:
  5. Field template in com.jzd1997.studyredis.TemplateController required a single bean, but 2 were found:
  6. - redisTemplate: defined by method 'redisTemplate' in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration$RedisConfiguration.class]
  7. - stringRedisTemplate: defined by method 'stringRedisTemplate' in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration$RedisConfiguration.class]
  8. Action:
  9. 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解决。

  1. @Qualifier("XXX") 中的 XX Bean 的名称,所以 @Autowired @Qualifier 结合使用时,自动注入的策略就从 byType 转变成 byName 了。
  2. @Autowired 可以对成员变量、方法以及构造函数进行注释,而 @Qualifier 的标注对象是成员变量、方法入参、构造函数入参。
  3. 示例
  4. 配合autowired使用:
  5. @Autowired
  6. @Qualifier("userService")
  7. public IUserService userService;

发表评论

表情:
评论列表 (有 0 条评论,374人围观)

还没有评论,来说两句吧...

相关阅读