@Component、@Repository和@Service注释是否可以在Spring中互换使用,或者它们除了充当符号设备之外,是否提供任何特定功能?

换句话说,如果我有一个Service类,并且我将注释从@Service更改为@Component,它的行为是否仍然相同?

或者注释是否也会影响类的行为和功能?


当前回答

@组件是顶级通用注释,它使带注释的bean能够被扫描并在DI容器中可用

@Repository是专门的注释,它具有转换DAO类中所有未检查的异常的功能

@服务是专门的注释。到目前为止,它没有带来任何新特性,但它阐明了bean的意图

@控制器是专门的注释,它使bean MVC意识到,并允许使用进一步的注释,如@RequestMapping等

以下是更多详细信息

其他回答

来自Spring文档:

@Repository注释是满足存储库的角色或原型(也称为数据访问对象或DAO)。该标记的用途之一是自动翻译异常,如异常转换中所述。Spring提供了更多的原型注释:@Component、@Service、,和@Controller@组件是任何Spring管理的组件@Repository、@Service和@Controller是@Component的专门化,用于更具体的用例(在持久性、服务和表示层)。因此,您可以使用@component注释组件类,但是,通过用@Repository、@Service或@Controller注释它们相反,您的类更适合由工具处理或与方面相关。例如,这些原型注释成为切入点的理想目标@存储库、@Service和@控制器还可以在未来版本的Spring框架。因此,如果您在使用@组件或服务层的@Service,@Service显然是更好的选择。同样,如前所述,@Repository已经支持作为自动异常转换的标记持久层。

Annotation Meaning
@Component generic stereotype for any Spring-managed component
@Repository stereotype for persistence layer
@Service stereotype for service layer
@Controller stereotype for presentation layer (spring-mvc)

它们几乎相同——所有这些都意味着这个类是一个Spring bean@Service、@Repository和@Controller是专门的@Components。您可以选择与他们一起执行特定操作。例如:

@springmvc使用控制器bean@存储库bean有资格进行持久性异常转换

另一件事是将组件语义上指定给不同的层。

@Component提供的一点是,您可以用它注释其他注释,然后以与@Service相同的方式使用它们。

例如,最近我做了:

@Component
@Scope("prototype")
public @interface ScheduledJob {..}

因此,所有用@ScheduledJob注释的类都是springbean,除此之外,它们还注册为石英作业。您只需要提供处理特定注释的代码。

所有这些注释都是立体类型的注释类型,这三种注释之间的区别是

如果我们添加@Component,那么它告诉类的角色是一个组件类,这意味着它是一个包含一些逻辑的类,但它无法确定包含特定业务或持久性或控制器逻辑,因此我们不直接使用@零部件注释如果我们添加@Service注释,那么它告诉组成业务逻辑的类的角色如果我们在类的顶部添加@Repository,那么它告诉一个包含持久性逻辑的类这里@Component是@Service、@Repository和@Controller注释的基础注释

例如

package com.spring.anno;
@Service
public class TestBean
{
    public void m1()
    {
       //business code
    }
}

package com.spring.anno;
@Repository
public class TestBean
{
    public void update()
    {
       //persistence code
    }
}

每当我们添加@Service或@Repositroy或@Controller注释时,@Component注释将默认存在于类的顶部

@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");

@存储库@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.