首先 springboot整合 RedisTemplate时,导入快速启动依赖,配置文件中配置redis的连接信息
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.database= 0
spring.redis.timeout=1800000
然后在需要使用 redisTemplate的spring组件中使用@Autowired完成自动装配
但是 在spring装配 redisTemplate 的时候,可能会报错 如下
Description:
Field redisTemplate in com.sgg.yygh.msm.controller.MSMController 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)
The following candidates were found but could not be injected:
- Bean method 'redisTemplate' in 'RedisAutoConfiguration' not loaded because @ConditionalOnBean (names: redisTemplate; SearchStrategy: all) found beans named redisTemplate
Action:
Consider revisiting the entries above or defining a bean of type 'org.springframework.data.redis.core.RedisTemplate' in your configuration.
Disconnected from the target VM, address: '127.0.0.1:54567', transport: 'socket'
注意 重点来了
在springboot整合RedisTemplate时 如果使用 @Autowired 注解完成自动装配 那么
- RedisTemplate要么不指定泛型
- 要么泛型 为<Stirng,String> 或者<Object,Object>
如果你非得使用其他类型的 比如 RedisTemplate<String,Object> 那么请使用 @Resource 注解
@Autowired 按类型装配 byType
@Resource 按bean名字装配 byName