简体   繁体   English

有没有办法在spring-data-rest存储库方法上验证方法参数?

[英]Is there a way to validate method parameters on spring-data-rest repository methods?

For instance, I have a repository class like this. 例如,我有一个类似的存储库类。

@RepositoryRestResource
public interface FooRepository extends JpaRepository<Foo, Integer> {

  Optional<Foo> findByBarId(@Param("barId") Integer barId);

}

This generates a search endpoint with path http://hostname/foo/search/findByBarId{?fooId} 这将生成路径为http://hostname/foo/search/findByBarId{?fooId}的搜索端点

When I access this URL without any parameters, I get a 404 which I i think is okay. 当我不带任何参数访问此URL时,会得到一个404 ,我认为还可以。

However, I would rather send a 400 for this type or errors as my business would definitely need a parameter for this API. 但是,我宁愿为此类型发送400或错误消息,因为我的业务肯定需要为此API提供参数。

I tried using @javax.validation.constraints.NotNull 我尝试使用@javax.validation.constraints.NotNull

Optional<Foo> findByBarId(@Param("barId") @NotNull Integer barId);

as well as @org.springframework.lang.NonNull 以及@org.springframework.lang.NonNull

Optional<Foo> findByBarId(@Param("barId") @NonNull Integer barId);

Both annotations did not work. 两种注释均无效。 Of Course it doesn't work because these annotations by itself is just meta information which is not being taken into account by spring-framework. 当然,这是行不通的,因为这些注释本身只是元信息,spring-framework并未考虑这些信息。

The documentation didn't have anything showcased for parameter validation behaviour. 该文档没有展示任何有关参数验证行为的内容。 (They only speak about entity lifecycle validation ) (他们只谈论实体生命周期验证

Is there any straightforward way I can achieve such behaviour? 有什么简单的方法可以实现这种行为?

I use spring-boot 2.0.4 if that helps. 我可以使用spring-boot 2.0.4。

You can write a RepositoryRestController to run specific business to customize your endpoints. 您可以编写RepositoryRestController来运行特定业务以自定义端点。

Here is an example for your case, you can customize it as well : 这是您的案例的示例,您也可以对其进行自定义:

@RepositoryRestController
public class FooController {

    FooRepository fooRepository;

    @Autowired
    public FooController(FooRepository fooRepository) {
        this.fooRepository = fooRepository;
    }

    @GetMapping(path = "/foo")
    public ResponseEntity getfoo(@RequestParam("barId") Optional<Integer> barId) {
        if (!barId.isPresent()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }

        Optional<Foo> foo = fooRepository.findByBarId(barId.get());

        return ResponseEntity.ok(foo);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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