SpringMVC中@RedisTemplate的装配的问题

RedisTemplate的装配的问题

把项目中遇见的问题记下来,做个笔记,比敲一阵子代码要更有成就!

一、背景

初入Springmvc,使用redis,不像django给你封装的挺好。就踩了一些坑,什么版本不对的问题,什么通过注解方式无法创建redis的bean对象(装载到容器失败),子容器父容器扫描冲突等等。

这次遇到的是常见bean对象失败的错误。


解决方案

不要使用@Autowired按类型注解自动装配RedisTemplate对象,而使用@Resource按名字进行装配对象。!!!

不要使用@Autowired按类型注解自动装配RedisTemplate对象,而使用@Resource按名字进行装配对象。!!!

不要使用@Autowired按类型注解自动装配RedisTemplate对象,而使用@Resource按名字进行装配对象。!!!

重要的事情说三遍

官网原话: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).

告诉我们RedisTemplate要依赖名称注入,而不是对象注入!

但是我使用了@Resource注解后,仍然出错。经过一番差错,最终找到了原因,就是Spring父容器,和Springmvc子容器的冲突,最好让springmvc只扫描controller层,而Spring可以扫描service,dao,util等其他层。

假如spring父容器扫了全部的层,那么此时springmvc想扫描controller层,就扫描不到该层,从而创建不了该对象。所以一定要注意配置好容器所扫描的层。