使用spring-data-redis报错
测试代码
@Test
public void SpringRedisDemoTest() {
RedisTemplate<String, Object> template =
ctx.getBean("redisTemplate", RedisTemplate.class);
template.opsForValue().set("demo", "Hello World!");
String str = (String) template.opsForValue().get("demo");
System.out.println(str);
}
报错详情
[main] WARN org.springframework.context.support.ClassPathXmlApplicationContext - Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jedisConnFactory' defined in class path resource [spring-redis.xml]:
Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.
connection.jedis.JedisConnectionFactory]: No default constructor found; nested exception is java.lang.NoClassDefFoundError: redis/clients/jedis/util/Pool
用到的依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
xml
配置文件
<bean id="jedisConnFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="usePool" value="true"/>
<property name="hostName" value="127.0.0.1"/>
<property name="password" value="123456"/>
</bean>
<bean id="redisTemplate"
class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnFactory"/>
</bean>
一开始以为是xml文件配置出错,仔细查找后并没有发现错误,经过网络查找原因,最终发现是spring-data-redis
和jedis
版本不兼容。
修改spring-data-redis
和jedis
版本
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.0.7.RELEASE</version>
</dependency>
测试结果
[main] INFO org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6833ce2c: startup date [Thu Sep 22 09:47:08 CST 2022]; root of context hierarchy
[main] INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [spring-redis.xml]
Hello World!
[main] INFO org.springframework.context.support.ClassPathXmlApplicationContext - Closing org.springframework.context.support.ClassPathXmlApplicationContext@6833ce2c: startup date [Thu Sep 22 09:47:08 CST 2022]; root of context hierarchy
可以看到现在测试程序执行成功