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

非Spring Boot独立Maven Java项目如何正确使用spring-data-redis

问题结论

你当前的代码无法正常运行,不需要强制更换其他Redis类库,根据你是否要保留Spring的使用习惯,有两种可直接跑通的实现方案。

当前代码存在的核心问题

  • 未启动Spring IoC容器:普通Maven Java项目没有SpringBoot的自动装配逻辑,你直接new App()得到的对象不归Spring管理,@Autowired注入的Repository、@Bean注册的组件都不会生效,运行时会报空指针。
  • 依赖不全:现有pom.xml缺少Spring核心上下文依赖,Spring容器本身无法启动。
  • 配置缺失:RedisTemplate未配置序列化规则,默认JDK序列化写入Redis的内容是不可读的二进制流;实体类未加Redis映射注解,Repository无法识别要存储的实体结构。

方案1:保留spring-data-redis,修正现有代码

适合习惯Spring Repository抽象、后续可能有更复杂Redis操作的场景。

  1. 首先补全pom依赖,在<dependencies>节点下新增Spring上下文依赖,版本和你当前使用的spring-data-redis 2.3.3匹配:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.8.RELEASE</version>
</dependency>
<!-- 存JSON序列化用,不需要可以不引 -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.2</version>
</dependency>
  1. 单独写Redis配置类,把Bean定义从App类移出来,开启Redis仓库扫描:
package com.test.mvn.redis.test_redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableRedisRepositories(basePackages = "com.test.mvn.redis.test_redis")
public class RedisConfig {
    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName("localhost");
        factory.setPort(6379);
        // Redis有密码就加这行:factory.setPassword("你的密码");
        return factory;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        // 配置序列化规则,避免存二进制乱码
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
}
  1. 给Student实体类加Redis映射注解:
package com.test.mvn.redis.test_redis;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;

@Data
@RedisHash("student")
public class Student {
    public enum Gender {MALE, FEMALE}

    @Id
    private String id;
    private String name;
    private Gender gender;
    private Integer grade;

    public Student(String id, String name, Gender gender, Integer grade) {
        this.id = id;
        this.name = name;
        this.gender = gender;
        this.grade = grade;
    }
}
  1. 修正App主类启动逻辑,手动启动Spring容器拿Bean,不要自己new对象:
package com.test.mvn.redis.test_redis;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App {
    public static void main( String[] args ) {
        // 启动Spring容器加载配置
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RedisConfig.class);
        StudentRepository studentRepository = context.getBean(StudentRepository.class);
        
        Student student = new Student("Eng2015001", "John Doe", Student.Gender.MALE, 1);
        studentRepository.save(student);
        System.out.println("数据写入成功");
        
        context.close();
    }
}

原有StudentRepository接口不需要修改,直接保留即可。


方案2:去掉Spring依赖,直接用原生Jedis(更轻量)

适合只需要基础读写、不想引入Spring全家桶依赖的场景,代码更直白、启动更快。

  1. 精简pom依赖,只保留Jedis即可,spring-data-redis、lombok都可以删掉:
<dependencies>
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>3.3.0</version>
    </dependency>
    <!-- 要存对象就引JSON包,只存字符串可以不用 -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.11.2</version>
    </dependency>
</dependencies>
  1. 主类直接连Redis写数据,不需要其他配置:
package com.test.mvn.redis.test_redis;

import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.Jedis;

public class App {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    public static void main( String[] args ) throws Exception {
        // 建立连接,try-with-resource自动关闭连接
        try(Jedis jedis = new Jedis("localhost", 6379)) {
            // 直接存字符串
            jedis.set("test:str", "hello redis");
            // 存对象转成JSON字符串即可
            Student student = new Student("Eng2015001", "John Doe", Student.Gender.MALE, 1);
            jedis.set("student:Eng2015001", objectMapper.writeValueAsString(student));
            System.out.println("数据写入成功");
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 14:30:56