Java 五种方法实现普通类注入spring管理的service、repository等资源

场景

在一些普通的工具类或者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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值