@Component、@Repository和@Service注释是否可以在Spring中互换使用,或者它们除了充当符号设备之外,是否提供任何特定功能?
换句话说,如果我有一个Service类,并且我将注释从@Service更改为@Component,它的行为是否仍然相同?
或者注释是否也会影响类的行为和功能?
@Component、@Repository和@Service注释是否可以在Spring中互换使用,或者它们除了充当符号设备之外,是否提供任何特定功能?
换句话说,如果我有一个Service类,并且我将注释从@Service更改为@Component,它的行为是否仍然相同?
或者注释是否也会影响类的行为和功能?
当前回答
在Spring 4中,最新版本:
@Repository注释是满足存储库的角色或原型(也称为数据访问对象或DAO)。该标记的用途之一是自动翻译第20.2.2节“例外翻译”中所述的例外。Spring提供了更多的原型注释:@Component、@Service、,和@Controller@组件是任何Spring管理的组件@Repository、@Service和@Controller是@Component的专门化,用于更具体的用例例如,在持久性、服务和表示层中,分别地因此,可以使用@组件,但使用@Repository、@Service或@相反,您的类更适合通过工具处理或与方面相关。例如,这些原型注释是切入点的理想目标。它也是@Repository、@Service和@Controller可能携带Spring框架未来版本中的附加语义。因此如果您选择使用@Component或@Service服务层,@service显然是更好的选择。同样,作为如上所述,@Repository已被支持作为持久化层中的自动异常转换。
其他回答
@Component、@Repository、@Controller和@Service注释之间的差异
@组件–通用,可跨应用程序使用@服务–在服务层级别注释类@控制器–注释表示层级别的类,主要用于SpringMVC。@Repository–在持久层注释类,它将充当数据库存储库。
@控制器=@Component(内部注释)+表示层功能@服务=@Component(内部注释)+服务层功能@分量=实际分量(豆类)@Repository=@Component(内部注释)+数据层特性(用于处理域bean)
即使我们交换@Component或@Repository或@service
它的行为是一样的,但一个方面是,如果我们使用component或@service,它们将无法捕获与DAO相关的特定异常,而不是Repository
@存储库@Service和@Controller用作@Component的专用化,以便更具体地使用。在此基础上,您可以将@Service替换为@Component,但在这种情况下,您会失去专用化。
1. **@Repository** - Automatic exception translation in your persistence layer.
2. **@Service** - It indicates that the annotated class is providing a business service to other layers within the application.
存储库和服务是组件注释的子级。所以,它们都是组件。存储库和服务只是扩展它。具体如何?服务只有意识形态上的区别:我们把它用于服务。存储库具有特定的异常处理程序。
@Component:你注释一个类@Component,它告诉hibernate它是一个Bean。
@Repository:您注释一个类@Repositories,它会告诉hibernate它是一个DAO类,并将其视为DAO类。意味着它使未检查的异常(从DAO方法抛出)有资格转换为SpringDataAccessException。
@服务:这告诉hibernate它是一个服务类,您将在其中使用@Transactional等服务层注释,因此hibernate将其视为服务组件。
另外,@Service是@Component的进步。假设bean类名为CustomerService,因为您没有选择XMLbean配置方式,所以您使用@Component注释了bean,以将其指示为bean。因此,在获取bean对象CustomerService cust=(CustomerService)context.getBean(“CustomerService”)时;默认情况下,Spring会将组件的第一个字符从“CustomerService”小写为“CustomerService”。您可以检索名为“customerService”的组件。但是,如果对bean类使用@Service注释,则可以通过以下方式提供特定的bean名称
@Service("AAA")
public class CustomerService{
您可以通过
CustomerService cust = (CustomerService)context.getBean("AAA");