您的位置:首页 > 产品设计 > UI/UE

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

2018-02-01 13:48 579 查看
今天使用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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: