RedisUtil工具类,redisTemplate装配对象为null问题。静态方法如何获取注入的静态变量

最近在写Redis的小demo,发现在写reidisUtil工具类时,不管怎样,获取的redisTemplate对象都为null.下面我将代码为大家展示出来。

package com.xcbeyond.springboot.redis;

import com.alibaba.fastjson.JSON;
import com.xcbeyond.springboot.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

/**
 * redis操作工具类
 */
@Component
public class RedisUtils{

    @Autowired
	private static RedisTemplate<String, String> redisTemplate;

    /**
	 * 读取缓存
	 * 
	 * @param key
	 * @return
	 */
	public static String get(final String key) {
		return redisTemplate.opsForValue().get(key);
	}

	/**
	 * 写入缓存
	 */
	public static boolean set(final String key, String value) {
		boolean result = false;
		try {
//			redisTemplate.opsForValue().set(key, value);
			System.out.println(new RedisTemplate<>()+"+++++++++++___________");
			System.out.println(key+"key   key");
			System.out.println(value+"value    value");
			System.out.println(redisTemplate+"  redistamplate  redisTemplate");
			redisTemplate.opsForValue().set(key, value);
//			new RedisTemplate<>().opsForValue().set(key, value);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 更新缓存
	 */
	public static boolean getAndSet(final String key, String value) {
		boolean result = false;
		try {
			redisTemplate.opsForValue().getAndSet(key, value);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 删除缓存
	 */
	public static boolean delete(final String key) {
		boolean result = false;
		try {
			redisTemplate.delete(key);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 用于将查询出的历史记录List转化为json格式字符串,存储到redis
	 * */
	public static String toJson(List<User> list){
		if (ifListNull(list))
			return null;
		return JSON.toJSONString(list);
	}

	/**
	 * 用于 递推 判断 List是否为空
	 * */
	public static boolean ifListNull(List list){
		if (list == null||list.size()==0)
			return true;
		Iterator iterator = list.iterator();

		while(iterator.hasNext()){
			Object next = iterator.next();
			if (next!=null){
				if((next instanceof List?ifListNull((List) next):false)?false:true)
					return false;
			}
		}
		return true;
	}
	private static boolean ifListNull(Object[] a){
		if (a == null)
			return true;

		int n = 0;
		for (int i = 0;i<a.length;i++){
			if (a[i] == null)
				n++;
		}
		if (n == a.length)
			return true;
		return false;
	}

}

controller层

@RequestMapping(value="/queryAll", method=RequestMethod.GET)
	public String queryUser() {
		long t1=System.currentTimeMillis();
		List<User> userList=userService.queryAll();
		for (User user:userList) {
//			System.out.println(user);
		}
		long t2=System.currentTimeMillis();
		logger.info("查询用户花费了"+(t2-t1)+"毫秒  ");

		System.out.println(RedisUtils.toJson(userList)+"****************");
//		redisUtils.set("key",RedisUtils.toJson(userList));
//		redisUtils.set("key",RedisUtils.toJson(userList));
		RedisUtils.set("key",RedisUtils.toJson(userList));
		return userList + "查询成功!";

	}

说明一下:
这里我想直接调用工具类的方法,所以我需要将Redisutil工具类中的方法设置为静态–》由static修饰,这样的话,redistTemplate变量也需要有static修饰,(因为静态方法只能调用静态成员变量)并且由autowired注解进行注入(自动装配)。

但是这样代码执行过后,发现redisUtil的工具类中set方法的redisTemplate始终为null,说明该对象并没有注入该方法中。
但是这样,我没有找静态变量如何注入到静态方法的解决方法,而是使用了另一个方法进行解决。

下面为大家奉上代码。

package com.xcbeyond.springboot.redis;

import com.alibaba.fastjson.JSON;
import com.xcbeyond.springboot.model.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

/**
 * redis操作工具类.</br>
 * (基于RedisTemplate)
 * @author xcbeyond
 * 2018年7月19日下午2:56:24
 */
@Component
public class RedisUtils {

//    @Autowired
//	private static RedisTemplate<String, String> redisTemplate;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
	 * 读取缓存
	 * 
	 * @param key
	 * @return
	 */
	public String get(final String key) {
		return redisTemplate.opsForValue().get(key);
	}

	/**
	 * 写入缓存
	 */
	public boolean set(final String key, String value) {
		boolean result = false;
		try {
//			redisTemplate.opsForValue().set(key, value);
			System.out.println(new RedisTemplate<>()+"+++++++++++___________");
			System.out.println(key+"key   key");
			System.out.println(value+"value    value");
			System.out.println(redisTemplate+"  redistamplate  redisTemplate");
			redisTemplate.opsForValue().set(key, value);
//			new RedisTemplate<>().opsForValue().set(key, value);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 更新缓存
	 */
	public boolean getAndSet(final String key, String value) {
		boolean result = false;
		try {
			redisTemplate.opsForValue().getAndSet(key, value);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 删除缓存
	 */
	public boolean delete(final String key) {
		boolean result = false;
		try {
			redisTemplate.delete(key);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 用于将查询出的历史记录List转化为json格式字符串,存储到redis
	 * */
	public static String toJson(List<User> list){
		if (ifListNull(list))
			return null;
		return JSON.toJSONString(list);
	}

	/**
	 * 用于 递推 判断 List是否为空
	 * */
	public static boolean ifListNull(List list){
		if (list == null||list.size()==0)
			return true;
		Iterator iterator = list.iterator();

		while(iterator.hasNext()){
			Object next = iterator.next();
			if (next!=null){
				if((next instanceof List?ifListNull((List) next):false)?false:true)
					return false;
			}
		}
		return true;
	}
	private static boolean ifListNull(Object[] a){
		if (a == null)
			return true;

		int n = 0;
		for (int i = 0;i<a.length;i++){
			if (a[i] == null)
				n++;
		}
		if (n == a.length)
			return true;
		return false;
	}

}

将原来的redisTemplate对象(注入方式)由autowired注解改为了resource注解
controller层

	@Resource
	private RedisUtils redisUtils;


	@RequestMapping(value="/queryAll", method=RequestMethod.GET)
	public String queryUser() {
		long t1=System.currentTimeMillis();
		List<User> userList=userService.queryAll();
		for (User user:userList) {
//			System.out.println(user);
		}
		long t2=System.currentTimeMillis();
		logger.info("查询用户花费了"+(t2-t1)+"毫秒  ");

		System.out.println(RedisUtils.toJson(userList)+"****************");
//		redisUtils.set("key",RedisUtils.toJson(userList));
		redisUtils.set("key",RedisUtils.toJson(userList));
		return userList + "查询成功!";
	}

这样的话,redisUtil工具类中的set方法不需要static修饰,但是在controller层,redisUtils工具类需要由resource注解修饰一下,这样工具类中的方法就可以由装配后的工具类进行调用。
并且工具类的redisTemplate也不会为null.


这辈子坚持与不坚持都不可怕,怕的是独自走在前进的道路上!!!

欢迎加入技术群聊

在这里插入图片描述


  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值