Update Spring Data Redis example to use constructor injection

This commit is contained in:
David Morley 2016-02-01 05:51:27 -06:00
parent e6cc0bb722
commit ddec979e4d
2 changed files with 20 additions and 7 deletions

View File

@ -1,12 +1,13 @@
package org.baeldung.spring.data.redis.repo;
import org.baeldung.spring.data.redis.model.Student;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Map;
public interface StudentRepository {
void saveStudent(Student person);
void updateStudent(Student student);

View File

@ -2,9 +2,11 @@ package org.baeldung.spring.data.redis.repo;
import org.baeldung.spring.data.redis.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import java.util.Map;
@Repository
@ -12,26 +14,36 @@ public class StudentRepositoryImpl implements StudentRepository {
private static final String KEY = "Student";
@Autowired
private RedisTemplate<String, Object> redisTemplate;
private HashOperations hashOperations;
@Autowired
public StudentRepositoryImpl(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@PostConstruct
private void init() {
hashOperations = redisTemplate.opsForHash();
}
public void saveStudent(final Student student) {
redisTemplate.opsForHash().put(KEY, student.getId(), student);
hashOperations.put(KEY, student.getId(), student);
}
public void updateStudent(final Student student) {
redisTemplate.opsForHash().put(KEY, student.getId(), student);
hashOperations.put(KEY, student.getId(), student);
}
public Student findStudent(final String id) {
return (Student) redisTemplate.opsForHash().get(KEY, id);
return (Student) hashOperations.get(KEY, id);
}
public Map<Object, Object> findAllStudents() {
return redisTemplate.opsForHash().entries(KEY);
return hashOperations.entries(KEY);
}
public void deleteStudent(final String id) {
this.redisTemplate.opsForHash().delete(KEY, id);
hashOperations.delete(KEY, id);
}
}