1

I am seeing some code injects Controller as dependency into service layer in a spring application. My first reaction is this seems very wrong, but I don't know how to explain it to my colleague. Can someone please give me why or why not a good idea?

Ben Li
  • 117
  • 1
  • 1
  • 9
  • Yes, this is a bad practice. The cleaner practice would be to create another class that contains the state and behavior your dependent class needs, and instantiate that class in the controller and inject into the dependent class. – Brian Driscoll Jan 10 '18 at 17:32
  • You can take a look in this [answer](https://stackoverflow.com/questions/15922991/is-spring-annotation-controller-same-as-service) too. Of course, it is bad practice. – lzagkaretos Jan 10 '18 at 17:33

3 Answers3

3

No. A good practice is to do the inverse injection. I mean to inject the service into controller.

3

This is not a good idea. The controller is meant to deal with the receiving of new requests. Hence controllers are tightly coupled to the medium/technology that they operate on. For example HTTP controllers, or controllers that get their requests via a message queue.

The service classes, on the other hand, are designed to not be coupled at all with how the request arrived into the application. This allows you to re-use service classes, which contain the main business logic, across various controllers. Let say that tomorrow your boss no longer wants to use HTTP, and instead wants all new requests to come in via a message queue. Because your service classes are not dependent to any controller classes, it will be a lot easier to alter your application so that it can properly process requests coming from the message queue.

As such, your controllers would require the services classes, and not the other way around.

Jose Martinez
  • 11,452
  • 7
  • 53
  • 68
3

You should not inject the Controller into the Service

"Domain" classes(like DAOs) -- >Injected into "Services" --> then "Services" into Controller(s).

Jeryl Cook
  • 989
  • 17
  • 40