Issue
Let me explain the situation with an example.
Currently, there are teams and members as Models.
class Member {
String name;
Team team;
}
class Team {
String teamName;
}
There is a MemberRepository that can access the Member database.
public interface MemberRepository {
public Member findByName(String name);
}
MemberService that can inquire Member exists.
@Service
Memberservice {
@Autowired
MemberRepository memberRepository;
public Member searchMember(String name) {
return memberRepository.findByName(name);
}
}
In this situation, When creating TeamService If you need to inquire about members , Which one is better to inject, Memberservice or MemberRepository?
Solution
Following the single responsibility principle, you should strive to keep your classes focused on doing a few and related things. With this in mind, MemberService should be the only one managing Members and this includes being the only one that touches MemberRepository. Having said this you should definitely inject MemberService.
As a general rule of thumb, you should avoid multiple Services using the same Repository. If you fail to do so you might end up with spaghetti code. This means that Services should "communicate" between them.
Answered By - João Dias
Answer Checked By - Marie Seifert (JavaFixing Admin)