SpringBoot整合Redis的坑

本文介绍了在Spring Boot测试中遇到的RedisTemplate未找到bean的问题,原因在于缺少@RunWith(SpringRunner.class)注解和@SpringBootTest配置的包名一致性。作者分享了解决步骤和注意事项,帮助读者避免此类Spring Boot新手常见坑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我在项目的测试包里面写了测试方法,然后注入RedisTemplate,发现redisTemplate爆红,提示找不到bean。首先说下我犯得错误。
1、在这里插入图片描述
在这里插入图片描述
这是主要的原因,没有加@RunWith(SpringRunner.class)注解
然后我的@SpringBootTest还要在后面指定上classes = Application.class,这是因为我的main启动的包名和Test的包名不一致导致的。
spring boot测试类包名与main下application.class启动类的包名默认要一致
这个bug相对于踩了两坑,还是SpringBoot不熟练

在这里插入图片描述

package com.ccl;

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.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;


/**
 * @author 超厉害的我啊
 * @date 2021/3/23 10:46:09
 */

@RunWith(SpringRunner.class)
//@SpringBootTest(classes = Application.class)
@SpringBootTest
public class ApplicationTest {

    @Autowired
    private RedisTemplate redisTemplate;

//    @Resource
//    RedisTemplate redisTemplate;

    @Test
    public void contextLoads(){

        //redisTemplate     操作不同的数据类型,ops和redis的指令是一样的
        //opsForValue       操作字符串 类似String
        //opsForList        操作List 类似List
        //opsForHash
        //.....

        redisTemplate.opsForHash();
        redisTemplate.opsForValue();

        //除了基本的操作,我们常用的方法都可以直接通过redisTemplate操作,比如事务,和基本的CRUD

        //获取redis的连接对象
//        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
//        connection.flushAll();
//        connection.flushDb();
        redisTemplate.opsForValue().set("mykey","ccl");
        System.out.println(redisTemplate.opsForValue().get("mykey"));


    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值