简体   繁体   中英

Spring Boot Optional Path Variables

In our Spring Boot app, we use separate endpoints for optional parameters as shown below:

// two methods - not recommended
@GetMapping("/todos/{id}")
public @ResponseBody Todo fetchTodoById(@PathVariable Long id) {
    return todoRespository.findById(id);
}

@GetMapping("/todos")
public @ResponseBody List<Todo> fetchAllTodos() {
    return todoRespository.findAll();
}

I know that this approach can quickly lead to a large number of (almost) duplicate code-blocks.

To fix this, I can use one of the following approaches:

@GetMapping(value = {"/todos", "/todos/{id}"})
public @ResponseBody Object fetchTodos(@PathVariable(required = false) Long id) {
    if (id == null) {
        return todoRespository.findById(id);
    } else {
        return todoRespository.findAll();
    }
}

and a similar way using Java Optional . However, even if it seems better, I think it may be much better to use a separate endpoint. So, which one is proper approach?

  • Endpoint /todos/{id} returns one ToDo object.
  • Endpoint /todos returns the List of ToDo objects. According to SOLID principle each class or method must do only one thing (return an object or list of objects). So you need to separate methods. I think using optional pathVariable is a bad practice.

I know that this approach can quickly lead to a large number of (almost) duplicate code-blocks.

well it is not exactly true that code is duplicate. The parameter is not exactly separated. The endpoint with the parameter leads to aa given item whereas the second endpoint leads to a list of elements. Even the return type is not the same although you may not see it since you return object.

Therefore, the first method (2 different endpoint handlers) is a far better approach than the second one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM