【Java】SpringCloud中使用set方法报错空指针

前言:今天在交流群中看见了一个空指针报错,想着哪里为空点过去看看为什么赋不上值就行,没想到啪啪打脸了,今天总结一下。

以下是他的RedisTempate注入和方法

可以看到,89行报错空指针。先分析一下,

①赋值没赋上吗?不对,因为84行已将将responseBodyString的值打印在控制台了,是有值的。

②那只能是redisTemlate这个方法有问题了,set赋值赋不进去。为什么呢? 

群里大佬说:“spring 注入static 对象会是个Null对象(根据name或者type实例化失败)”。

原来如此! 往上划看图一,他是这样注入的:

@Resource

private static RedisTempalte<String,Object> redisTemplate;

因为不知道spring注入static对象会是空对象,所以没考虑到这个方面。

总结:

        我们在使用注解注入set方法时,不可以加static,因为静态变量和类变量不是对象的属性,而是一个类的属性,静态方法是属于类的;而普通方法才是属于实体的对象,即new出来的对象。

参考:文章 

补充:

除了通过注解注入,我们也可以通过构造方法注入

package com.medical.member.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * @author: 宁兴星
 * Date: 2024/9/10 20:18
 * Description:
 */
@Controller
public class TestController {

    private final RedisTemplate<String, Object> redisTemplate; // 移除了 static 关键字

    // 构造函数注入
    @Autowired
    public TestController(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate; // 将 redisTemplate 赋值给实例变量
    }

    @GetMapping("test/method")
    public void test() {
        redisTemplate.opsForValue().set("test", "这是我的测试数据");
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值