问题背景

最近使用Springboot引入redis,直接在Service里使用@Autowired 注入RedisTemplate,但是启动时发现注入的@RedisTemplate为null

@Service
public class CacheRedisImpl implements Cache {

    @Autowired(required = false)
    private RedisTemplate<String,Object> redisTemplate;
	....    
}
  • 上述代码运行启动之后断点,如下图,无论如何都是null
    这里无论如何都就是null
    最后去查阅spring的源码 RedisAutoConfiguration(在org.springframework.boot.autoconfigure.data.redis包)
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {

	@Bean
	@ConditionalOnMissingBean(name = "redisTemplate")
	public RedisTemplate<Object, Object> redisTemplate(
			RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
		RedisTemplate<Object, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);
		return template;
		}
		...

终于发现问题了,spring注入的是RedisTemplate<Object, Object>
而我注入的泛型是RedisTemplate<String,Object>。

解决:

通过上述排查分析,解决方案有如下

  1. @Autowired 时使用RedisTemplate<Object, Object> 或RedisTemplate
@Service
public class CacheRedisImpl implements Cache {
    @Autowired(required = false)
    private RedisTemplate redisTemplate;
    

运行效果如下图:
在这里插入图片描述

  1. 如一定要使用RedisTemplate<String,Object>,写一个Configuration自行手动注入@Bean
@Configuration
public class RedisAutoConfig {
    @Bean(name = "redisTemplate4String")
    public RedisTemplate<String,Object> redisTemplate4String(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        return  redisTemplate;
    }
}

效果如下:
在这里插入图片描述
PS: 其实细心的童鞋可能会发现我的代码里@Autowired配置是(required = false)。如果去掉的话,springboot 启动里会直接报错找不到bean。解决方案与本文类似。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐