/**
*RedisConfig.java
**/
@Configuration //配置类
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setConnectionFactory(factory);
//key序列化方式
template.setKeySerializer(redisSerializer);
//value序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
//value hashmap序列化
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
/**
*RedisConnect.java
**/
public class RedisTest {
//这一行报错:Exception in thread "main" java.lang.NullPointerException
@Autowired
private RedisTemplate<String,Object> template;
public void test(){
User user = new User();
user.setName("你好");
user.setNo(123456);
template.opsForValue().set("redis", user);
User redis = (User) template.opsForValue().get("redis");
System.out.println(redis);
}
}
/**
*Application.java
**/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
RedisTest redisTest = new RedisTest();
redisTest.test(); //这里报错:Exception in thread "main" java.lang.NullPointerException
}
}
<!-- maven中与之关联的包 -->
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>6.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
报错信息
Exception in thread "main" java.lang.NullPointerException
at security.test.RedisTest.test(RedisConnect.java:20)
at security.Application.main(Application.java:15)
尝试过各种相关的方法,折腾了一下午,实在顶不住了。
推荐了解一下Spring的基础(IoC相关的)
使用new的方式并不能自动注入,Spring无法管理使用new构建的对象
所以正确的方法是使用Spring依赖注入你的测试对象
@SpringBootApplication
public class Application {
@Autowired
RedisTest re;
public static void main(String[] args) {
SpringApplication.run(Application.class);
re.test();
}
}
问题解决后记得标记已解决
首先,你的测试的方法是错误的。看你的RedisTest类,你是想用Springboot环境来测试你的redis连接是否好用。那么,你应该在测试模块去写代码,使用springboot的test框架。
其次,解释一下为什么,报空指针异常。你的RedisTest类中的RedisTemplate的对象使用到了@Autowired注解,该注解只在Spring容器内生效,像你这么写(直接使用构造函数)是无法生效的,RedisTemplate的对象只能是null,无论再怎么写只要调用方法就会报空指针异常
没有初始化:RedisTemplate<String,Object> template;
这个只是声明了template的类型,没看到哪里对它初始化了,那么template是NULL。