今天在写一个工具类,里面用了@Autowired
注入了StringRedisTemplate以及RedisTemplate时,在template.opsForValue().set(key, obj)方法一直报 java.lang.nullpointerexception
异常,通过调试发现template为null。java
Spring 注入失败redis
可能的缘由: 网上百度了好久,缘由可能在于个人utils包的类和controller的类不是同一个上下文。服务器
经过添加如下三个关键的地方,能够解决该问题函数
关于@PostConstruct:被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,而且只会被服务器调用一次,相似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数以后,init()方法以前运行。
//解决工具类中注入 3个步骤 @Component //关键步骤1,添加Component public class RedisUtils { @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate<String, Object> template; public static RedisUtils redisUtils; // 关键2 添加该类的静态对象 protected static Logger logger = LoggerFactory.getLogger(RedisUtils.class); public RedisUtils() { } // 关键3 用PostConstruct修饰init方法,并在init方法中对其赋值 @PostConstruct public void init() { redisUtils = this; redisUtils.template = this.template; redisUtils.stringRedisTemplate = this.stringRedisTemplate; }
这样就能够经过redisUtils.template.opsForValue().set(key, obj)调用了工具