@Component、@Repository和@Service注释是否可以在Spring中互换使用,或者它们除了充当符号设备之外,是否提供任何特定功能?
换句话说,如果我有一个Service类,并且我将注释从@Service更改为@Component,它的行为是否仍然相同?
或者注释是否也会影响类的行为和功能?
@Component、@Repository和@Service注释是否可以在Spring中互换使用,或者它们除了充当符号设备之外,是否提供任何特定功能?
换句话说,如果我有一个Service类,并且我将注释从@Service更改为@Component,它的行为是否仍然相同?
或者注释是否也会影响类的行为和功能?
当前回答
@Component、@Repository、@Controller和@Service注释之间的差异
@组件–通用,可跨应用程序使用@服务–在服务层级别注释类@控制器–注释表示层级别的类,主要用于SpringMVC。@Repository–在持久层注释类,它将充当数据库存储库。
@控制器=@Component(内部注释)+表示层功能@服务=@Component(内部注释)+服务层功能@分量=实际分量(豆类)@Repository=@Component(内部注释)+数据层特性(用于处理域bean)
其他回答
@存储库@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
@Controller
@Repository
@Service
@RestController
这些都是StereoType注释。这对于在ioc容器中将我们的类制作为springbean非常有用,
这里有足够好的答案来解释组件存储库服务注释之间的区别。我想分享@Controller和@RestController之间的区别
@控制器与RestController
@RestController(RestController):
此注释是@Controller的专用版本,它添加了@Controller和@ResponseBody自动注释。因此我们不必将@ResponseBody添加到映射方法中。这意味着@ResponseBody默认处于活动状态。如果使用@RestController,则无法返回视图(通过使用Spring/Spring Boot中的Viewresolver)@RestController还将响应自动转换为JSON/XML,因为@ResponseBody将返回的对象转换为可能在主体中的对象,例如JSON或XML
@控制器
@控制器用于将类标记为SpringMVC控制器。这注释只是@Component的一个专门版本允许基于类路径自动检测控制器类扫描。@控制器,您可以在SpringwebMVC中返回视图。
更详细的视图
用@Component注释其他组件,例如REST资源类。
@Component
public class AdressComp{
.......
...//some code here
}
@组件是任何Spring管理组件的通用原型。
@Controller、@Service和@Repository是@Component针对特定用例的专门化。
@弹簧中的部件