Difference between path and value attributes in @RequestMapping annotation

后端 未结 3 1558
旧巷少年郎
旧巷少年郎 2021-01-07 16:54

What is the difference between below two attributes and which one to use when?

@GetMapping(path = \"/usr/{userId}\")         


        
3条回答
  •  轮回少年
    2021-01-07 17:27

    @GetMapping is a shorthand for @RequestMapping(method = RequestMethod.GET).

    In your case. @GetMapping(path = "/usr/{userId}") is a shorthand for @RequestMapping(value = "/usr/{userId}", method = RequestMethod.GET).

    Both are equivalent. Prefer using shorthand @GetMapping over the more verbose alternative. One thing that you can do with @RequestMapping which you can't with @GetMapping is to provide multiple request methods.

    @RequestMapping(value = "/path", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT)
    public void handleRequet() {
    
    }
    

    Use @RequestMapping when you need to provide multiple Http verbs.

    Another usage of @RequestMapping is when you need to provide a top level path for a controller. For e.g.

    @RestController
    @RequestMapping("/users")
    public class UserController {
    
        @PostMapping
        public void createUser(Request request) {
            // POST /users
            // create a user
        }
    
        @GetMapping
        public Users getUsers(Request request) {
            // GET /users
            // get users
        }
    
        @GetMapping("/{id}")
        public Users getUserById(@PathVariable long id) {
            // GET /users/1
            // get user by id
        }
    }
    

提交回复
热议问题