先上工具代码
import org.springframework.beans.factory.annotation.Autowired;
import com.ssh.dao.RedisServer;
public class RedisUtil {
@Autowired
private static RedisServer redisServer;
public static <T> void put(String key, T obj) {
redisServer.put(key, obj);
}
public static <T> void put(String key, T obj, int timeout) {
redisServer.put(key, obj,timeout);
}
public static <T> T get(String key, Class<T> cls) {
return redisServer.get(key,cls);
}
public static <T> String get(String key) {
return redisServer.get(key);
}
}
当我们调用
RedisUtil.put(obj,obj);
就会报空指针,原因是因为静态变量不属于对象,只属于类,也就是说在类被加载字节码的时候变量已经初始化了,也就是给该变量分配内存了,导致spring忽略静态变量,在调用静态变量时就会报空指针。
解决办法:
使用 @Component 将redisUtil 注册为组件,创建需要注入的非静态成员变量,再使用 @PostConstruct 等待初始化完成后将注入的成员变量赋值给静态成员变量
下面贴代码
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ssh.dao.RedisServer;
@Component
public class RedisUtil {
@Autowired
private RedisServer redisServerTemp;
private static RedisServer redisServer;
private static RedisUtil redisUtilTemp;
@PostConstruct
public void init(){
redisUtilTemp = this;
redisServer =this.redisServerTemp;
}
public static <T> void put(String key, T obj) {
redisServer.put(key, obj);
}
public static <T> void put(String key, T obj, int timeout) {
redisServer.put(key, obj,timeout);
}
public static <T> T get(String key, Class<T> cls) {
return redisServer.get(key,cls);
}
public static <T> String get(String key) {
return redisServer.get(key);
}
}