0
@Component
public class RepositoryContainer {
    @Autowired
    public CommentRepository commentRepository;
    @Autowired
    public ItemRepository itemRepository;
    @Autowired
    public UserRepository userRepository;
    @Autowired
    public PostRepository postRepository;
}

In this way, I just need to inject a single god RepositoryContainer and don't need to inject every repository that will pollute my controller.

  • 1
    There's no real gain hidding the dependencies. It just place the problem somewhere out of the controller, but the problem still remain the same. – Laiv Feb 5 '18 at 22:21
5

No, you should not. Simply hiding the dependencies by another service class will not suddenly make your controller better.

Injecting the repositories into your controller directly is much better, because once your controller grows and you inject more and more service classes, the sheer amount of injected dependencies alone is a warning sign for you to tell you that something is wrong with your design - perhaps your controller is doing too much.

Besides, the RepositoryContainer would also start to act like a service locator, which isn't very good either.

2

By injecting repositories directly into your controller, you are removing an important layer - Service layer, which is meant to do all the heavy-lifting in your application.

I agree with David Packer's answer to some extent that your controller should remain clean without too much code that doesn't have anything to do with routing calls however I wouldn't skip the service layer.

It decouples the web layer from the dao layer if anytime in the future you want to change your database implementation.

I would go for UserService, ItemService, PostService and call them from the controller and have them handle the logic for each domain separatly.

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.