Common Annotations in Spring

Contents

Common Annotations in Spring

@Component & @Repository & @Service

  • @Component: generic annotation, Spring will automatically detect and register it as a bean

  • @Repository: used to annotate DAO class, subclass of @Component. It is used to mark the DAO layer, indicating that the class is used to perform database operations, and the exception translation layer is automatically generated by Spring at runtime, which is convenient for developers to handle exceptions.

  • @Service: used to annotate service class, subclass of @Component, it is used to mark the service layer, the service layer is the same as the business layer, and the service layer is used to encapsulate business logic.

They can be used interchangeably, they all registe the class as bean

@Autowired, @Qualifier, @Primary

See Dependency Injection

@PathVariable & @RequestParam

They both can be used to get the parameters from the request, but they are used in different scenarios.

  • @PathVariable: used to get the parameters from the URL. In Spring, we can customize the URL, such as http://localhost:8080/user/{id}, the {id} is the parameter, we can use @PathVariable to get the parameter.

  • @RequestParam: used to get the parameters from the request body (which is the form data), such as http://localhost:8080/user?id=1, the 1 is the parameter, we can use @RequestParam to get the parameter.

Contents