Hyeonjun Park
Hyeonjun Park

Reputation: 48

Which dependency injection is appropriate in the MVC pattern?

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?

Upvotes: 0

Views: 105

Answers (1)

João Dias
João Dias

Reputation: 17460

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.

Upvotes: 2

Related Questions