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

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

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


当前回答

@Component
@Controller
@Repository
@Service
@RestController

这些都是StereoType注释。这对于在ioc容器中将我们的类制作为springbean非常有用,

其他回答

来自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)

为了简化这一说明,让我们通过用例来考虑技术性,这些注释用于注入,正如我所说的“用于注入”,这意味着,如果你知道如何使用依赖注入“DI”,并且你应该这样做,那么你将一直寻找这些注释,并通过使用这些立体类型来注释类,您正在通知DI容器扫描它们,以准备在其他地方进行注入,这是实际的目标。

现在让我们来看看每一个;first@Service,如果您正在为特定的业务案例构建一些逻辑,则需要在包含您的业务逻辑的地方将其分离,该服务是普通的Class,或者您可以根据需要将其用作接口,其编写方式如下

@Service
public class Doer {
   // Your logic 
}

要在另一个类中使用它,请假设在Controller中

@Controller
public class XController {
    // You have to inject it like this 
    @Autowired 
    private Doer doer;

    // Your logic
}

当你注入它们时,它们都是相同的方式,@Repository这是一个应用Repository Pattern Repository设计模式实现的接口,通常在处理某些数据存储或数据库时使用,你会发现,它包含多个现成的实现,供你处理数据库操作;它可以是CrudRepository、JpaRepository等。

例如:

public interface DoerRepository implements JpaRepository<Long, XEntity> {
}

最后,@Component,这是Spring中注册bean的通用形式,也就是说,Spring总是在寻找标记有@Component的bean来注册,那么@Service和@Repository都是@Component的特例,然而,组件的常见用例是当您制作一些纯技术性的东西而不是直接的业务案例时!比如格式化日期或处理特殊的请求序列化机制等等。

@Component
@Controller
@Repository
@Service
@RestController

这些都是StereoType注释。这对于在ioc容器中将我们的类制作为springbean非常有用,

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

In-spring框架提供了一些特殊类型的注释,称为原型注释。具体如下:-

@RestController- Declare at controller level.
@Controller – Declare at controller level.
@Component – Declare at Bean/entity level.
@Repository – Declare at DAO level.
@Service – Declare at BO level.

上面声明的注释是特殊的,因为当我们将<context:componentscan>添加到xxx-servlet.xml文件中时,spring将自动创建那些在上下文创建/加载阶段用上面的注释注释的类的对象。