【Redis】a bean of type ‘org.springframework.data.redis.core.RedisTemplate‘ that could not be found

Field redisTemplate in com.lzp.controller.test.RedisController required a bean of type 'org.springframework.data.redis.core.RedisTemplate' that could not be found.

The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'org.springframework.data.redis.core.RedisTemplate' in your configuration.

Error code

@ApiIgnore
@RestController
@RequestMapping("redis")
public class RedisController {
    
    

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/get")
    public Object get(String key) {
    
    
        return redisTemplate.opsForValue().get(key);
    }
}

Solution: Delete the RedisTemplate generic designation.

No qualifying bean of type ‘org.springframework.data.redis.core.RedisTemplate< java.lang.String, java.lang.Object>。

Official website, there are notes in the section Connecting to Redis

If you add your own @Bean of any of the auto-configured types, it replaces the default (except in the case of RedisTemplate, when the exclusion is based on the bean name, redisTemplate, not its type). 

The above RedisTemplate<String, Object> uses @Autowired when injecting, and @Autowired is assembled by type by default. In other words, if you want to get the Bean of RedisTemplate<String, Object>, you need to assemble it according to the name. Then naturally think of using @Resource, which is assembled by name by default. Therefore, modify the following code to start the application normally.

@Resource
private RedisTemplate<String, Object> redisTemplate;

Secondly, the parent class of StringRedisTemplate is RedisTemplate<String, String>, and Bean is singleton by default, and the two are naturally the same object. Therefore, the following injection method can also be used.

@Autowired
private RedisTemplate<String, String> redisTemplate;

Reference link: https://blog.csdn.net/zhaoheng314/article/details/81564166

Guess you like

Origin blog.csdn.net/LIZHONGPING00/article/details/115314418