Spring 中刻板印象的错误使用以及他们在幕后实际做了什么

Incorrect usage of Stereotypes in Spring and what do they actually do behind the scenes

Spring 的@Component 的特殊变体是否使用不当?即,如果我调用我的服务 class @Repository 而不是 @Service 或相反。 是否有针对此类不当使用的任何保护措施,或者只是建议根据上下文正确使用它们而无需 Spring 的任何强制措施?

有人可以让我知道每个 Stereotype 到底发生了什么吗?我阅读了 javadocs 但不完全理解每个 Spring Stereotype 提供了哪些专门的功能集

是的,您可以用 @Repository@Service 注释任何 class,它们的行为相同,但文档中有趣的一点是:

Therefore, you can annotate your component classes with @Component, but by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts.

Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated above, @Repository is already supported as a marker for automatic exception translation in your persistence layer.

在这里你可以看到正在讨论的两个重要的事情切入点的理想目标在第一段和第二段作为自动异常翻译

显然,如果您了解 AOP,第一个是可以理解的,第二个是关于这些注释的一件美妙的事情。让我们看看文档 automatic exception translation 是什么意思:

Common data access exceptions. Spring can wrap exceptions from your O/R mapping tool of choice, converting them from proprietary (potentially checked) exceptions to a common runtime DataAccessException hierarchy. This allows you to handle most persistence exceptions, which are non-recoverable, only in the appropriate layers, without annoying boilerplate catches/throws, and exception declarations. You can still trap and handle exceptions anywhere you need to. Remember that JDBC exceptions (including DB specific dialects) are also converted to the same hierarchy, meaning that you can perform some operations with JDBC within a consistent programming model.

所以基本上,它们是相同的,但当你深入挖掘时,它们会有一点不同。希望你明白了。 例如,如果我们用 @Service 注释对所有 classes 进行注释,则所有这些 classes 都将在容器中注册,但情况会有所不同。看,如果你用 @Repository 注释注释一些 class, 后处理器会自动查找所有异常翻译器(PersistenceExceptionTranslator 接口的实现)并建议所有标有 @Repository 注释的 bean 所以发现的翻译器可以拦截并在抛出的异常上应用适当的翻译。

因此,这又是关于某种异常处理的。现在,如果您使用 @Service 注释而不是 @Repository 注释来注释 class,则不会发现所需的翻译器。

现在关于 @Service 注释。这个注解对 table 的贡献并不比 @Component 多。它们是相同的,唯一的区别是 @Service 注释是 @Component 的特化,它根据文档添加的唯一特化是

This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate. Hence, @Service just adds more understanding than @Component.

所以,最后,我们知道它们几乎相同,只是略有不同,其中 @Repository 注解在 DAO class 的情况下有更多好处.