Skip to content

Commit ddec979

Browse files
committed
Update Spring Data Redis example to use constructor injection
1 parent e6cc0bb commit ddec979

2 files changed

Lines changed: 20 additions & 7 deletions

File tree

‎spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
package org.baeldung.spring.data.redis.repo;
22

33
import org.baeldung.spring.data.redis.model.Student;
4+
import org.springframework.data.redis.core.RedisTemplate;
45
import org.springframework.stereotype.Component;
56

67
import java.util.Map;
78

89
public interface StudentRepository {
9-
10+
1011
void saveStudent(Student person);
1112

1213
void updateStudent(Student student);

‎spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java‎

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,36 +2,48 @@
22

33
import org.baeldung.spring.data.redis.model.Student;
44
import org.springframework.beans.factory.annotation.Autowired;
5+
import org.springframework.data.redis.core.HashOperations;
56
import org.springframework.data.redis.core.RedisTemplate;
67
import org.springframework.stereotype.Repository;
78

9+
import javax.annotation.PostConstruct;
810
import java.util.Map;
911

1012
@Repository
1113
public class StudentRepositoryImpl implements StudentRepository {
1214

1315
private static final String KEY = "Student";
1416

15-
@Autowired
1617
private RedisTemplate<String, Object> redisTemplate;
18+
private HashOperations hashOperations;
19+
20+
@Autowired
21+
public StudentRepositoryImpl(RedisTemplate<String, Object> redisTemplate) {
22+
this.redisTemplate = redisTemplate;
23+
}
24+
25+
@PostConstruct
26+
private void init() {
27+
hashOperations = redisTemplate.opsForHash();
28+
}
1729

1830
public void saveStudent(final Student student) {
19-
redisTemplate.opsForHash().put(KEY, student.getId(), student);
31+
hashOperations.put(KEY, student.getId(), student);
2032
}
2133

2234
public void updateStudent(final Student student) {
23-
redisTemplate.opsForHash().put(KEY, student.getId(), student);
35+
hashOperations.put(KEY, student.getId(), student);
2436
}
2537

2638
public Student findStudent(final String id) {
27-
return (Student) redisTemplate.opsForHash().get(KEY, id);
39+
return (Student) hashOperations.get(KEY, id);
2840
}
2941

3042
public Map<Object, Object> findAllStudents() {
31-
return redisTemplate.opsForHash().entries(KEY);
43+
return hashOperations.entries(KEY);
3244
}
3345

3446
public void deleteStudent(final String id) {
35-
this.redisTemplate.opsForHash().delete(KEY, id);
47+
hashOperations.delete(KEY, id);
3648
}
3749
}

0 commit comments

Comments
 (0)