@Component、@Repository和@Service注释是否可以在Spring中互换使用,或者它们除了充当符号设备之外,是否提供任何特定功能?
换句话说,如果我有一个Service类,并且我将注释从@Service更改为@Component,它的行为是否仍然相同?
或者注释是否也会影响类的行为和功能?
@Component、@Repository和@Service注释是否可以在Spring中互换使用,或者它们除了充当符号设备之外,是否提供任何特定功能?
换句话说,如果我有一个Service类,并且我将注释从@Service更改为@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.
其他回答
@Component、@Service、@Controller、@Repository之间没有区别。@Component是表示MVC组件的泛型注释。但作为MVC应用程序的一部分,将有几个组件,如服务层组件、持久层组件和表示层组件。所以为了区分它们,Spring的人也给出了其他三个注释。
表示持久层组件:@Repository表示服务层组件:@service表示表示层组件:@Controller否则,您可以对所有组件使用@Component。
所有这些注释都是立体类型的注释类型,这三种注释之间的区别是
如果我们添加@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编写配置
@组件在配置类中充当@Bean注释,在spring上下文中注册Bean。它也是@Service、@Repository和@Controller注释的父级。
@服务,扩展了@Component注释,只有命名差异。
@Repository-扩展@Component注释并将所有数据库异常转换为DataAccessException。
@控制器-在MVC模式中充当控制器。分派器将扫描这些带注释的类以查找映射方法,检测@RequestMapping注释。