简体   繁体   English

在春季应用程序中将Controller注入服务层是一个好习惯吗?

[英]is it a good practice to inject Controller into service layer in spring applicaiton?

I am seeing some code injects Controller as dependency into service layer in a spring application. 我看到一些代码将Controller作为依赖项注入到Spring应用程序的服务层中。 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? 有人可以告诉我为什么还是为什么不是个好主意吗?

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. 例如,HTTP控制器或通过消息队列获取其请求的控制器。

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. 假设明天您的老板不再希望使用HTTP,而是希望所有新请求都通过消息队列进入。 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. 这样,您的控制器将需要服务类,而不需要其他方法。

You should not inject the Controller into the Service 您不应将Controller注入服务

"Domain" classes(like DAOs) -- >Injected into "Services" --> then "Services" into Controller(s). “域”类(例如DAO)->注入“服务”->然后注入“服务”到控制器。

No. A good practice is to do the inverse injection. 否。一个好的做法是进行反向注入。 I mean to inject the service into controller. 我的意思是将服务注入控制器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM