在@RepositoryRestResource 中导出 PATCH/PUT 但不导出 POST

Export PATCH/PUT but not POST in @RepositoryRestResource

我正在使用 spring-data-rest 并通过存储库为我的实体公开端点。
实体之一应该可以用 PATCH/PUT 方法更新,但不可能用 POST 方法创建新实例。

这两个操作似乎都通过 save 方法,因此似乎无法仅导出部分请求:

@RestResource(exported = ?)
@Override
<S extends User> S save(S s);

实现该目标的最佳方法是什么?
我应该覆盖 save 方法吗?写自定义Validator

您可以使用

  • Validators 并向 errors 参数添加错误

  • Event Handlers,抛出异常并由 @ControllerAdvice 捕获,returns 自定义消息或 HTTP 状态代码

  • Custom Controllers and handle the request manually. See this answer:

前两个要听BeforeCreateEvent.

一种解决方案是扩展 WebSecurityConfigurerAdapter(在 spring-security-config 中可用)以拒绝 POST 请求访问目标 url :

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(HttpMethod.POST, "/path_to_target_url").denyAll();
    }

}

任何 POST 到目标 URL 的尝试都将失败并出现 401 Unauthorized 错误。