You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBootTest中RedisService注入为空引发空指针异常求助

解决RedisService注入空指针问题

核心原因

测试类中的redisService未被Spring容器成功注入,导致调用setValue时抛出NullPointerException。

分步解决方案

1. 检查测试类的包扫描范围

Spring Boot测试默认扫描主启动类所在包及其子包下的组件。

  • 确认RedisService所在包是主启动类包的子包,或者在@SpringBootTest注解中指定主启动类:
@SpringBootTest(classes = YourMainApplication.class) // 替换成你的项目主启动类
public class RedisDemoTest{
    // ... 原有代码
}

2. 验证RedisService的注解正确性

确保RedisService上的@Service注解是Spring官方包下的:

import org.springframework.stereotype.Service; // 必须导入此包的注解

@Service
public class RedisService {
    // ... 原有代码
}

3. 检查测试类的依赖注入配置

  • 确保测试类中的@Resource或@Autowired注解包导入正确:
import javax.annotation.Resource; // 或 org.springframework.beans.factory.annotation.Autowired
  • 若使用@Autowired,可显式指定required = true(默认值)强制检查注入有效性:
@Autowired(required = true)
private RedisService redisService;

4. 补充JedisPool配置(避免后续报错)

当前问题解决后,JedisPool可能也会出现注入失败,需添加配置类初始化连接池:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {

    @Bean
    public JedisPool jedisPool() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(10);
        poolConfig.setMaxIdle(5);
        // 根据你的Redis实例配置地址、端口、超时时间等参数
        return new JedisPool(poolConfig, "localhost", 6379, 10000);
    }
}

5. 优化RedisService的资源管理

原代码手动关闭Jedis客户端易引发连接泄漏,改用try-with-resources自动管理资源:

public RedisService setValue(String key, Long value){
    try (Jedis client = jedisPool.getResource()) {
        client.set(key, value.toString());
    }
    return this;
}

public String getValue(String key) {
    try (Jedis client = jedisPool.getResource()) {
        return client.get(key);
    }
}

验证步骤

  1. 确保Redis服务正常运行(本地或远程实例)。
  2. 重新运行stockTest方法,此时redisService会被正确注入,控制台将打印出10。

内容的提问来源于stack exchange,提问作者SlientDrinker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 05:15:20