我认为@Component
和@Service
都可以用来自动检测bean,任何人都可以告诉我这两个注释之间的区别吗?
答案 0 :(得分:4)
两个注释之间的基本区别在于@Service
是@Component
的特化。
另请参阅@Service
的{{3}}春天:
表示带注释的类是“服务”(例如,业务) 服务门面)。
此注释用作@Component的特化,允许 要通过类路径扫描自动检测的实现类。
组件的特化也是@Repository
和@Controller
可以找到更多信息,例如documentation
答案 1 :(得分:2)
从Spring 3.1开始,Spring处理它们的方式没有区别。 The docs say this, but in a rather obscure way:
Spring 2.5引入了更多刻板印象注释:
@Component
,@Service
和@Controller
。@Component
是任何Spring管理组件的通用构造型。对于更具体的用例,@Repository
,@Service
和@Controller
是@Component
的特化,例如,分别在持久性,服务和表示层中。因此,您可以使用@Component
注释组件类,但是通过使用@Repository
,@Service
或@Controller
注释它们,您的类更适合通过工具进行处理或与方面联系。例如,这些刻板印象注释成为切入点的理想目标。@Repository
,@Service
和@Controller
也可能在Spring Framework的未来版本中带有其他语义。因此,如果您选择在服务层使用@Component
或@Service
,@Service
显然是更好的选择。同样,如上所述,@Repository
已被支持作为持久层中自动异常转换的标记。
因此,目前,@Service
将被@Component
与@Service
完全相同,但@Service
可视为一种文档形式。
我不确定为什么{{1}}完全包含在Spring 2.5中,因为它似乎没有任何真正的用途。
答案 2 :(得分:0)
检查源代码
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Service { /** * The value may indicate a suggestion for a logical component name, * to be turned into a Spring bean in case of an autodetected component. * @return the suggested component name, if any */ String value() default ""; }
服务注释反过来用@Component注释。没有什么不同。
答案 3 :(得分:0)
这里解释了为什么我们需要这样的专业化......
在Spring 2.0及更高版本中,@ Repository注释是任何类的标记 履行存储库的角色或构造型(也称为数据访问对象或DAO)。该标记的用途是自动翻译例外。
Spring 2.5引入了更多的构造型注释:@ Component,@ Service和@Controller。 @Component是任何Spring管理组件的通用构造型。 @Repository,@ Service和@Controller是@Component的特殊化,用于更具体的用例,例如,分别在持久性,服务和表示层中。
因此,您可以使用@Component注释组件类,但是通过使用@ Repository,@ Service或@Controller注释它们,您的类更适合通过工具处理或与方面关联。例如,这些刻板印象注释成为切入点的理想目标。
因此,如果您选择在服务层使用@Component或@Service,@ Service显然是更好的选择。同样,如上所述,已经支持@Repository作为持久层中自动异常转换的标记。