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

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

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


当前回答

@组件、@Repository、@Service、@Controller:

@Component是由Spring@Repository、@Service和@Controller管理的组件的通用原型,是用于更具体用途的@Component专用化:

@持久性存储库@服务和交易服务@MVC控制器的控制器

为什么在@Component上使用@Repository、@Service、@Controller?我们可以用@component标记我们的组件类,但如果相反,我们使用适应预期功能的替代方法。我们的类更适合每种特定情况下的预期功能。

用@Repository注释的类使用org.springframework.dao.DataAccessException具有更好的翻译和可读错误处理。非常适合实现访问数据的组件(DataAccessObject或dao)。

带有@Controller的注释类在SpringWebMVC应用程序中扮演控制器角色

带有@Service的注释类在业务逻辑服务中发挥作用,例如DAO Manager(Facade)的Facade模式和事务处理

其他回答

即使它的行为相同,但这利用了应用程序的许多软件开发原则,也很少有这样的例子:

- Single Responsibility
- Open Closed Principal 

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

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

如果我们添加@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注释将默认存在于类的顶部

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

Spring2.5引入了更多的原型注释:@Component、@Service和@Controller@组件充当任何Spring管理组件的通用原型;而@Repository、@Service和@Controller作为@Component的特殊化,用于更具体的用例(例如,分别在持久性、服务和表示层)。这意味着你可以用@component来注释你的组件类,但是通过用@Repository、@Service或@Controller来注释它们,你的类更适合由工具处理或与方面关联。例如,这些原型注释是切入点的理想目标。当然,@Repository、@Service和@Controller也有可能在未来的Spring Framework版本中携带额外的语义。因此,如果您在服务层使用@Component或@Service之间做出决定,@Service显然是更好的选择。类似地,如上所述,@Repository已经被支持作为持久层中自动异常转换的标记。@组件–表示自动扫描组件。@Repository–表示持久层中的DAO组件。@服务–表示业务层中的服务组件。@控制器–表示表示层中的控制器组件。

参考:-Spring Documentation-Classpath扫描、托管组件和使用Java编写配置