各位前辈,我现在在初学redis,用了RedisTemplate。配置如下:
@Bean
public static RedisConnectionFactory redisConnectionFactory(){
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setPort(6379);
factory.setHostName("127.0.0.1");
factory.afterPropertiesSet();
return factory;
}
@Bean
public static RedisTemplate redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String, Object> template = new RedisTemplate();
template.setConnectionFactory(factory);
template.afterPropertiesSet();
return template;
}
在新的项目springboot环境中的启动类里面有main方法。由于main是静态方法,我只能这样注入redisTemplate:
private static RedisTemplate template;
@Autowired
public TestapiApplication(RedisTemplate redisTemplate) {
this.template = redisTemplate;
}
public static void main(String[] args) {
SpringApplication.run(TestapiApplication.class, args);
//....
}
redisTemplate可以运行成功。
我就在自己的Web项目中写了一个配置类RedisConfid.java以及一个工具类RedisUtil.java。其中工具类的静态方法test方法就是上述main方法的内容,在某个controller里面直接使用工具类的静态方法,运行的时候报redisTemplate空指针的错误。
我想问问各位前辈,一样的环境为什么Web下会出现空指针?
说几点:
RedisConfid.java
里面包含这两个Bean注解的方法,需要加上@Configuration
注解。SpringApplication.run(TestapiApplication.class, args);
这玩意放到工具类的test方法里了?如果是这样,我不明白你调用这个run方法有什么意义。你应该去了解一下SpringBoot的启动方法也就是这个run方法干了什么事.