最常见报错是启动时抛出NoSuchBeanDefinitionException:No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate' available,或运行时调用redisTemplate.opsForValue().get(...)报NullPointerException。

RedisTemplate注入失败的典型报错长什么样
最常见的是启动时报 NoSuchBeanDefinitionException,比如:No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate' available;或者运行时在某个 Service、Controller、Interceptor 里调用 redisTemplate.opsForValue().get(...) 报 NullPointerException,debug 发现字段值为 null。
检查依赖和自动配置是否启用
Spring Boot 不会无条件创建 RedisTemplate,它依赖 spring-boot-starter-data-redis 的存在以及基础连接配置是否就位。
- 确认
pom.xml中有且仅有一个版本的 starter:spring-boot-starter-data-redis(注意不是spring-data-redis单独引入) -
application.yml或application.properties中至少配置了spring.redis.host和spring.redis.port;若 Redis 有密码,必须加spring.redis.password - 如果使用了自定义连接池(如 Lettuce),确保没漏掉
spring.redis.lettuce.pool.max-active等关键项,否则自动配置可能静默跳过 - 禁用自动配置会导致
RedisAutoConfiguration不生效,检查是否误加了@EnableAutoConfiguration(exclude = RedisAutoConfiguration.class)
为什么拦截器/Filter/Listener 里 redisTemplate 总是 null
因为这些组件的实例化发生在 Spring 容器完全初始化之前。即使你写了 @Autowired,此时上下文还没准备好,字段不会被注入。
Redis 缓存和数据结构管理技能。通过自然语言操作 Redis,支持 String、Hash、List、Set、ZSet、Stream 等数据结构操作。当用户提到 Redis、缓存、消息队列、会话存储时使用此技能。
- 不要在
HandlerInterceptor实现类中直接@AutowiredredisTemplate - 改用
ApplicationContext手动获取:在拦截器中注入ApplicationContext,然后调用context.getBean(RedisTemplate.class) - 更稳妥的做法是把 Redis 操作抽成独立 Service,并在
preHandle中通过ApplicationContext获取该 Service(而非直接拿RedisTemplate) - 若用
@WebMvcConfigurer注册拦截器,确保注册方式是通过registry.addInterceptor(...),而不是 new 出来硬塞进去
测试类里 redisTemplate 为空?缺了这个注解
普通 JUnit 测试(@Test)不加载 Spring 上下文,@Autowired 完全无效 —— 这是最容易忽略的点。
- 单元测试需加
@SpringBootTest(推荐搭配@AutoConfigureTestDatabase或@Testcontainers做集成验证) - 避免在测试类里写
new XxxService(),否则redisTemplate字段永远是默认值null - 如果只是想 mock 行为,用
@MockBean RedisTemplate替代@Autowired,但注意这不会触发真实连接 - 调试时可在测试方法开头加
System.out.println(redisTemplate != null);快速确认注入状态
真正难排查的不是“没配对”,而是“配了但被覆盖”——比如多个 @Configuration 类都声明了 @Bean RedisTemplate,或用了 @Primary 却没留意冲突;还有 YAML 缩进错误导致配置未被读取,这种问题不会报错,但 RedisTemplate 就是空的。

















