目录
场景
在一些普通的工具类或者POJO类需要注入service或者repository等spring管理的资源进行一定的逻辑处理,普通类不受spring管理,所以利用@Autowired实现不了。本文介绍几种方式解决此问题。
本文利用老师与学生的关系作为例子讲解,一个老师可以管理多个学生,在查询老师列表时也将他名下的学生查询出来,Teacher表与Student不进行关联表处理,那么就需要在Teacher的Entity里注入StudentService进行查询。
数据准备
数据库
Student
uuid | deleted | status | teacher
------+---------+----------+---------
s1 | | active | t1
s2 | deleted | inactive | t1
(2 rows)
Teacher
uuid
------
t1
t2
(2 rows)
Entity
Teacher
不同的实现方法有不同的注入,具体的参考下文
Student
@Data
@Entity
@Table(name = "student")
@EqualsAndHashCode(of = {
"id"})
public class Student {
@Column(name = "uuid")
@Id
private String id;
@Column(name = "deleted")
private String deleted;
@Column(name = "status")
private String status;
@Column(name = "teacher")
private String teacher;
}
Repository
StudentReposity
@Repository
public interface StudentReposity extends CrudRepository<Student, String>{
@Query("select s from Student s where s.teacher=:teacherId")
public Set<Student> findStudentsByTeacher(@Param("teacherId") String teacherId);
}
TeacherRepository
@Repository
public interface TeacherRepository extends CrudRepository<Teacher, String>{
@Query("select t from Teacher t")
public Set<Teacher> findTeachers();
}
Service
StudentService
@Service
public class StudentService {
@Autowired
StudentReposity studentReposity;
public Set<Student> findStudentsByTeacher(String teacherId){
return studentReposity.findStudentsByTeacher(teacherId);
}
}
TeacherService
@Service
public class TeacherService {
@Autowired
TeacherRepository teacherRepository;
public Set<Teacher> findTeachers(){
return teacherRepository.findTeachers();
}
}
Controller
@RestController
public class TeacherController {
@Autowired
TeacherService teacherService;
@GetMapping("/teachers")
public Set<Teacher> fi