我何时应该使用@Component而不是@Service?

时间:2018-01-18 18:53:43

标签: java spring spring-boot software-quality

我已经在What's the difference between @Component, @Repository & @Service annotations in Spring?

中了解了每个Spring注释

我知道@Component@Service在Spring Framework中几乎完全相同。它的区别在于它的用途,因此我只需将@Service用于服务层,即可访问我的存储库。< / p>

我想知道选择@Component而不是@Service的更好方法是什么。请注意,我现在正在为我创建的工厂使用@Component,因为工厂不需要处理存储库。

1 个答案:

答案 0 :(得分:5)

请记住,这些是Spring的刻板印象,应该适用于通常应用围绕一个代码的刻板印象或假设。

  • 如果您的组件是通用组件,并非真正位于服务层,或者可以访问但可以保持状态,那么请使用@Component
  • 如果您的组件是特定服务,位于服务层,或者可以访问且固有地保持状态,请使用@Service

Spring将这两者最终视为@Component