我正在为 Rest Controller 使用可选参数,在我的例子中是为了区分要调用的方法:
@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();
}
为什么下面线程的最高投票响应提出“使用可选参数在方法内部导致条件逻辑实际上是适得其反的。”?
Why should Java 8's Optional not be used in arguments
我正是这样做的,并将其视为最具可读性和直接的解决方案。这种方法有什么不好?
最佳答案
使用Optional
作为@RequestParam
的唯一问题是性能以及使用Optional.OfNullable
创建Optional包装器并使用Optional解包。 get()
或使用 Optional.ifPresent()
检查。从功能角度来看,使用 Optional
看起来总是不错,但作为一个优秀的程序员,它是不必要的额外操作包装和展开。在 spring @RequestParam 中允许Optional
将参数声明为可选
By default, method parameters that use this annotation are required, but you can specify that a method parameter is optional by setting the @RequestParam annotation’s required flag to false or by declaring the argument with an java.util.Optional wrapper.
因此,您可以简单地使用 required==false
将这些 @RequestParam
设置为可选,并使用 if else 遵循相同的方法,您也可以使用 Objects.nonNull为了提高可读性,或者您也可以使用 defaultValue
@GetMapping("/cars")
@ResponseBody
public List<CarsDTO> getAllCarsByCat(@RequestParam(name="cat1", required=false) Integer cat1,
@RequestParam(name="cat2", required=false) Integer cat2) {
if (cat1!=null && cat2!=null)
return carsService.getAllCarsByCat1AndCat2(cat1, cat2);
else if (cat1!=null)
return carsService.getAllCarsByCat1(cat1);
else if (cat2!=null)
return carsService.getAllCarsByCat2(cat2);
else
return carsService.getAllCars();
}
关于java - Request Param 的可选参数是一种不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59480883/