何时使用 spring 中的服务或组件?

When to use service or component in spring?

何时使用 spring 中的服务或组件?

例如,负责发送电子邮件或常见业务逻辑的模块是"service"还是"component"? 有什么区别?

一个服务可以调用其他服务吗? 交易有问题吗?或者服务应该只调用组件?

有人告诉我,一个服务不应该调用其他服务,而应该只调用组件,这意味着 Controller->Service->Component->DAO,但我发现很多人都认同 Controller-> 的概念服务->没有组件的 DAO。

在Spring中是否有关于此主题的任何系统设计标准?

@Component 对其他刻板印象是通用的。
所以你可以更换 @Repository, @Service, @Controller@Component,什么都不会改变。但为了更好的可读性,你应该使用 @Repository, @Service, @Controller

为了 "configure" Spring 可以为您提供您需要的 classes 的实例,您应该告诉 Spring 涉及什么 个对象以及如何 构建它们。为此,您可以使用 xml 配置文件或通过注释

如果您采用注释方法(恕我直言,这是一种更好更简单的方法),您可以使用 @Component 来注释 class。这就像告诉 Spring:"Hey! I want you to know that you may need an instance of this class. Maybe because I request it, maybe because something I requested needs it"。所以用 @Component 注释 class 只是让 Spring 知道它存在

还有其他注释做同样的事情:

  • @Controller(和@RestController
  • @Service
  • @Repository

它们都通知Spring class 涉及DI 上下文。 但是它们也有语义:

  • @Controller = @Component属于表示层
  • @Service = @Component 属于 Service/Use 个案例层
  • @Repository = @Component属于持久层

您可以在 this question

中找到更多信息

Should a service be able to call the other services?

我认为这没有任何问题。如果您的任何服务需要执行其他人已经执行的某些操作,您肯定希望避免代码重复。只要您尊重架构层依赖性(永不上升),您就会没事的。

关于这个你可以查看this article关于Clean Architecture