【问题标题】:When should I use @Component instead of @Service? [closed]什么时候应该使用@Component 而不是@Service? [关闭]
【发布时间】:2018-01-18 18:53:42
【问题描述】:

我已经阅读了What's the difference between @Component, @Repository & @Service annotations in Spring? 中的每个 Spring 注释

我知道 @Component@Service 在 Spring Framework 中的作用几乎相同。区别在于它的用途,所以我只是在 服务层 中使用@Service 来访问我的存储库

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

【问题讨论】:

  • 最终没关系,只使用你认为合乎逻辑的东西。有时我在不使用存储库的类上使用@Service,而只使用其他服务。

标签: java spring spring-boot software-quality


【解决方案1】:

请记住,这些是 Spring 刻板印象,应该作为通常应用的围绕代码的刻板印象或假设来应用。

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

Spring 最终将这两者视为@Components。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 2017-09-11
    • 2020-01-13
    • 2013-04-06
    • 2012-12-23
    • 2021-07-13
    相关资源
    最近更新 更多