10 java spring java-8 option-type
我在 Rest 控制器中使用可选参数,在我的例子中是为了区分要调用的方法:
@GetMapping("/cars")
@ResponseBody
public List<CarsDTO> getAllCarsByCat(@RequestParam Optional<Integer> cat1,
@RequestParam Optional<Integer> cat2) {
if (cat1.isPresent() && cat2.isPresent())
return carsService.getAllCarsByCat1AndCat2(cat1.get(), cat2.get());
else if (cat1.isPresent())
return carsService.getAllCarsByCat1(cat1.get());
else if (cat2.isPresent())
return carsService.getAllCarsByCat2(cat2.get());
else
return carsService.getAllCars();
}
Run Code Online (Sandbox Code Playgroud)
为什么下面线程的最高投票响应提出“使用可选参数在方法内部导致条件逻辑实际上是适得其反的。”?
我正是这样做的,并将其视为最具可读性和直接的解决方案。这种方法有什么不好?
Dea*_*ool 11
Optional
使用as 的唯一问题@RequestParam
是性能以及使用创建可选包装器Optional.OfNullable
以及使用解包Optional.get()
或使用检查Optional.ifPresent()
。从功能角度来看,它看起来总是很好用Optional
,但作为一个好的程序员,它是不必要的额外操作包装和展开。在spring中Optional
允许在@RequestParam中将param声明为可选
\n\n\n默认情况下,使用此注释的方法参数是必需的,但您可以通过将 @RequestParam 注释\xe2\x80\x99s required 标志设置为 false 或使用 java.util.Optional 声明参数来指定方法参数是可选的包装纸。
\n
因此,您可以简单地将它们设为@RequestParam
可选required==false
,并使用 if else 遵循相同的方法,您也可以使用Objects.nonNull以获得更高的可读性,或者您也可以使用defaultValue
@GetMapping("/cars")\n@ResponseBody\n public List<CarsDTO> getAllCarsByCat(@RequestParam(name="cat1", required=false) Integer cat1,\n @RequestParam(name="cat2", required=false) Integer cat2) {\n if (cat1!=null && cat2!=null)\n return carsService.getAllCarsByCat1AndCat2(cat1, cat2);\n else if (cat1!=null)\n return carsService.getAllCarsByCat1(cat1);\n else if (cat2!=null)\n return carsService.getAllCarsByCat2(cat2);\n else\n return carsService.getAllCars();\n\n }\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
9801 次 |
最近记录: |