Why is redis throwing NullPointerException running via JUnit with spring and default config?
java, redis, spring
Solution
The problem is that both the redisTemplate and the jedisConnectionFactory need to have afterPropertiesSet() called. Usually this is called by Spring configuration, but since that wasn't working for me, it has to be called explicitly.
Also, theses lines
factory.setHostName("localhost")
factory.setPort(6379)
factory.setUsePool(true)
are unnecessary because they are the default values.
Problem
I'm working on OS X with Java 7, Spring 3.2, jedis 2.1.0, spring-data-redis 1.1.1, trying to get the most bare-bones redis set up working with the default redis configuration. Meaning I haven't put anything into the redis.conf file. When I do ``` redis-server ``` it says it started and is ready to accept connections on port 6379. Initially, I tried this with Annotated Beans for the RedisTemplate and JedisConnectionFactory, but spring complained it couldn't create or find those beans, so I did it this way. Maybe that was indicating a more basic problem. So I did it with the slightly longer version below, but this at least appears to create the Redis and Jedis components. Here is my test : ``` @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader=AnnotationConfigContextLoader.class) public class RedisTest { @Configuration static class ContextConfiguration { } RedisTemplate<String, String> template; private JedisConnectionFactory getJedisConnectionFactory() { JedisConnectionFactory factory = new JedisConnectionFactory(); factory.setHostName("localhost"); factory.setPort(6379); factory.setUsePool(true); return factory; } private RedisTemplate<String, String> getRedisTemplate() { RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>(); redisTemplate.setConnectionFactory(getJedisConnectionFactory()); return redisTemplate; } @Test public void testRedis() { System.out.println("testing redis "); template = getRedisTemplate(); template.opsForValue().set("Key", "Value"); String value = template.opsForValue().get("Key"); System.out.println("got value : " + value); } } ``` and the top of the error stack trace is ``` java.lang.NullPointerException java.lang.NullPointerException at org.springframework.data.redis.core.AbstractOperations.rawValue(AbstractOperations.java:110) at org.springframework.data.redis.core.DefaultValueOperations.set(DefaultValueOperations.java:166) at com.mycompany.storage.RedisTest.testRedis(RedisTest.java:46) ```