SpringBootTest自动注入失败@Autowired

注入失败的代码:

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
public class LearnTest {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Test
    public void testRedis()
    {
        stringRedisTemplate.opsForValue().set("v","ymy");
        System.out.println(stringRedisTemplate.opsForValue().get("a"));
    }
}

已配置好Redis,再验证是否能够连接成功的时候,发现执行到stringRedisTemplate.opsForValue()的时候会报错:空指针异常,Debug发现,stringRedisTemplate为null,竟然没有成功注入。
解决方法:
设置在运行类的时候,启动整个springboot项目,从而达到自动注入的效果,在测试方法运行结束后,springboot项目也就会关闭了。
在测试类上加上这个注解即可,就可以使用@Autowired注解了
此处参考:https://blog.csdn.net/mrhamster/article/details/103393853

import cn.ymy.redis.HomeApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = HomeApplication.class)
public class LearnTest {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Test
    public void testRedis()
    {

        stringRedisTemplate.opsForValue().set("v","ymy");
        System.out.println(stringRedisTemplate.opsForValue().get("v"));
    }
}

这个时候就能成功注入依赖了

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值