Could not autowire. There is more than one bean of ‘RedisTemplate‘ type原因

code show as below:

@RunWith(SpringRunner.class)
@SpringBootTest
class RedisdemoApplicationTests {
    
    
    @Autowired
    private RedisTemplate template;
    @Test
    public void a() {
    
    
        template.opsForValue().set("1","测试中文");
        System.out.println(template.opsForValue().get("1"));
    }
}

Error message

Could not autowire. There is more than one bean of 'RedisTemplate' type.
Beans:
redisTemplate   (RedisAutoConfiguration.class) stringRedisTemplate   (RedisAutoConfiguration.class) 

wrong reason

The StringRedisTemplate class is a subclass of RedisTemplate, and the parent class will be called when the subclass is injected. In fact, we can understand that the subclass is also a special parent class.
For the @Autowired annotation, it is first injected according to the type. Since there are two RedisTemplate types, it does not know which one should be injected. Then according to the name injection, because the object name is template, the type cannot be determined, so an error is reported.

solution

  • 1. Change the object name to redisTemplate and use the @Autowired annotation: @Autowired will inject according to the name when it cannot be judged based on the type.
  • 2. Change the object name to redisTemplate and use @Resource annotation: @Resource will inject according to the name.
  • 3. Without changing the object name, use @Resource(name = "redisTemplate") to specify the name injection.

Guess you like

Origin blog.csdn.net/weixin_44159662/article/details/112316333