SpringBoot项目中,添加了redis依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.0.6.RELEASE</version>
</dependency>
配置:
@Configuration public class BeanConfig { @Autowired private RedisTemplate<String, Object> redisTemplate ; @Bean @ConditionalOnMissingBean public RedisUtil redisUtil() { RedisUtil redisUtil = new RedisUtil() ; redisUtil.setRedisTemplate(redisTemplate); return redisUtil ; } }
在启动的时候报错:
redisTemplate in com.meihaocloud.scblog.blog.common.config.BeanConfig required a bean of type 'org.springframework.data.redis.core.RedisTemplate' that could not be found.
1、注入时不指定K、V的类型
/**
* 注入时不指定K、V的类型
*/
@Autowired
private RedisTemplate redisTemplate;
RedisTemplate在SpringBoot框架中是自动配置的,容器中默认的就是RedisTemplate的实例。
2、使用@Resource
@Resource
private RedisTemplate<String, Object> redisTemplate ;
查看官方文档地址:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/
针对RedisTemplate做了说明.
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).
如果您添加自己的@Bean(属于任何自动配置的类型),它将替换默认值(在RedisTemplate的情况下除外,当排除基于Bean名称RedisTemplate而不是其类型时)。
RedisTemplate< String, Object>注入时用到了@Autowired,@Autowired默认按照类型装配的。也就是说,想要获取RedisTemplate< String, Object>的Bean,要根据名字装配。那么自然想到使用@Resource,它默认按照名字装配