@Component、@Repository和@Service注释是否可以在Spring中互换使用,或者它们除了充当符号设备之外,是否提供任何特定功能?
换句话说,如果我有一个Service类,并且我将注释从@Service更改为@Component,它的行为是否仍然相同?
或者注释是否也会影响类的行为和功能?
@Component、@Repository和@Service注释是否可以在Spring中互换使用,或者它们除了充当符号设备之外,是否提供任何特定功能?
换句话说,如果我有一个Service类,并且我将注释从@Service更改为@Component,它的行为是否仍然相同?
或者注释是否也会影响类的行为和功能?
当前回答
@Component
@Controller
@Repository
@Service
@RestController
这些都是StereoType注释。这对于在ioc容器中将我们的类制作为springbean非常有用,
其他回答
存储库和服务是组件注释的子级。所以,它们都是组件。存储库和服务只是扩展它。具体如何?服务只有意识形态上的区别:我们把它用于服务。存储库具有特定的异常处理程序。
它们几乎相同——所有这些都意味着这个类是一个Spring bean@Service、@Repository和@Controller是专门的@Components。您可以选择与他们一起执行特定操作。例如:
@springmvc使用控制器bean@存储库bean有资格进行持久性异常转换
另一件事是将组件语义上指定给不同的层。
@Component提供的一点是,您可以用它注释其他注释,然后以与@Service相同的方式使用它们。
例如,最近我做了:
@Component
@Scope("prototype")
public @interface ScheduledJob {..}
因此,所有用@ScheduledJob注释的类都是springbean,除此之外,它们还注册为石英作业。您只需要提供处理特定注释的代码。
@存储库@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.
来自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) |
即使我们交换@Component或@Repository或@service
它的行为是一样的,但一个方面是,如果我们使用component或@service,它们将无法捕获与DAO相关的特定异常,而不是Repository